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
SUFIAG/Hotel-Reservation-System-Java-And-PHP
src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Customer_Choose_Option_Screen.java
[ { "identifier": "Customer", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/Customer.java", "snippet": "public class Customer {\n private String name, address, email, password, phoneNo, CNIC, accountNo, dp;\n private int ID;\n\n //constructors\n public Customer() {\n }\n public Customer(int id, String mail, String pass, String Name,\n String add, String phone, String cnic, String accNo, String dp) {\n ID = id;\n name = Name;\n address = add;\n phoneNo = phone;\n CNIC = cnic;\n accountNo = accNo;\n email = mail;\n password = pass;\n this.dp = dp;\n }\n\n //getters\n public int getID() {\n return ID;\n }\n public String getEmail() {\n return email;\n }\n public String getAccountNo() {\n return accountNo;\n }\n public String getCNIC() {\n return CNIC;\n }\n public String getPhoneNo() {\n return phoneNo;\n }\n public String getAddress() {\n return address;\n }\n public String getName() {\n return name;\n }\n public String getPassword() {\n return password;\n }\n public String getDp() { return dp; }\n\n //setters\n public void setAccountNo(String accountNo) {\n this.accountNo = accountNo;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public void setCNIC(String CNIC) {\n this.CNIC = CNIC;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n public void setID(int ID) {\n this.ID = ID;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void setPhoneNo(String phoneNo) {\n this.phoneNo = phoneNo;\n }\n public void setPassword(String password) {\n this.password = password;\n }\n public void setDp(String dp) { this.dp = dp; }\n}" }, { "identifier": "HRS", "path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/HRS.java", "snippet": "public class HRS {\n private Vector<Customer> customers;\n private Vector<Hotel> hotels;\n private Vector<Vendor> vendors;\n private writerAndReader readAndWrite;\n private static HRS hrs;\n\n // constructor\n private HRS(Context context) {\n // initializing data members\n customers = new Vector<>();\n hotels = new Vector<>();\n vendors = new Vector<>();\n readAndWrite = new writerAndReader(context);\n\n // fetching old data from server\n readAndWrite.getCustomersFromServer(customers);\n readAndWrite.getVendorsFromServer(vendors);\n readAndWrite.getHotelsFromServer(hotels, new VolleyCallBack() {\n @Override\n public void onSuccess() {\n for (int i = 0; i < hotels.size(); ++i) {\n readAndWrite.getRoomsFromServer(hotels.get(i));\n }\n readAndWrite.getReservationsFromServer(hotels);\n }\n });\n }\n\n // getters\n public static HRS getInstance(Context context) {\n if (hrs == null) {\n hrs = new HRS(context);\n }\n return hrs;\n }\n public Vector<Customer> getCustomers() {\n return customers;\n }\n public Vector<Hotel> getHotels() {\n return hotels;\n }\n public Vector<Vendor> getVendors() {\n return vendors;\n }\n public writerAndReader getReadAndWrite() {\n return readAndWrite;\n }\n\n // setters\n public void setCustomers(Vector<Customer> customers) {\n this.customers = customers;\n }\n public void setHotels(Vector<Hotel> hotels) {\n this.hotels = hotels;\n }\n public void setReadAndWrite(writerAndReader readAndWrite) {\n this.readAndWrite = readAndWrite;\n }\n public void setVendors(Vector<Vendor> vendors) { this.vendors = vendors; }\n\n // function to check if customer with same email already exists or not\n public boolean validateCustomerEmail(String email) {\n for (int i = 0; i < customers.size(); ++i) {\n if (email.equals(customers.get(i).getEmail())) {\n return false;\n }\n }\n return true;\n }\n\n // function to check if customer has logged in correctly or not\n public boolean validateCustomerAccount(String email, String pass) {\n for (int i = 0; i < customers.size(); ++i) {\n if (email.equals(customers.get(i).getEmail()) && customers.get(i).getPassword().equals(pass)) {\n return true;\n }\n }\n return false;\n }\n\n // function to check if vendor with same email already exists or not\n public boolean validateVendorEmail(String email) {\n for (int i = 0; i < vendors.size(); ++i) {\n if (email.equals(vendors.get(i).getEmail())) {\n return false;\n }\n }\n return true;\n }\n\n // function to check if vendor has logged in correctly or not\n public boolean validateVendorAccount(String email, String pass) {\n for (int i = 0; i < vendors.size(); ++i) {\n if (email.equals(vendors.get(i).getEmail()) && vendors.get(i).getPassword().equals(pass)) {\n return true;\n }\n }\n return false;\n }\n\n // function to check if hotel with same name and location already exists or not\n public boolean validateHotel(String name, String loc) {\n for (int i = 0; i < hotels.size(); ++i) {\n if (name.equals(hotels.get(i).getName()) && loc.equals(hotels.get(i).getLocation())) {\n return false;\n }\n }\n return true;\n }\n\n // function for customer registration\n public void registerCustomer(String name, String email, String pass,\n String add, String phone, String cnic, String accNo, Uri dp,\n VolleyCallBack volleyCallBack) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < customers.size(); ++i) {\n if (customers.get(i).getID() > ID) {\n ID = customers.get(i).getID();\n }\n }\n ID++;\n\n //registering customer\n Customer c = new Customer(ID, email, pass, name, add, phone, cnic, accNo, \"\");\n readAndWrite.insertCustomerDataIntoServer(c, dp, volleyCallBack);\n customers.add(c);\n }\n\n //function for vendor registration\n public void registerVendor(String name, String email, String pass,\n String add, String phone, String cnic, String accNo, Uri dp,\n VolleyCallBack volleyCallBack) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < vendors.size(); ++i) {\n if (vendors.get(i).getID() > ID) {\n ID = vendors.get(i).getID();\n }\n }\n ID++;\n\n //registering vendor\n Vendor v = new Vendor(ID, email, pass, name, add, phone, cnic, accNo, \"\");\n readAndWrite.insertVendorDataIntoServer(v, dp, volleyCallBack);\n vendors.add(v);\n }\n\n //function for hotel registration\n public void registerHotel(String name, String add, String loc, String singleRooms, String doubleRooms,\n String singleRoomPrice, String doubleRoomPrice, String registered_by) {\n int ID = 0;\n\n //getting maximum ID\n for (int i = 0; i < hotels.size(); ++i) {\n if (hotels.get(i).getID() > ID) {\n ID = hotels.get(i).getID();\n }\n }\n ID++;\n\n //registering hotel\n Hotel h = new Hotel(ID, name, add, loc, singleRooms, doubleRooms, singleRoomPrice, doubleRoomPrice, registered_by);\n hotels.add(h);\n readAndWrite.insertHotelIntoServer(h);\n readAndWrite.insertRoomsIntoServer(h);\n }\n\n //function for hotel booking\n public Vector<Hotel> getHotels(String location, String noOfPersons, LocalDate checkInDate, String roomType, boolean both) {\n Vector<Hotel> searchedHotels = new Vector<>();\n for (int i = 0; i < hotels.size(); ++i) {\n if (hotels.get(i).getLocation().equals(location)) {\n Hotel h1 = new Hotel();\n h1.setAddress(hotels.get(i).getAddress());\n h1.setName(hotels.get(i).getName());\n h1.setID(hotels.get(i).getID());\n h1.setRooms(hotels.get(i).getRooms());\n h1.setTotalRooms(hotels.get(i).getTotalRooms());\n h1.setLocation(hotels.get(i).getLocation());\n h1.setDoubleRoomPrice(hotels.get(i).getDoubleRoomPrice());\n h1.setDoubleRooms(hotels.get(i).getDoubleRooms());\n h1.setSingleRooms(hotels.get(i).getSingleRooms());\n h1.setSingleRoomPrice(hotels.get(i).getSingleRoomPrice());\n h1.setReservations(hotels.get(i).getReservations());\n Vector<Room> r;\n r = hotels.get(i).getRooms(noOfPersons, checkInDate, roomType, both);\n if (r != null) {\n h1.setRooms(r);\n searchedHotels.add(h1);\n }\n }\n }\n return searchedHotels;\n }\n\n //function for reserving room\n public void makeReservation(String email, Hotel h, LocalDate checkInDate, LocalDate checkOutDate) {\n //finding customer and calling for reservation\n for (int i = 0; i < customers.size(); ++i) {\n if (customers.get(i).getEmail().equals(email)) {\n Reservation reservation = h.reserveRoom(checkInDate, checkOutDate, customers.get(i), hotels);\n readAndWrite.truncateATable(\"rooms\", new VolleyCallBack() {\n @Override\n public void onSuccess() {\n for (int j = 0; j < hotels.size(); ++j) {\n readAndWrite.insertRoomsIntoServer(hotels.get(j));\n }\n }\n });\n if (reservation != null) {\n readAndWrite.insertReservationIntoServer(reservation);\n }\n break;\n }\n }\n }\n\n // Search Customer On Email Basis\n public Customer searchCustomerByMail(String Email){\n for(int i=0;i<customers.size();++i){\n if(Email.equals(customers.get(i).getEmail())){\n return customers.get(i);\n }\n }\n return null;\n }\n // Search Vendor On Email Basis\n public Vendor searchVendorByMail(String Email){\n for(int i=0;i<vendors.size();++i){\n if(Email.equals(vendors.get(i).getEmail())){\n return vendors.get(i);\n }\n }\n return null;\n }\n // Search Hotel On Name and Location Basis\n public Hotel searchHotelByNameLoc(String Name,String Loc){\n for(int i=0;i<hotels.size();++i){\n if(Name.equals(hotels.get(i).getName()) && Loc.equals(hotels.get(i).getLocation())){\n return hotels.get(i);\n }\n }\n return null;\n }\n\n // Login Customer On Email and Password Basis\n public Boolean LoginCustomer(String Email,String Pass){\n for(int i=0;i<customers.size();++i){\n if(Email.equals(customers.get(i).getEmail()) && Pass.equals(customers.get(i).getPassword())){\n return true;\n }\n }\n return false;\n }\n // Login Vendor On Email and Password Basis\n public Boolean LoginVendor(String Email,String Pass){\n for(int i=0;i<vendors.size();++i){\n if(Email.equals(vendors.get(i).getEmail()) && Pass.equals(vendors.get(i).getPassword())){\n return true;\n }\n }\n return false;\n }\n}" } ]
import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import com.sameetasadullah.i180479_i180531.R; import com.sameetasadullah.i180479_i180531.logicLayer.Customer; import com.sameetasadullah.i180479_i180531.logicLayer.HRS; import com.squareup.picasso.Picasso; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import de.hdodenhof.circleimageview.CircleImageView;
3,164
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Customer_Choose_Option_Screen extends AppCompatActivity { RelativeLayout reserve_hotel, view_old_reservations; CircleImageView dp;
package com.sameetasadullah.i180479_i180531.presentationLayer; public class Customer_Choose_Option_Screen extends AppCompatActivity { RelativeLayout reserve_hotel, view_old_reservations; CircleImageView dp;
HRS hrs;
1
2023-10-25 20:58:45+00:00
4k
MachineMC/Cogwheel
cogwheel-yaml/src/main/java/org/machinemc/cogwheel/yaml/YamlConfigSerializer.java
[ { "identifier": "ConfigAdapter", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigAdapter.java", "snippet": "public abstract class ConfigAdapter<T> {\n\n public abstract ConfigAdapter<T> newConfigInstance();\n\n public abstract T getConfig();\n\n public abstract Set<String> keys();\n\n public boolean containsKey(String key) {\n return keys().contains(key);\n }\n\n public Map<String, Object> getAsMap() {\n return new ConfigAdapterMap(this);\n }\n\n public abstract Optional<Number> getNumber(String key);\n\n public abstract Optional<String> getString(String key);\n\n public abstract Optional<Boolean> getBoolean(String key);\n\n public abstract Optional<Object[]> getArray(String key);\n\n public <C extends Collection<Object>> Optional<C> getCollection(String key, Supplier<C> collectionFactory) {\n return getArray(key).map(array -> Arrays.stream(array).collect(Collectors.toCollection(collectionFactory)));\n }\n\n public abstract Optional<Map<String, Object>> getMap(String key);\n\n public Optional<Object> getPrimitive(String key) {\n if (!containsKey(key)) return Optional.empty();\n Object object = getNumber(key).orElse(null);\n if (object == null) object = getString(key).orElse(null);\n if (object == null) object = getBoolean(key).orElse(null);\n if (object == null) object = getArray(key).orElse(null);\n if (object == null) object = getMap(key).orElse(null);\n return Optional.ofNullable(object);\n }\n\n public abstract void setNull(String key);\n\n public abstract void setNumber(String key, Number number);\n\n public abstract void setString(String key, String string);\n\n public abstract void setBoolean(String key, Boolean bool);\n\n public abstract void setArray(String key, Object[] array);\n\n public void setCollection(String key, Collection<?> collection) {\n setArray(key, collection.toArray());\n }\n\n public abstract void setMap(String key, Map<String, Object> map);\n\n public abstract void setConfig(String key, T config);\n\n public abstract void setComments(String key, @Nullable String[] comments);\n\n public abstract void setInlineComment(String key, String comment);\n\n @SuppressWarnings(\"unchecked\")\n public boolean setPrimitive(String key, Object object) {\n switch (object) {\n case null -> setNull(key);\n case Number number -> setNumber(key, number);\n case String string -> setString(key, string);\n case Boolean bool -> setBoolean(key, bool);\n case byte[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case short[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case int[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case long[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case float[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case double[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case boolean[] array -> setArray(key, ArrayUtils.wrapArray(array));\n case Object[] array -> setArray(key, array);\n case Collection<?> collection -> setCollection(key, collection);\n case Map<?, ?> map -> setMap(key, (Map<String, Object>) map);\n case ConfigAdapter<?> adapter -> setPrimitive(key, adapter.getConfig());\n default -> {\n if (!getConfig().getClass().isInstance(object)) return false;\n setConfig(key, (T) object);\n }\n }\n return true;\n }\n\n public abstract void load(T t);\n\n public void load(Map<String, Object> map) {\n map.forEach(this::setPrimitive);\n }\n\n}" }, { "identifier": "ConfigProperties", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigProperties.java", "snippet": "public class ConfigProperties {\n\n SerializerRegistry serializerRegistry = new SerializerRegistry();\n ClassInitiator classInitiator = ClassInitiator.DEFAULT;\n KeyFormatter keyFormatter = new IdentifierKeyFormatter();\n NodeFilter nodeFilter = NodeFilter.DEFAULT;\n FieldExtractor fieldExtractor = FieldExtractor.DEFAULT;\n RecordDisassembler recordDisassembler = RecordDisassembler.DEFAULT;\n ErrorHandler errorHandler = ErrorHandler.NORMAL;\n\n public SerializerRegistry serializerRegistry() {\n return serializerRegistry;\n }\n\n public ClassInitiator classInitiator() {\n return classInitiator;\n }\n\n public KeyFormatter keyFormatter() {\n return keyFormatter;\n }\n\n public NodeFilter nodeFilter() {\n return nodeFilter;\n }\n\n public FieldExtractor fieldExtractor() {\n return fieldExtractor;\n }\n\n public RecordDisassembler recordDisassembler() {\n return recordDisassembler;\n }\n\n public ErrorHandler errorHandler() {\n return errorHandler;\n }\n\n}" }, { "identifier": "ConfigSerializer", "path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/config/ConfigSerializer.java", "snippet": "public abstract class ConfigSerializer<T> {\n\n private final ConfigProperties properties;\n\n protected ConfigSerializer(ConfigProperties properties) {\n this.properties = properties;\n }\n\n protected abstract ConfigAdapter<T> newAdapter();\n\n protected abstract void save(File file, T t);\n\n public void save(File file, Configuration configuration) {\n save(file, serialize(configuration).getConfig());\n }\n\n @SuppressWarnings(\"unchecked\")\n public <C extends Configuration> ConfigAdapter<T> serialize(C configuration) {\n Serializers.ConfigurationSerializer<C> serializer = newSerializer(configuration);\n return (ConfigAdapter<T>) Serializer.serialize(serializer, configuration);\n }\n\n public abstract T load(File file);\n\n public <C extends Configuration> C load(File file, Class<C> configurationClass) {\n return load(load(file), configurationClass);\n }\n\n public <C extends Configuration> C load(T config, Class<C> configurationClass) {\n ConfigAdapter<T> adapter = newAdapter();\n adapter.load(config);\n return load(adapter, configurationClass);\n }\n\n private <C extends Configuration> C load(ConfigAdapter<T> adapter, Class<C> configurationClass) {\n SerializerContext context = newContext();\n Serializers.ConfigurationSerializer<C> serializer =\n new Serializers.ConfigurationSerializer<>(configurationClass, context);\n C configuration = Serializer.deserialize(serializer, adapter, context.errorContainer());\n if (configuration == null)\n throw new IllegalArgumentException(\"Could not load configuration: \" + configurationClass);\n return configuration;\n }\n\n @SuppressWarnings(\"unchecked\")\n private <C extends Configuration> Serializers.ConfigurationSerializer<C> newSerializer(C configuration) {\n return (Serializers.ConfigurationSerializer<C>) newSerializer(configuration.getClass());\n }\n\n private <C extends Configuration> Serializers.ConfigurationSerializer<C> newSerializer(Class<C> configurationClass) {\n return new Serializers.ConfigurationSerializer<>(configurationClass, newContext());\n }\n\n private SerializerContext newContext() {\n return new SerializerContext(properties, this::newAdapter);\n }\n\n public ConfigProperties getProperties() {\n return properties;\n }\n\n public <P extends ConfigProperties> P getProperties(Class<P> type) {\n return type.cast(getProperties());\n }\n\n protected abstract static class Builder<S extends ConfigSerializer<?>, P extends ConfigProperties, B extends Builder<S, P, B>> {\n\n protected final P properties;\n\n protected Builder(P properties) {\n this.properties = properties;\n }\n\n public B registry(SerializerRegistry registry) {\n properties.serializerRegistry = registry;\n return getThis();\n }\n\n public <T> B addSerializer(Class<T> type, Class<? extends T>[] subtypes, Serializer<T> serializer) {\n properties.serializerRegistry().addSerializer(type, subtypes, serializer);\n return getThis();\n }\n\n public <T> B addSerializer(Class<T> type, Serializer<T> serializer) {\n properties.serializerRegistry().addSerializer(type, serializer);\n return getThis();\n }\n\n public <T> B addSerializer(Class<T> type, Class<? extends T>[] subtypes, SerializerFactory<T> serializer) {\n properties.serializerRegistry().addSerializer(type, subtypes, serializer);\n return getThis();\n }\n\n public <T> B addSerializer(Class<T> type, SerializerFactory<T> serializer) {\n properties.serializerRegistry().addSerializer(type, serializer);\n return getThis();\n }\n\n public B classInitiator(ClassInitiator classInitiator) {\n properties.classInitiator = classInitiator;\n return getThis();\n }\n\n public B keyFormatter(KeyFormatter keyFormatter) {\n properties.keyFormatter = keyFormatter;\n return getThis();\n }\n\n public B nodeFilter(NodeFilter nodeFilter) {\n properties.nodeFilter = nodeFilter;\n return getThis();\n }\n\n public B fieldExtractor(FieldExtractor fieldExtractor) {\n properties.fieldExtractor = fieldExtractor;\n return getThis();\n }\n\n public B recordDisassembler(RecordDisassembler recordDisassembler) {\n properties.recordDisassembler = recordDisassembler;\n return getThis();\n }\n\n public B errorHandler(ErrorHandler errorHandler) {\n properties.errorHandler = errorHandler;\n return getThis();\n }\n\n protected abstract B getThis();\n\n protected abstract S build();\n\n }\n\n}" }, { "identifier": "YamlObject", "path": "cogwheel-yaml/src/main/java/org/machinemc/cogwheel/yaml/wrapper/YamlObject.java", "snippet": "public non-sealed class YamlObject extends YamlElement {\n\n private final Map<String, YamlElement> members = new LinkedHashMap<>();\n\n public YamlObject() {\n }\n\n @Override\n public YamlObject deepCopy() {\n YamlObject result = new YamlObject();\n for (Map.Entry<String, YamlElement> entry : members.entrySet()) {\n result.add(entry.getKey(), entry.getValue().deepCopy());\n }\n copyComments(result);\n return result;\n }\n\n @Override\n public Map<String, Object> asRawObject() {\n Map<String, Object> map = new LinkedHashMap<>();\n for (Map.Entry<String, YamlElement> entry : members.entrySet())\n map.put(entry.getKey(), entry.getValue().asRawObject());\n return map;\n }\n\n public void add(String property, YamlElement value) {\n members.put(property, value == null ? new YamlNull() : value);\n }\n\n public YamlElement remove(String property) {\n return members.remove(property);\n }\n\n public void addProperty(String property, String value) {\n add(property, value == null ? new YamlNull() : new YamlPrimitive(value));\n }\n\n public void addProperty(String property, Number value) {\n add(property, value == null ? new YamlNull() : new YamlPrimitive(value));\n }\n\n public void addProperty(String property, Boolean value) {\n add(property, value == null ? new YamlNull() : new YamlPrimitive(value));\n }\n\n public void addProperty(String property, Character value) {\n add(property, value == null ? new YamlNull() : new YamlPrimitive(value));\n }\n\n public Set<Map.Entry<String, YamlElement>> entrySet() {\n return members.entrySet();\n }\n\n public Set<String> keySet() {\n return members.keySet();\n }\n\n public int size() {\n return members.size();\n }\n\n public boolean isEmpty() {\n return members.isEmpty();\n }\n\n public boolean has(String memberName) {\n return members.containsKey(memberName);\n }\n\n public YamlElement get(String memberName) {\n return members.get(memberName);\n }\n\n public YamlPrimitive getAsYamlPrimitive(String memberName) {\n return (YamlPrimitive) members.get(memberName);\n }\n\n public YamlArray getAsYamlArray(String memberName) {\n return (YamlArray) members.get(memberName);\n }\n\n public YamlObject getAsYamlObject(String memberName) {\n return (YamlObject) members.get(memberName);\n }\n\n public Map<String, YamlElement> asMap() {\n return Collections.unmodifiableMap(members);\n }\n\n @Override\n public boolean equals(Object o) {\n return (o == this) || (o instanceof YamlObject && ((YamlObject) o).members.equals(members));\n }\n\n @Override\n public int hashCode() {\n return members.hashCode();\n }\n\n public static YamlObject of(Map<String, ?> map) {\n YamlObject yamlObject = new YamlObject();\n map.forEach((key, value) -> yamlObject.add(key, YamlElement.of(value)));\n return yamlObject;\n }\n\n}" } ]
import org.machinemc.cogwheel.config.ConfigAdapter; import org.machinemc.cogwheel.config.ConfigProperties; import org.machinemc.cogwheel.config.ConfigSerializer; import org.machinemc.cogwheel.yaml.wrapper.YamlObject; import org.snakeyaml.engine.v2.api.Dump; import org.snakeyaml.engine.v2.api.Load; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;
3,193
package org.machinemc.cogwheel.yaml; public class YamlConfigSerializer extends ConfigSerializer<YamlObject> { protected YamlConfigSerializer(ConfigProperties properties) { super(properties); } @Override
package org.machinemc.cogwheel.yaml; public class YamlConfigSerializer extends ConfigSerializer<YamlObject> { protected YamlConfigSerializer(ConfigProperties properties) { super(properties); } @Override
protected ConfigAdapter<YamlObject> newAdapter() {
0
2023-10-25 11:31:02+00:00
4k
F4pl0/iex-cloud-java
src/main/java/io/github/f4pl0/companydata/CompanyData.java
[ { "identifier": "IEXHttpClient", "path": "src/main/java/io/github/f4pl0/IEXHttpClient.java", "snippet": "public class IEXHttpClient {\n private static IEXHttpClient instance;\n @IEXConfiguration\n private IEXCloudConfig config;\n\n private final CloseableHttpClient httpClient;\n\n private IEXHttpClient() {\n this.httpClient = HttpClients.createDefault();\n }\n\n @SneakyThrows\n public CloseableHttpResponse execute(String requestUri) {\n URI uri = new URIBuilder(config.getBaseEndpoint() + requestUri)\n .addParameter(\"token\", config.getPublishableToken())\n .build();\n\n HttpGet request = new HttpGet(uri);\n\n CloseableHttpResponse response = httpClient.execute(request);\n\n if (response.getStatusLine().getStatusCode() >= 400) {\n throw new IOException(\"Request failed: \" + response.getStatusLine());\n }\n\n return response;\n }\n\n public static IEXHttpClient getInstance() {\n if (instance == null) {\n instance = new IEXHttpClient();\n }\n return instance;\n }\n}" }, { "identifier": "IEXCompanyCeoCompensation", "path": "src/main/java/io/github/f4pl0/companydata/data/IEXCompanyCeoCompensation.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class IEXCompanyCeoCompensation {\n private String symbol;\n private String name;\n private String companyName;\n private String location;\n private long salary;\n private long bonus;\n private long stockAwards;\n private long optionAwards;\n private long nonEquityIncentives;\n private long pensionAndDeferred;\n private long otherComp;\n private long total;\n private String year;\n}" }, { "identifier": "IEXCompanyData", "path": "src/main/java/io/github/f4pl0/companydata/data/IEXCompanyData.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class IEXCompanyData {\n private String address;\n private String address2;\n private String ceo;\n private String city;\n private String companyName;\n private String country;\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd\")\n private Date date;\n private int employees;\n private String exchange;\n private String exchangeCode;\n private String industry;\n private String issuetype;\n private String longDescription;\n private long marketcap;\n private String phone;\n private String primarySicCode;\n private String sector;\n private String securityName;\n private String securityType;\n private String shortDescription;\n private String state;\n private String symbol;\n private String website;\n private String zip;\n private String id;\n private String key;\n private String subkey;\n private long updated;\n}" }, { "identifier": "IEXCompanyLogo", "path": "src/main/java/io/github/f4pl0/companydata/data/IEXCompanyLogo.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class IEXCompanyLogo {\n private String url;\n}" }, { "identifier": "IEXTradeDate", "path": "src/main/java/io/github/f4pl0/reference/data/IEXTradeDate.java", "snippet": "public class IEXTradeDate {\n /**\n * Trade date\n */\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd\")\n public String date;\n\n /**\n * Settlement date\n */\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd\")\n public String settlementDate;\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import io.github.f4pl0.IEXHttpClient; import io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation; import io.github.f4pl0.companydata.data.IEXCompanyData; import io.github.f4pl0.companydata.data.IEXCompanyLogo; import io.github.f4pl0.reference.data.IEXTradeDate; import lombok.NonNull; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List;
2,666
package io.github.f4pl0.companydata; public class CompanyData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyData} object. */ public IEXCompanyData companyData(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + encodedSymbol); List<IEXCompanyData> data = mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); return data.get(0); } /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyData(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + encodedSymbol); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol, int last) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + encodedSymbol + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols, int last) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + joinedSymbols + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * CEO Compensation * * <p>Returns the latest compensation information for the CEO of the company matching the symbol.</p> * * @see <a href="https://iexcloud.io/docs/core/ceo-compensation#ceo-compensation">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation} object. */ public IEXCompanyCeoCompensation companyCeoCompensation(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/stock/" + encodedSymbol + "/ceo-compensation"); return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyCeoCompensation.class); } /** * Company Logo * * <p>Returns a logo (if available) for the company.</p> * * @see <a href="https://iexcloud.io/docs/core/company-logo#company-logo">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyLogo} object. */
package io.github.f4pl0.companydata; public class CompanyData { private final IEXHttpClient httpClient = IEXHttpClient.getInstance(); private final ObjectMapper mapper = new ObjectMapper(); /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyData} object. */ public IEXCompanyData companyData(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + encodedSymbol); List<IEXCompanyData> data = mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); return data.get(0); } /** * Company Information * * <p>Latest snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY#company-information">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyData(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + encodedSymbol); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbol Company symbol. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String symbol, int last) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + encodedSymbol + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute("/data/core/company_historical/" + joinedSymbols); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * Historical Company Snapshots * * <p>Historical daily snapshot of public company information such as address, number of employees, CEO, and description.</p> * * @see <a href="https://iexcloud.io/docs/core/COMPANY_HISTORICAL#historical-company-snapshots">IEX Cloud API</a> * @param symbols Company symbols. * @param last Number of records to return. * @throws IOException If the request fails. * @return A List of {@link io.github.f4pl0.companydata.data.IEXCompanyData} objects. */ public List<IEXCompanyData> companyDataSnapshots(@NonNull String[] symbols, int last) throws IOException { List<String> encodedSymbols = new ArrayList<>(symbols.length); for (String symbol : symbols) { encodedSymbols.add(URLEncoder.encode(symbol, StandardCharsets.UTF_8)); } String joinedSymbols = String.join(",", encodedSymbols); CloseableHttpResponse response = httpClient.execute( "/data/core/company_historical/" + joinedSymbols + "?last=" + last ); return mapper.readValue( EntityUtils.toString(response.getEntity()), mapper.getTypeFactory().constructCollectionType(List.class, IEXCompanyData.class)); } /** * CEO Compensation * * <p>Returns the latest compensation information for the CEO of the company matching the symbol.</p> * * @see <a href="https://iexcloud.io/docs/core/ceo-compensation#ceo-compensation">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyCeoCompensation} object. */ public IEXCompanyCeoCompensation companyCeoCompensation(@NonNull String symbol) throws IOException { String encodedSymbol = URLEncoder.encode(symbol, StandardCharsets.UTF_8); CloseableHttpResponse response = httpClient.execute("/stock/" + encodedSymbol + "/ceo-compensation"); return mapper.readValue(EntityUtils.toString(response.getEntity()), IEXCompanyCeoCompensation.class); } /** * Company Logo * * <p>Returns a logo (if available) for the company.</p> * * @see <a href="https://iexcloud.io/docs/core/company-logo#company-logo">IEX Cloud API</a> * @param symbol Company symbol. * @throws IOException If the request fails. * @return A {@link io.github.f4pl0.companydata.data.IEXCompanyLogo} object. */
public IEXCompanyLogo companyLogo(@NonNull String symbol) throws IOException {
3
2023-10-27 17:56:14+00:00
4k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/TrajectorySequenceBuilder.java
[ { "identifier": "TrajectorySegment", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/sequencesegment/TrajectorySegment.java", "snippet": "public final class TrajectorySegment extends SequenceSegment {\n private final Trajectory trajectory;\n\n public TrajectorySegment(Trajectory trajectory) {\n // Note: Markers are already stored in the `Trajectory` itself.\n // This class should not hold any markers\n super(trajectory.duration(), trajectory.start(), trajectory.end(), Collections.emptyList());\n this.trajectory = trajectory;\n }\n\n public Trajectory getTrajectory() {\n return this.trajectory;\n }\n}" }, { "identifier": "TurnSegment", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/sequencesegment/TurnSegment.java", "snippet": "public final class TurnSegment extends SequenceSegment {\n private final double totalRotation;\n private final MotionProfile motionProfile;\n\n public TurnSegment(Pose2d startPose, double totalRotation, MotionProfile motionProfile, List<TrajectoryMarker> markers) {\n super(\n motionProfile.duration(),\n startPose,\n new Pose2d(\n startPose.getX(), startPose.getY(),\n Angle.norm(startPose.getHeading() + totalRotation)\n ),\n markers\n );\n\n this.totalRotation = totalRotation;\n this.motionProfile = motionProfile;\n }\n\n public final double getTotalRotation() {\n return this.totalRotation;\n }\n\n public final MotionProfile getMotionProfile() {\n return this.motionProfile;\n }\n}" }, { "identifier": "WaitSegment", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/sequencesegment/WaitSegment.java", "snippet": "public final class WaitSegment extends SequenceSegment {\n public WaitSegment(Pose2d pose, double seconds, List<TrajectoryMarker> markers) {\n super(seconds, pose, pose, markers);\n }\n}" }, { "identifier": "SequenceSegment", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/sequencesegment/SequenceSegment.java", "snippet": "public abstract class SequenceSegment {\n private final double duration;\n private final Pose2d startPose;\n private final Pose2d endPose;\n private final List<TrajectoryMarker> markers;\n\n protected SequenceSegment(\n double duration,\n Pose2d startPose, Pose2d endPose,\n List<TrajectoryMarker> markers\n ) {\n this.duration = duration;\n this.startPose = startPose;\n this.endPose = endPose;\n this.markers = markers;\n }\n\n public double getDuration() {\n return this.duration;\n }\n\n public Pose2d getStartPose() {\n return startPose;\n }\n\n public Pose2d getEndPose() {\n return endPose;\n }\n\n public List<TrajectoryMarker> getMarkers() {\n return markers;\n }\n}" } ]
import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.geometry.Vector2d; import com.acmerobotics.roadrunner.path.PathContinuityViolationException; import com.acmerobotics.roadrunner.profile.MotionProfile; import com.acmerobotics.roadrunner.profile.MotionProfileGenerator; import com.acmerobotics.roadrunner.profile.MotionState; import com.acmerobotics.roadrunner.trajectory.DisplacementMarker; import com.acmerobotics.roadrunner.trajectory.DisplacementProducer; import com.acmerobotics.roadrunner.trajectory.MarkerCallback; import com.acmerobotics.roadrunner.trajectory.SpatialMarker; import com.acmerobotics.roadrunner.trajectory.TemporalMarker; import com.acmerobotics.roadrunner.trajectory.TimeProducer; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.TrajectoryMarker; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.acmerobotics.roadrunner.util.Angle; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.TrajectorySegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.TurnSegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.WaitSegment; import org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence.sequencesegment.SequenceSegment; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
3,340
this.currentVelConstraint = this.baseVelConstraint; this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) { this.currentVelConstraint = velConstraint; return this; } public TrajectorySequenceBuilder resetVelConstraint() { this.currentVelConstraint = this.baseVelConstraint; return this; } public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) { this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetAccelConstraint() { this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) { this.currentTurnConstraintMaxAngVel = maxAngVel; this.currentTurnConstraintMaxAngAccel = maxAngAccel; return this; } public TrajectorySequenceBuilder resetTurnConstraint() { this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; return this; } public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) { return this.addTemporalMarker(currentDuration, callback); } public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) { return this.addTemporalMarker(currentDuration + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) { return this.addTemporalMarker(0.0, time, callback); } public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) { return this.addTemporalMarker(time -> scale * time + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) { this.temporalMarkers.add(new TemporalMarker(time, callback)); return this; } public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) { this.spatialMarkers.add(new SpatialMarker(point, callback)); return this; } public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement, callback); } public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement + offset, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) { return this.addDisplacementMarker(0.0, displacement, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) { return addDisplacementMarker((displacement -> scale * displacement + offset), callback); } public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) { displacementMarkers.add(new DisplacementMarker(displacement, callback)); return this; } public TrajectorySequenceBuilder turn(double angle) { return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel); } public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) { pushPath(); MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile( new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0), new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0), maxAngVel, maxAngAccel ); sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList())); lastPose = new Pose2d( lastPose.getX(), lastPose.getY(), Angle.norm(lastPose.getHeading() + angle) ); currentDuration += turnProfile.duration(); return this; } public TrajectorySequenceBuilder waitSeconds(double seconds) { pushPath();
package org.firstinspires.ftc.teamcode.RoadRunner.trajectorysequence; public class TrajectorySequenceBuilder { private final double resolution = 0.25; private final TrajectoryVelocityConstraint baseVelConstraint; private final TrajectoryAccelerationConstraint baseAccelConstraint; private TrajectoryVelocityConstraint currentVelConstraint; private TrajectoryAccelerationConstraint currentAccelConstraint; private final double baseTurnConstraintMaxAngVel; private final double baseTurnConstraintMaxAngAccel; private double currentTurnConstraintMaxAngVel; private double currentTurnConstraintMaxAngAccel; private final List<SequenceSegment> sequenceSegments; private final List<TemporalMarker> temporalMarkers; private final List<DisplacementMarker> displacementMarkers; private final List<SpatialMarker> spatialMarkers; private Pose2d lastPose; private double tangentOffset; private boolean setAbsoluteTangent; private double absoluteTangent; private TrajectoryBuilder currentTrajectoryBuilder; private double currentDuration; private double currentDisplacement; private double lastDurationTraj; private double lastDisplacementTraj; public TrajectorySequenceBuilder( Pose2d startPose, Double startTangent, TrajectoryVelocityConstraint baseVelConstraint, TrajectoryAccelerationConstraint baseAccelConstraint, double baseTurnConstraintMaxAngVel, double baseTurnConstraintMaxAngAccel ) { this.baseVelConstraint = baseVelConstraint; this.baseAccelConstraint = baseAccelConstraint; this.currentVelConstraint = baseVelConstraint; this.currentAccelConstraint = baseAccelConstraint; this.baseTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.baseTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; sequenceSegments = new ArrayList<>(); temporalMarkers = new ArrayList<>(); displacementMarkers = new ArrayList<>(); spatialMarkers = new ArrayList<>(); lastPose = startPose; tangentOffset = 0.0; setAbsoluteTangent = (startTangent != null); absoluteTangent = startTangent != null ? startTangent : 0.0; currentTrajectoryBuilder = null; currentDuration = 0.0; currentDisplacement = 0.0; lastDurationTraj = 0.0; lastDisplacementTraj = 0.0; } public TrajectorySequenceBuilder( Pose2d startPose, TrajectoryVelocityConstraint baseVelConstraint, TrajectoryAccelerationConstraint baseAccelConstraint, double baseTurnConstraintMaxAngVel, double baseTurnConstraintMaxAngAccel ) { this( startPose, null, baseVelConstraint, baseAccelConstraint, baseTurnConstraintMaxAngVel, baseTurnConstraintMaxAngAccel ); } public TrajectorySequenceBuilder lineTo(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineTo( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineTo(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToConstantHeading(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToConstantHeading( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToConstantHeading(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToLinearHeading(Pose2d endPose) { return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToLinearHeading( Pose2d endPose, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToLinearHeading(endPose, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder lineToSplineHeading(Pose2d endPose) { return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder lineToSplineHeading( Pose2d endPose, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.lineToSplineHeading(endPose, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeTo(Vector2d endPosition) { return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeTo( Vector2d endPosition, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeTo(endPosition, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder forward(double distance) { return addPath(() -> currentTrajectoryBuilder.forward(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder forward( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.forward(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder back(double distance) { return addPath(() -> currentTrajectoryBuilder.back(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder back( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.back(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeLeft(double distance) { return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeLeft( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeLeft(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder strafeRight(double distance) { return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder strafeRight( double distance, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.strafeRight(distance, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineTo(Vector2d endPosition, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineTo( Vector2d endPosition, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineTo(endPosition, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToConstantHeading(Vector2d endPosition, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToConstantHeading( Vector2d endPosition, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToConstantHeading(endPosition, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToLinearHeading(Pose2d endPose, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToLinearHeading( Pose2d endPose, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToLinearHeading(endPose, endHeading, velConstraint, accelConstraint)); } public TrajectorySequenceBuilder splineToSplineHeading(Pose2d endPose, double endHeading) { return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, currentVelConstraint, currentAccelConstraint)); } public TrajectorySequenceBuilder splineToSplineHeading( Pose2d endPose, double endHeading, TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { return addPath(() -> currentTrajectoryBuilder.splineToSplineHeading(endPose, endHeading, velConstraint, accelConstraint)); } private TrajectorySequenceBuilder addPath(AddPathCallback callback) { if (currentTrajectoryBuilder == null) newPath(); try { callback.run(); } catch (PathContinuityViolationException e) { newPath(); callback.run(); } Trajectory builtTraj = currentTrajectoryBuilder.build(); double durationDifference = builtTraj.duration() - lastDurationTraj; double displacementDifference = builtTraj.getPath().length() - lastDisplacementTraj; lastPose = builtTraj.end(); currentDuration += durationDifference; currentDisplacement += displacementDifference; lastDurationTraj = builtTraj.duration(); lastDisplacementTraj = builtTraj.getPath().length(); return this; } public TrajectorySequenceBuilder setTangent(double tangent) { setAbsoluteTangent = true; absoluteTangent = tangent; pushPath(); return this; } private TrajectorySequenceBuilder setTangentOffset(double offset) { setAbsoluteTangent = false; this.tangentOffset = offset; this.pushPath(); return this; } public TrajectorySequenceBuilder setReversed(boolean reversed) { return reversed ? this.setTangentOffset(Math.toRadians(180.0)) : this.setTangentOffset(0.0); } public TrajectorySequenceBuilder setConstraints( TrajectoryVelocityConstraint velConstraint, TrajectoryAccelerationConstraint accelConstraint ) { this.currentVelConstraint = velConstraint; this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetConstraints() { this.currentVelConstraint = this.baseVelConstraint; this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setVelConstraint(TrajectoryVelocityConstraint velConstraint) { this.currentVelConstraint = velConstraint; return this; } public TrajectorySequenceBuilder resetVelConstraint() { this.currentVelConstraint = this.baseVelConstraint; return this; } public TrajectorySequenceBuilder setAccelConstraint(TrajectoryAccelerationConstraint accelConstraint) { this.currentAccelConstraint = accelConstraint; return this; } public TrajectorySequenceBuilder resetAccelConstraint() { this.currentAccelConstraint = this.baseAccelConstraint; return this; } public TrajectorySequenceBuilder setTurnConstraint(double maxAngVel, double maxAngAccel) { this.currentTurnConstraintMaxAngVel = maxAngVel; this.currentTurnConstraintMaxAngAccel = maxAngAccel; return this; } public TrajectorySequenceBuilder resetTurnConstraint() { this.currentTurnConstraintMaxAngVel = baseTurnConstraintMaxAngVel; this.currentTurnConstraintMaxAngAccel = baseTurnConstraintMaxAngAccel; return this; } public TrajectorySequenceBuilder addTemporalMarker(MarkerCallback callback) { return this.addTemporalMarker(currentDuration, callback); } public TrajectorySequenceBuilder UNSTABLE_addTemporalMarkerOffset(double offset, MarkerCallback callback) { return this.addTemporalMarker(currentDuration + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(double time, MarkerCallback callback) { return this.addTemporalMarker(0.0, time, callback); } public TrajectorySequenceBuilder addTemporalMarker(double scale, double offset, MarkerCallback callback) { return this.addTemporalMarker(time -> scale * time + offset, callback); } public TrajectorySequenceBuilder addTemporalMarker(TimeProducer time, MarkerCallback callback) { this.temporalMarkers.add(new TemporalMarker(time, callback)); return this; } public TrajectorySequenceBuilder addSpatialMarker(Vector2d point, MarkerCallback callback) { this.spatialMarkers.add(new SpatialMarker(point, callback)); return this; } public TrajectorySequenceBuilder addDisplacementMarker(MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement, callback); } public TrajectorySequenceBuilder UNSTABLE_addDisplacementMarkerOffset(double offset, MarkerCallback callback) { return this.addDisplacementMarker(currentDisplacement + offset, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double displacement, MarkerCallback callback) { return this.addDisplacementMarker(0.0, displacement, callback); } public TrajectorySequenceBuilder addDisplacementMarker(double scale, double offset, MarkerCallback callback) { return addDisplacementMarker((displacement -> scale * displacement + offset), callback); } public TrajectorySequenceBuilder addDisplacementMarker(DisplacementProducer displacement, MarkerCallback callback) { displacementMarkers.add(new DisplacementMarker(displacement, callback)); return this; } public TrajectorySequenceBuilder turn(double angle) { return turn(angle, currentTurnConstraintMaxAngVel, currentTurnConstraintMaxAngAccel); } public TrajectorySequenceBuilder turn(double angle, double maxAngVel, double maxAngAccel) { pushPath(); MotionProfile turnProfile = MotionProfileGenerator.generateSimpleMotionProfile( new MotionState(lastPose.getHeading(), 0.0, 0.0, 0.0), new MotionState(lastPose.getHeading() + angle, 0.0, 0.0, 0.0), maxAngVel, maxAngAccel ); sequenceSegments.add(new TurnSegment(lastPose, angle, turnProfile, Collections.emptyList())); lastPose = new Pose2d( lastPose.getX(), lastPose.getY(), Angle.norm(lastPose.getHeading() + angle) ); currentDuration += turnProfile.duration(); return this; } public TrajectorySequenceBuilder waitSeconds(double seconds) { pushPath();
sequenceSegments.add(new WaitSegment(lastPose, seconds, Collections.emptyList()));
2
2023-10-31 16:06:46+00:00
4k
Fuzss/diagonalwalls
1.19/Common/src/main/java/fuzs/diagonalwindows/client/model/MultipartAppender.java
[ { "identifier": "DiagonalWindows", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/DiagonalWindows.java", "snippet": "public class DiagonalWindows implements ModConstructor {\n public static final String MOD_ID = \"diagonalwindows\";\n public static final String MOD_NAME = \"Diagonal Windows\";\n public static final Logger LOGGER = LogManager.getLogger(DiagonalWindows.MOD_NAME);\n\n @Override\n public void onConstructMod() {\n ModRegistry.touch();\n }\n\n public static ResourceLocation id(String path) {\n return new ResourceLocation(MOD_ID, path);\n }\n}" }, { "identifier": "DiagonalBlock", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/api/world/level/block/DiagonalBlock.java", "snippet": "public interface DiagonalBlock extends IDiagonalBlock {\n BooleanProperty NORTH_EAST = BooleanProperty.create(\"north_east\");\n BooleanProperty SOUTH_EAST = BooleanProperty.create(\"south_east\");\n BooleanProperty SOUTH_WEST = BooleanProperty.create(\"south_west\");\n BooleanProperty NORTH_WEST = BooleanProperty.create(\"north_west\");\n\n /**\n * @return have diagonal properties successfully been applied to this block\n */\n @Override\n boolean hasProperties();\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n @Override\n default boolean canConnectDiagonally() {\n return this.supportsDiagonalConnections();\n }\n\n /**\n * @return is this block not blacklisted via a block tag\n */\n boolean supportsDiagonalConnections();\n\n /**\n * @param neighborState neighbor block state to check if it can connect to me diagonally\n * @param neighborDirectionToMe my direction from the neighbor blocks point of view\n * @return is a diagonal connection between both blocks allowed\n */\n boolean canConnectToMe(BlockState neighborState, EightWayDirection neighborDirectionToMe);\n}" }, { "identifier": "EightWayDirection", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/api/world/level/block/EightWayDirection.java", "snippet": "public enum EightWayDirection implements StringRepresentable {\n SOUTH(0, new Vec3i(0, 0, 1)),\n WEST(1, new Vec3i(-1, 0, 0)),\n NORTH(2, new Vec3i(0, 0, -1)),\n EAST(3, new Vec3i(1, 0, 0)),\n SOUTH_WEST(0, new Vec3i(-1, 0, 1)),\n NORTH_WEST(1, new Vec3i(-1, 0, -1)),\n NORTH_EAST(2, new Vec3i(1, 0, -1)),\n SOUTH_EAST(3, new Vec3i(1, 0, 1));\n\n private static final Map<String, EightWayDirection> DIRECTIONS_BY_KEY = Stream.of(EightWayDirection.values()).collect(Collectors.toMap(EightWayDirection::getSerializedName, Function.identity()));\n\n private final int data2d;\n private final Vec3i directionVec;\n\n EightWayDirection(int data2d, Vec3i directionVec) {\n this.data2d = data2d;\n this.directionVec = directionVec;\n }\n\n public static EightWayDirection toEightWayDirection(Direction direction) {\n return getCardinalDirections()[direction.get2DDataValue()];\n }\n\n public static EightWayDirection byIndex(int index, boolean intercardinal) {\n index = ((index % 4) + 4) % 4;\n return intercardinal ? getIntercardinalDirections()[index] : getCardinalDirections()[index];\n }\n\n public static EightWayDirection[] getCardinalDirections() {\n return new EightWayDirection[]{SOUTH, WEST, NORTH, EAST};\n }\n\n public static EightWayDirection[] getIntercardinalDirections() {\n return new EightWayDirection[]{SOUTH_WEST, NORTH_WEST, NORTH_EAST, SOUTH_EAST};\n }\n\n public int getX() {\n return this.directionVec.getX();\n }\n\n public int getY() {\n return this.directionVec.getY();\n }\n\n public int getZ() {\n return this.directionVec.getZ();\n }\n\n public boolean compareAxis(EightWayDirection other) {\n if (this.isCardinal() != other.isCardinal()) return false;\n return (this.getX() + other.getX() + this.getY() + other.getY() + this.getZ() + other.getZ()) == 0;\n }\n\n @Nullable\n public static EightWayDirection byName(String name) {\n return DIRECTIONS_BY_KEY.get(name);\n }\n\n public boolean isCardinal() {\n return !this.isIntercardinal();\n }\n\n public boolean isIntercardinal() {\n return this.directionVec.getX() != 0 && this.directionVec.getZ() != 0;\n }\n\n public int getHorizontalIndex() {\n return 1 << (this.isIntercardinal() ? 4 + this.data2d : this.data2d);\n }\n\n public Vec3[] transform(Vec3[] vectors) {\n if (this.directionVec.getX() != 0) {\n vectors = VoxelUtils.ortho(vectors);\n }\n if (this.directionVec.getX() == -1 || this.directionVec.getZ() == -1) {\n vectors = VoxelUtils.mirror(vectors);\n }\n return vectors;\n }\n\n public EightWayDirection opposite() {\n return EightWayDirection.byIndex((this.data2d + 2), this.isIntercardinal());\n }\n\n public EightWayDirection[] getCardinalNeighbors() {\n if (this.isIntercardinal()) {\n return new EightWayDirection[]{EightWayDirection.byIndex(this.data2d, false), EightWayDirection.byIndex(this.data2d + 1, false)};\n }\n throw new IllegalStateException(\"Direction already is cardinal\");\n }\n\n public EightWayDirection[] getIntercardinalNeighbors() {\n if (this.isCardinal()) {\n return new EightWayDirection[]{EightWayDirection.byIndex(this.data2d + 3, true), EightWayDirection.byIndex(this.data2d, true)};\n }\n throw new IllegalStateException(\"Direction already is intercardinal\");\n }\n\n public Direction toDirection() {\n if (this.isCardinal()) {\n return Direction.from2DDataValue(this.data2d);\n }\n throw new IllegalStateException(\"Cannot convert intercardinal direction to vanilla direction\");\n }\n\n public EightWayDirection rotateClockWise() {\n return byIndex(this.isIntercardinal() ? this.data2d + 1 : this.data2d, !this.isIntercardinal());\n }\n\n public EightWayDirection rotateCounterClockWise() {\n return byIndex(this.isIntercardinal() ? this.data2d : this.data2d + 3, !this.isIntercardinal());\n }\n\n @Override\n public String getSerializedName() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}" }, { "identifier": "ClientAbstractions", "path": "1.18/Common/src/main/java/fuzs/diagonalwindows/client/core/ClientAbstractions.java", "snippet": "public interface ClientAbstractions {\n ClientAbstractions INSTANCE = ServiceProviderHelper.load(ClientAbstractions.class);\n\n BakedModel createWrappedBakedModel(BakedModel baseModel, Map<Direction, List<BakedQuad>> quadMap);\n}" } ]
import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import fuzs.diagonalwindows.DiagonalWindows; import fuzs.diagonalwindows.api.world.level.block.DiagonalBlock; import fuzs.diagonalwindows.api.world.level.block.EightWayDirection; import fuzs.diagonalwindows.client.core.ClientAbstractions; import fuzs.diagonalwindows.mixin.client.accessor.*; import net.minecraft.client.renderer.block.BlockModelShaper; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.MultiVariant; import net.minecraft.client.renderer.block.model.Variant; import net.minecraft.client.renderer.block.model.multipart.*; import net.minecraft.client.resources.model.BakedModel; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.RandomSource; import net.minecraft.world.level.block.FenceBlock; import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.state.BlockState; import org.apache.commons.lang3.ArrayUtils; import org.apache.logging.log4j.util.BiConsumer; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Predicate; import java.util.function.UnaryOperator;
2,229
package fuzs.diagonalwindows.client.model; public class MultipartAppender { public static void onPrepareModelBaking(ModelBakery modelBakery) { Stopwatch stopwatch = Stopwatch.createStarted(); Registry.BLOCK.stream() .filter(block -> (block instanceof FenceBlock || block instanceof IronBarsBlock) && block instanceof DiagonalBlock diagonalBlock && diagonalBlock.hasProperties()) .map(block -> block.getStateDefinition().any()) .forEach(state -> { if (modelBakery.getModel(BlockModelShaper.stateToModelLocation(state)) instanceof MultiPart multiPart) { appendDiagonalSelectors(((ModelBakeryAccessor) modelBakery)::diagonalfences$callCacheAndQueueDependencies, multiPart, state.getBlock() instanceof IronBarsBlock); } else {
package fuzs.diagonalwindows.client.model; public class MultipartAppender { public static void onPrepareModelBaking(ModelBakery modelBakery) { Stopwatch stopwatch = Stopwatch.createStarted(); Registry.BLOCK.stream() .filter(block -> (block instanceof FenceBlock || block instanceof IronBarsBlock) && block instanceof DiagonalBlock diagonalBlock && diagonalBlock.hasProperties()) .map(block -> block.getStateDefinition().any()) .forEach(state -> { if (modelBakery.getModel(BlockModelShaper.stateToModelLocation(state)) instanceof MultiPart multiPart) { appendDiagonalSelectors(((ModelBakeryAccessor) modelBakery)::diagonalfences$callCacheAndQueueDependencies, multiPart, state.getBlock() instanceof IronBarsBlock); } else {
DiagonalWindows.LOGGER.warn("Block '{}' is not using multipart models, diagonal connections will not be visible!", state.getBlock());
0
2023-10-27 09:06:16+00:00
4k
slatepowered/slate
slate-common/src/main/java/slatepowered/slate/model/ManagedNode.java
[ { "identifier": "Logger", "path": "slate-common/src/main/java/slatepowered/slate/logging/Logger.java", "snippet": "public interface Logger {\r\n\r\n /* Information */\r\n void info(Object... msg);\r\n default void info(Supplier<Object> msg) { info(msg.get()); }\r\n\r\n /* Warnings */\r\n void warn(Object... msg);\r\n default void warn(Supplier<Object> msg) { warn(msg.get()); }\r\n\r\n default void warning(Object... msg) {\r\n warn(msg);\r\n }\r\n\r\n default void warning(Supplier<Object> msg) {\r\n warn(msg);\r\n }\r\n\r\n /* Relatively unimportant errors */\r\n void error(Object... msg);\r\n default void error(Supplier<Object> msg) { error(msg); }\r\n\r\n /* Severe errors */\r\n void severe(Object... msg);\r\n default void severe(Supplier<Object> msg) { severe(msg); }\r\n\r\n /* Fatal errors */\r\n void fatal(Object... msg);\r\n default void fatal(Supplier<Object> msg) { fatal(msg); }\r\n\r\n /* Debug messages */\r\n void debug(Object... msg);\r\n default void debug(Supplier<Object> msg) { if (Logging.DEBUG) debug(msg.get()); }\r\n\r\n default void trace(Object... msg) {\r\n if (Logging.DEBUG) {\r\n debug(msg);\r\n\r\n // print the stack trace\r\n StackTraceElement[] elements = new RuntimeException().getStackTrace();\r\n for (int i = 1; i < elements.length; i++) {\r\n debug(elements[i]);\r\n }\r\n }\r\n }\r\n\r\n default void trace(Supplier<Object> msg) {\r\n if (Logging.DEBUG) trace(msg.get());\r\n }\r\n\r\n /**\r\n * Create a logger which doesn't do anything when the methods\r\n * are called.\r\n *\r\n * @return The voiding logger.\r\n */\r\n static Logger voiding() {\r\n return new Logger() {\r\n @Override\r\n public void info(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void warn(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void error(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void severe(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void fatal(Object... msg) {\r\n\r\n }\r\n\r\n @Override\r\n public void debug(Object... msg) {\r\n\r\n }\r\n };\r\n }\r\n\r\n}\r" }, { "identifier": "Logging", "path": "slate-common/src/main/java/slatepowered/slate/logging/Logging.java", "snippet": "public class Logging {\r\n\r\n /**\r\n * Whether to do debug logging.\r\n */\r\n public static boolean DEBUG;\r\n\r\n /**\r\n * The current set logger provider.\r\n */\r\n private static LoggerProvider provider;\r\n\r\n static {\r\n DEBUG = Boolean.parseBoolean(System.getProperty(\"slate.debug\", \"false\"));\r\n }\r\n\r\n /**\r\n * Set whether debug messages should be shown.\r\n *\r\n * @param debug The debug flag value.\r\n */\r\n public static void setDebug(boolean debug) {\r\n DEBUG = debug;\r\n }\r\n\r\n public static void setProvider(LoggerProvider provider1) {\r\n if (provider != null)\r\n return; // silently fail\r\n provider = provider1;\r\n }\r\n\r\n /**\r\n * Get the currently active logger provider.\r\n *\r\n * @return The logger provider.\r\n */\r\n public static LoggerProvider getProvider() {\r\n return provider;\r\n }\r\n\r\n /**\r\n * Get the consistently configured logger for the given name.\r\n *\r\n * @param name The name.\r\n * @return The logger.\r\n */\r\n public static Logger getLogger(String name) {\r\n return provider != null ? provider.getLogger(name) : Logger.voiding();\r\n }\r\n\r\n}\r" }, { "identifier": "Service", "path": "slate-common/src/main/java/slatepowered/slate/service/Service.java", "snippet": "public interface Service {\r\n\r\n}\r" }, { "identifier": "ServiceKey", "path": "slate-common/src/main/java/slatepowered/slate/service/ServiceKey.java", "snippet": "public interface ServiceKey<T extends Service> {\r\n\r\n /**\r\n * Get the service class. This is the base\r\n * parameter of the service tag.\r\n *\r\n * @return The service class.\r\n */\r\n Class<T> getServiceClass();\r\n\r\n /**\r\n * Called when the service associated with this\r\n * tag is registered to the given manager.\r\n *\r\n * @param manager The manager.\r\n * @param service The service.\r\n */\r\n void register(ServiceManager manager, T service);\r\n\r\n /**\r\n * Used to get the tag for retrieving the local instance.\r\n *\r\n * @return The local tag, can be this.\r\n */\r\n default ServiceKey<T> toLocal() {\r\n return this;\r\n }\r\n\r\n static <T extends Service> ServiceKey<T> local(Class<T> tClass) {\r\n return new ServiceKey<T>() {\r\n @Override\r\n public Class<T> getServiceClass() {\r\n return tClass;\r\n }\r\n\r\n @Override\r\n public void register(ServiceManager manager, T service) {\r\n // noop\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n return tClass.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) return true;\r\n if (!(obj instanceof ServiceKey)) return false;\r\n return tClass == ((ServiceKey<?>)obj).getServiceClass();\r\n }\r\n };\r\n }\r\n\r\n}\r" }, { "identifier": "NodeHostBoundServiceKey", "path": "slate-common/src/main/java/slatepowered/slate/service/network/NodeHostBoundServiceKey.java", "snippet": "public interface NodeHostBoundServiceKey<T extends Service> extends NodeBoundServiceKey<T> {\r\n\r\n Logger LOGGER = Logging.getLogger(\"NodeHostBoundServiceKey\");\r\n\r\n /**\r\n * Set the host this should be bound to.\r\n *\r\n * @param hostName The host name.\r\n * @return The key.\r\n */\r\n NodeHostBoundServiceKey<T> forHost(String hostName);\r\n\r\n /**\r\n * A node-host-bound service mapping from S -> R.\r\n */\r\n @RequiredArgsConstructor\r\n @SuppressWarnings(\"unchecked\")\r\n class Mapped<S extends Service, R extends Service> implements NodeHostBoundServiceKey<R>, DynamicServiceKey<R> {\r\n private final Class<R> serviceClass;\r\n private final ServiceKey<S> sourceKey;\r\n private final BiFunction<S, String, R> function;\r\n private String hostName;\r\n private String nodeName;\r\n\r\n @Override\r\n public Class<R> getServiceClass() {\r\n return serviceClass;\r\n }\r\n\r\n @Override\r\n public void register(ServiceManager manager, R service) {\r\n throw new UnsupportedOperationException(\"Can not register key: \" + this);\r\n }\r\n\r\n @Override\r\n public ServiceKey<R> toLocal() {\r\n return (ServiceKey<R>) sourceKey.toLocal();\r\n }\r\n\r\n @Override\r\n public NodeBoundServiceKey<R> forNode(String name) {\r\n this.nodeName = name;\r\n return this;\r\n }\r\n\r\n @Override\r\n public R create(ServiceProvider manager) {\r\n try {\r\n Network network = manager.getService(Network.KEY);\r\n Objects.requireNonNull(hostName, \"Host name is not set, can not get service\");\r\n Node hostNode = network.getNode(hostName);\r\n if (hostNode == null)\r\n throw new IllegalArgumentException(\"Could not find a node by hostName(\" + nodeName + \")\");\r\n ServiceKey<S> qualifiedSourceKey = hostNode.qualifyServiceKey(sourceKey);\r\n S baseService = manager.serviceManager().getService(qualifiedSourceKey);\r\n return function.apply(baseService, nodeName);\r\n } catch (RuntimeException e) {\r\n e.printStackTrace();\r\n throw new AssertionError();\r\n }\r\n }\r\n\r\n @Override\r\n public NodeHostBoundServiceKey<R> forHost(String hostName) {\r\n this.hostName = hostName;\r\n return this;\r\n }\r\n }\r\n\r\n /**\r\n * Creates a mapped, node-bound service key for the given\r\n * result service class.\r\n *\r\n * @param serviceClass The result service class.\r\n * @param key The source key.\r\n * @param function The mapping function.\r\n * @param <S> The source service type.\r\n * @param <R> The result service type.\r\n * @return The mapped service key.\r\n */\r\n static <S extends Service, R extends Service> Mapped<S, R> mapped(Class<R> serviceClass, ServiceKey<S> key, BiFunction<S, String, R> function) {\r\n return new Mapped<>(serviceClass, key, function);\r\n }\r\n\r\n}\r" } ]
import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.service.Service; import slatepowered.slate.service.ServiceKey; import slatepowered.slate.service.network.NodeHostBoundServiceKey; import slatepowered.veru.collection.Sequence; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; import java.util.function.Function;
3,051
package slatepowered.slate.model; /** * Represents a node you have management capabilities over. */ @SuppressWarnings("rawtypes") public abstract class ManagedNode extends Node { protected static final Logger LOGGER = Logging.getLogger("ManagedNode"); /** * The children of this node. */ protected final Map<String, ManagedNode> children = new HashMap<>(); /** * The parent node. */ protected final Node parent; /** * All components attached to this node. */ protected final List<NodeComponent> components; public ManagedNode(Node parent, String name, Network network, List<NodeComponent> components) { super(name, network); this.parent = parent; // ensure a thread-safe component list this.components = new Vector<>(); // invoke node attachments if (components != null) { for (NodeComponent component : components) { attach(component); } } } public ManagedNode(Node parent, String name, Network network) { super(name, network); this.parent = parent; this.components = new ArrayList<>(); } /** * Get the parent node of this node. * * The parent of a node is generally unimportant except for * organization or special behavior. * * @return The parent node. */ public Node getParent() { return parent; } /** * Get all components attached to this node. * * @return The components. */ public List<NodeComponent> getComponents() { return components; } /** * Find all components which are assignable to the given class. * * @param kl The class. * @param <T> The value type. * @return The list of components. */ @SuppressWarnings("unchecked") public <T extends NodeComponent> Sequence<T> findComponents(Class<? super T> kl) { Sequence<T> set = new Sequence<>(); for (NodeComponent component : components) { if (kl.isAssignableFrom(component.getClass())) { set.add((T) component); } } return set; } /** * Attach the given component to this node, this is the * only mutable part of the node. * * @param component The component. * @return This. */ public synchronized ManagedNode attach(NodeComponent component) { if (component == null) return this; if (component.attached(this)) { components.add(component); } return this; } public Map<String, ManagedNode> getChildren() { return children; } public ManagedNode getChild(String name) { return children.get(name); } /** * Assume this operation is valid under normal circumstances * and blindly adopt the given node as this node's child. * * @param node The node to adopt. * @return This. */ public ManagedNode adopt(ManagedNode node) { children.put(node.getName(), node); return this; } /** * Execute an action through all the components * * @param componentClass The component class to match the components against. * @param invoker The invoker function which runs the action and returns the result. * @param resultComposer The result composer which composes any errors into a result object. * @param <T> The result type. * @param <C> The component type. * @return The result future. */ @SuppressWarnings("unchecked") public <T, C extends NodeComponent> CompletableFuture<T> runVoidAction(Class<C> componentClass, BiFunction<C, ManagedNode, CompletableFuture<?>> invoker, Function<Throwable, T> resultComposer) { List<CompletableFuture<?>> futureList = new ArrayList<>(); for (C component : findComponents(componentClass)) { if (Logging.DEBUG) LOGGER.debug(" Action executed on component(" + component + ") of node(name: " + name + ")"); futureList.add(invoker.apply(component, this)); } if (resultComposer != null) { return CompletableFuture .allOf(futureList.toArray(new CompletableFuture[0])) .thenApply(__ -> resultComposer.apply(null)) .exceptionally(resultComposer); } else { return (CompletableFuture<T>) CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])); } } @Override
package slatepowered.slate.model; /** * Represents a node you have management capabilities over. */ @SuppressWarnings("rawtypes") public abstract class ManagedNode extends Node { protected static final Logger LOGGER = Logging.getLogger("ManagedNode"); /** * The children of this node. */ protected final Map<String, ManagedNode> children = new HashMap<>(); /** * The parent node. */ protected final Node parent; /** * All components attached to this node. */ protected final List<NodeComponent> components; public ManagedNode(Node parent, String name, Network network, List<NodeComponent> components) { super(name, network); this.parent = parent; // ensure a thread-safe component list this.components = new Vector<>(); // invoke node attachments if (components != null) { for (NodeComponent component : components) { attach(component); } } } public ManagedNode(Node parent, String name, Network network) { super(name, network); this.parent = parent; this.components = new ArrayList<>(); } /** * Get the parent node of this node. * * The parent of a node is generally unimportant except for * organization or special behavior. * * @return The parent node. */ public Node getParent() { return parent; } /** * Get all components attached to this node. * * @return The components. */ public List<NodeComponent> getComponents() { return components; } /** * Find all components which are assignable to the given class. * * @param kl The class. * @param <T> The value type. * @return The list of components. */ @SuppressWarnings("unchecked") public <T extends NodeComponent> Sequence<T> findComponents(Class<? super T> kl) { Sequence<T> set = new Sequence<>(); for (NodeComponent component : components) { if (kl.isAssignableFrom(component.getClass())) { set.add((T) component); } } return set; } /** * Attach the given component to this node, this is the * only mutable part of the node. * * @param component The component. * @return This. */ public synchronized ManagedNode attach(NodeComponent component) { if (component == null) return this; if (component.attached(this)) { components.add(component); } return this; } public Map<String, ManagedNode> getChildren() { return children; } public ManagedNode getChild(String name) { return children.get(name); } /** * Assume this operation is valid under normal circumstances * and blindly adopt the given node as this node's child. * * @param node The node to adopt. * @return This. */ public ManagedNode adopt(ManagedNode node) { children.put(node.getName(), node); return this; } /** * Execute an action through all the components * * @param componentClass The component class to match the components against. * @param invoker The invoker function which runs the action and returns the result. * @param resultComposer The result composer which composes any errors into a result object. * @param <T> The result type. * @param <C> The component type. * @return The result future. */ @SuppressWarnings("unchecked") public <T, C extends NodeComponent> CompletableFuture<T> runVoidAction(Class<C> componentClass, BiFunction<C, ManagedNode, CompletableFuture<?>> invoker, Function<Throwable, T> resultComposer) { List<CompletableFuture<?>> futureList = new ArrayList<>(); for (C component : findComponents(componentClass)) { if (Logging.DEBUG) LOGGER.debug(" Action executed on component(" + component + ") of node(name: " + name + ")"); futureList.add(invoker.apply(component, this)); } if (resultComposer != null) { return CompletableFuture .allOf(futureList.toArray(new CompletableFuture[0])) .thenApply(__ -> resultComposer.apply(null)) .exceptionally(resultComposer); } else { return (CompletableFuture<T>) CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])); } } @Override
public <T extends Service> ServiceKey<T> qualifyServiceKey(ServiceKey<T> key) throws UnsupportedOperationException {
2
2023-10-30 08:58:02+00:00
4k
The2019/NewBase-1.20.2
src/client/java/net/The2019/NewBase/utils/InitKeyBindings.java
[ { "identifier": "Test", "path": "src/client/java/net/The2019/NewBase/features/generic/Test.java", "snippet": "public class Test {\n\n public static void test(){\n }\n}" }, { "identifier": "YawSet", "path": "src/client/java/net/The2019/NewBase/features/generic/YawSet.java", "snippet": "public class YawSet {\n private static final MinecraftClient mc = MinecraftClient.getInstance();\n\n public static void setYaw() {\n if (mc.player != null) {\n mc.player.setYaw(roundYaw(mc.player.getYaw()));\n }\n }\n\n private static float roundYaw(float yaw) {\n float angel = yaw % 360.0F;\n float roundYaw = Math.round(angel/ 90.0F) * 90.0F;\n\n if(roundYaw == 360.0F){\n roundYaw = 0.0F;\n }\n return roundYaw;\n }\n}" }, { "identifier": "ChatCoordinatesScreen", "path": "src/client/java/net/The2019/NewBase/screens/ChatCoordinatesScreen.java", "snippet": "public class ChatCoordinatesScreen extends Screen {\n private final Screen parent;\n private final GameOptions settings;\n private static final MinecraftClient mc = MinecraftClient.getInstance();\n\n public ChatCoordinatesScreen(Screen parent, GameOptions gameOptions) {\n super(Text.translatable(\"newbase.chatcoordinatesscreen.name\"));\n this.parent = parent;\n this.settings = gameOptions;\n }\n\n @Override\n protected void init() {\n ButtonWidget yesButton = new ButtonWidget.Builder(Text.translatable(\"newbase.chatcoordinatesscreen.yes\"), button -> {\n if (mc.player != null) {\n BlockPos playerPos = mc.player.getBlockPos();\n mc.player.networkHandler.sendChatMessage(String.format(\"X: %s Y: %s Z: %s\", playerPos.getX(), playerPos.getY(), playerPos.getZ()));\n mc.setScreen(null);\n }\n }).dimensions(this.width / 2 - 90, this.height / 2, 80, 20).build();\n\n ButtonWidget noButton = new ButtonWidget.Builder(Text.translatable(\"newbase.chatcoordinatesscreen.no\"), button -> {\n mc.setScreen(null);\n }).dimensions(this.width / 2, this.height / 2, 80, 20).build();\n\n this.addDrawable(new TextWidget(this.width / 2 - 250, this.height / 2 - 30, 500, 20, Text.translatable(\"newbase.chatcoordinatesscreen.message\"), textRenderer));\n this.addDrawableChild(yesButton);\n this.addDrawableChild(noButton);\n }\n}" }, { "identifier": "ConfigScreen", "path": "src/client/java/net/The2019/NewBase/screens/ConfigScreen.java", "snippet": "public class ConfigScreen extends Screen {\n private final Screen parent;\n private final GameOptions settings;\n private static final MinecraftClient mc = MinecraftClient.getInstance();\n private int y = 50;\n private int x = 20;\n\n public ConfigScreen(Screen parent, GameOptions gameOptions) {\n super(Text.translatable(\"newbase.configscreen.name\"));\n this.parent = parent;\n this.settings = gameOptions;\n }\n\n @Override\n protected void init() {\n this.addDrawable(new TextWidget(x, 20, 100, 20, Text.translatable(\"newbase.configscreen.name\").formatted(Formatting.BOLD), textRenderer)).alignLeft().setTooltip(Tooltip.of(Text.translatable(\"newbase.configscreen.nametooltip\")));\n\n //Hud\n this.addDrawable(new TextWidget(x, y, 100, 20, Text.translatable(\"newbase.configscreen.hud\"), mc.textRenderer).alignLeft());\n this.addDrawableChild(new ButtonWidget.Builder(Text.translatable(\"newbase.configscreen.hudbutton\"), button -> {mc.setScreen(new HudScreen(mc.currentScreen, mc.options));}).tooltip(Tooltip.of(Text.translatable(\"newbase.configscreen.hudtooltip\"))).dimensions(this.width - 220, y, 200, 20).build());\n\n //Render\n this.addDrawable(new TextWidget(x, y+30, 100, 20, Text.translatable(\"newbase.configscreen.render\"), mc.textRenderer).alignLeft());\n this.addDrawableChild(new ButtonWidget.Builder(Text.translatable(\"newbase.configscreen.renderbutton\"), button -> {mc.setScreen(new RenderScreen(mc.currentScreen, mc.options));}).tooltip(Tooltip.of(Text.translatable(\"newbase.configscreen.rendertooltip\"))).dimensions(this.width - 220, y+30, 200, 20).build());\n\n //Generic\n this.addDrawable(new TextWidget(x, y+60, 100, 20, Text.translatable(\"newbase.configscreen.generic\"), mc.textRenderer).alignLeft());\n this.addDrawableChild(new ButtonWidget.Builder(Text.translatable(\"newbase.configscreen.genericbutton\"), button -> {mc.setScreen(new GenericScreen(mc.currentScreen, mc.options));}).tooltip(Tooltip.of(Text.translatable(\"newbase.configscreen.rendertooltip\"))).dimensions(this.width - 220, y+60, 200, 20).build());\n\n }\n}" }, { "identifier": "readModule", "path": "src/client/java/net/The2019/NewBase/config/ModuleConfig.java", "snippet": "public static boolean readModule(String module){\n try (FileReader reader = new FileReader(configFile)) {\n JsonObject json = gson.fromJson(reader, JsonObject.class);\n if (json != null && json.has(module)) {\n return json.get(module).getAsBoolean();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return true;\n}" }, { "identifier": "saveModuleState", "path": "src/client/java/net/The2019/NewBase/config/ModuleConfig.java", "snippet": "public static void saveModuleState(String module, boolean state) {\n JsonObject json = new JsonObject();\n\n try (FileReader reader = new FileReader(configFile)) {\n json = gson.fromJson(reader, JsonObject.class);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n json.addProperty(module, state);\n\n try (FileWriter writer = new FileWriter(configFile)) {\n gson.toJson(json, writer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n}" }, { "identifier": "placer", "path": "src/client/java/net/The2019/NewBase/config/ModuleStates.java", "snippet": "public static String placer = \"placer\";" } ]
import net.The2019.NewBase.features.generic.Test; import net.The2019.NewBase.features.generic.YawSet; import net.The2019.NewBase.screens.ChatCoordinatesScreen; import net.The2019.NewBase.screens.ConfigScreen; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.minecraft.client.MinecraftClient; import net.minecraft.client.option.KeyBinding; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import org.lwjgl.glfw.GLFW; import static net.The2019.NewBase.config.ModuleConfig.readModule; import static net.The2019.NewBase.config.ModuleConfig.saveModuleState; import static net.The2019.NewBase.config.ModuleStates.placer;
1,858
package net.The2019.NewBase.utils; public class InitKeyBindings { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void initKeys(){ KeyBinding configScreen = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.configscreen", GLFW.GLFW_KEY_O, "newbase.name")); KeyBinding chatCoordinates = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.sendcoordinates", GLFW.GLFW_KEY_P, "newbase.name")); KeyBinding togglePlacer = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggleplacer", GLFW.GLFW_KEY_K, "newbase.name")); KeyBinding toggleYawSet = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggletest", GLFW.GLFW_KEY_J, "newbase.name")); ClientTickEvents.END_CLIENT_TICK.register(client -> { if(configScreen.wasPressed()){ mc.setScreen(new ConfigScreen(mc.currentScreen, mc.options)); } if(chatCoordinates.wasPressed()){ mc.setScreen(new ChatCoordinatesScreen(mc.currentScreen, mc.options)); } if(togglePlacer.wasPressed()){
package net.The2019.NewBase.utils; public class InitKeyBindings { private static final MinecraftClient mc = MinecraftClient.getInstance(); public static void initKeys(){ KeyBinding configScreen = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.configscreen", GLFW.GLFW_KEY_O, "newbase.name")); KeyBinding chatCoordinates = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.sendcoordinates", GLFW.GLFW_KEY_P, "newbase.name")); KeyBinding togglePlacer = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggleplacer", GLFW.GLFW_KEY_K, "newbase.name")); KeyBinding toggleYawSet = KeyBindingHelper.registerKeyBinding(new KeyBinding("newbase.keybinds.toggletest", GLFW.GLFW_KEY_J, "newbase.name")); ClientTickEvents.END_CLIENT_TICK.register(client -> { if(configScreen.wasPressed()){ mc.setScreen(new ConfigScreen(mc.currentScreen, mc.options)); } if(chatCoordinates.wasPressed()){ mc.setScreen(new ChatCoordinatesScreen(mc.currentScreen, mc.options)); } if(togglePlacer.wasPressed()){
MinecraftClient.getInstance().options.forwardKey.setPressed(!readModule(placer));
6
2023-10-28 10:33:51+00:00
4k
Ax3dGaming/Sons-Of-Sins-Organs-Addition
src/main/java/com/axed/compat/OrganCreationCategory.java
[ { "identifier": "ModBlocks", "path": "src/main/java/com/axed/block/ModBlocks.java", "snippet": "public class ModBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID);\n\n public static final RegistryObject<Block> ORGAN_CREATOR = registerBlock(\"organ_creator\", () -> new OrganCreatorBlock());\n\n\n\n private static <T extends Block> RegistryObject<T> registerBlock(String name, Supplier<T> block) {\n RegistryObject<T> toReturn = BLOCKS.register(name, block);\n registerBlockItem(name, toReturn);\n return toReturn;\n }\n\n private static <T extends Block> RegistryObject<Item> registerBlockItem(String name, RegistryObject<T> block) {\n return ModItems.ITEMS.register(name, () -> new BlockItem(block.get(), new Item.Properties()));\n }\n\n public static void register(IEventBus eventBus) {\n BLOCKS.register(eventBus);\n }\n}" }, { "identifier": "OrganCreatorRecipe", "path": "src/main/java/com/axed/recipe/OrganCreatorRecipe.java", "snippet": "public class OrganCreatorRecipe implements Recipe<SimpleContainer> {\n private final NonNullList<Ingredient> inputItems;\n private final ItemStack output;\n private final ResourceLocation id;\n\n public OrganCreatorRecipe(NonNullList<Ingredient> inputItems, ItemStack output, ResourceLocation id) {\n this.inputItems = inputItems;\n this.output = output;\n this.id = id;\n }\n\n @Override\n public boolean matches(SimpleContainer pContainer, Level pLevel) {\n if(pLevel.isClientSide()) {\n return false;\n }\n\n return inputItems.get(0).test(pContainer.getItem(0)) && inputItems.get(1).test(pContainer.getItem(1));\n }\n\n @Override\n public NonNullList<Ingredient> getIngredients() {\n return inputItems;\n }\n\n @Override\n public ItemStack assemble(SimpleContainer pContainer, RegistryAccess pRegistryAccess) {\n return output.copy();\n }\n\n @Override\n public boolean canCraftInDimensions(int pWidth, int pHeight) {\n return true;\n }\n\n @Override\n public ItemStack getResultItem(RegistryAccess pRegistryAccess) {\n return output.copy();\n }\n\n @Override\n public ResourceLocation getId() {\n return id;\n }\n\n @Override\n public RecipeSerializer<?> getSerializer() {\n return Serializer.INSTANCE;\n }\n\n @Override\n public RecipeType<?> getType() {\n return Type.INSTANCE;\n }\n\n public static class Type implements RecipeType<OrganCreatorRecipe> {\n private Type() {}\n public static final Type INSTANCE = new Type();\n public static final String ID = \"organ_creation\";\n }\n\n public static class Serializer implements RecipeSerializer<OrganCreatorRecipe> {\n public static final Serializer INSTANCE = new Serializer();\n public static final ResourceLocation ID = new ResourceLocation(sosorgans.MODID, \"organ_creation\");\n\n @Override\n public OrganCreatorRecipe fromJson(ResourceLocation id, JsonObject json) {\n ItemStack output = ShapedRecipe.itemStackFromJson(GsonHelper.getAsJsonObject(json, \"output\"));\n\n JsonArray ingredients = GsonHelper.getAsJsonArray(json, \"ingredients\");\n NonNullList<Ingredient> inputs = NonNullList.withSize(2, Ingredient.EMPTY);\n\n for(int i = 0; i < inputs.size(); i++) {\n inputs.set(i, Ingredient.fromJson(ingredients.get(i)));\n }\n\n return new OrganCreatorRecipe(inputs, output, id);\n }\n\n @Override\n public @Nullable OrganCreatorRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf buf) {\n NonNullList<Ingredient> inputs = NonNullList.withSize(buf.readInt(), Ingredient.EMPTY);\n\n for(int i = 0; i < inputs.size(); i++) {\n inputs.set(i, Ingredient.fromNetwork(buf));\n }\n\n ItemStack output = buf.readItem();\n return new OrganCreatorRecipe(inputs, output, id);\n }\n\n @Override\n public void toNetwork(FriendlyByteBuf buf, OrganCreatorRecipe recipe) {\n buf.writeInt(recipe.getIngredients().size());\n\n for (Ingredient ing : recipe.getIngredients()) {\n ing.toNetwork(buf);\n }\n\n buf.writeItemStack(recipe.getResultItem(null), false);\n }\n }\n}" }, { "identifier": "sosorgans", "path": "src/main/java/com/axed/sosorgans.java", "snippet": "@Mod(sosorgans.MODID)\npublic class sosorgans\n{\n public static final String MODID = \"sosorgans\";\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public sosorgans()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n SERIALIZERS.register(modEventBus);\n BLOCKS.register(modEventBus);\n ITEMS.register(modEventBus);\n BLOCK_ENTITIES.register(modEventBus);\n CREATIVE_MODE_TABS.register(modEventBus);\n MENUS.register(modEventBus);\n\n MinecraftForge.EVENT_BUS.register(this);\n\n //modEventBus.addListener(this::addCreative);\n\n ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC);\n }\n\n private void commonSetup(final FMLCommonSetupEvent event){}\n\n //private void addCreative(BuildCreativeModeTabContentsEvent event)\n //{\n //if (event.getTabKey() == CreativeModeTabs.BUILDING_BLOCKS)\n //event.accept();\n //}\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n // Do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n MenuScreens.register(ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreatorScreen::new);\n }\n }\n}" } ]
import com.axed.block.ModBlocks; import com.axed.recipe.OrganCreatorRecipe; import com.axed.sosorgans; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.builder.IRecipeLayoutBuilder; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.recipe.IFocusGroup; import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeType; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack;
1,821
package com.axed.compat; public class OrganCreationCategory implements IRecipeCategory<OrganCreatorRecipe> { public static final ResourceLocation UID = new ResourceLocation(sosorgans.MODID, "organ_creation"); public static final ResourceLocation TEXTURE = new ResourceLocation(sosorgans.MODID, "textures/gui/organ_creator_gui_jei.png"); public static final RecipeType<OrganCreatorRecipe> ORGAN_CREATION_TYPE = new RecipeType<>(UID, OrganCreatorRecipe.class); private final IDrawable background; private final IDrawable icon; public OrganCreationCategory(IGuiHelper helper) { this.background = helper.createDrawable(TEXTURE, 0, 0, 176, 85);
package com.axed.compat; public class OrganCreationCategory implements IRecipeCategory<OrganCreatorRecipe> { public static final ResourceLocation UID = new ResourceLocation(sosorgans.MODID, "organ_creation"); public static final ResourceLocation TEXTURE = new ResourceLocation(sosorgans.MODID, "textures/gui/organ_creator_gui_jei.png"); public static final RecipeType<OrganCreatorRecipe> ORGAN_CREATION_TYPE = new RecipeType<>(UID, OrganCreatorRecipe.class); private final IDrawable background; private final IDrawable icon; public OrganCreationCategory(IGuiHelper helper) { this.background = helper.createDrawable(TEXTURE, 0, 0, 176, 85);
this.icon = helper.createDrawableIngredient(VanillaTypes.ITEM_STACK, new ItemStack(ModBlocks.ORGAN_CREATOR.get()));
0
2023-10-25 19:33:18+00:00
4k
DarlanNoetzold/anPerformaticEcommerce
src/main/java/tech/noetzold/anPerformaticEcommerce/security/controller/AuthenticationController.java
[ { "identifier": "CommerceItemController", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/controller/CommerceItemController.java", "snippet": "@CrossOrigin(origins = \"*\")\n@PreAuthorize(\"hasAnyRole('ADMIN', 'MANAGER', 'USER')\")\n@RestController\n@RequestMapping(\"/ecommerce/v1/commerceitem\")\npublic class CommerceItemController {\n\n @Autowired\n CommerceItemService commerceItemService;\n\n @Autowired\n private RabbitmqService rabbitmqService;\n\n private static final Logger logger = LoggerFactory.getLogger(CommerceItemController.class);\n\n @RequestMapping(method = RequestMethod.GET)\n public ResponseEntity<Collection<CommerceItem>> getAll() {\n Collection<CommerceItem> commerceItems = commerceItemService.findAllCommerceItem();\n if (commerceItems.isEmpty()) {\n logger.warn(\"No commerceItem register\");\n return new ResponseEntity<Collection<CommerceItem>>(HttpStatus.NO_CONTENT);\n }\n\n logger.info(\"commerceItems \"+commerceItems.size()+\" returned\");\n return new ResponseEntity<Collection<CommerceItem>>(commerceItems, HttpStatus.OK);\n }\n\n @RequestMapping(value = \"/{id}\", method = RequestMethod.GET)\n public ResponseEntity<CommerceItem> getCommerceItemById(@PathVariable(\"id\") String id) {\n CommerceItem commerceItem = null;\n try {\n commerceItem = commerceItemService.findCommerceItemById(UUID.fromString(id));\n } catch (Exception exception){\n logger.error(\"Error to get commerceItem\");\n return new ResponseEntity<CommerceItem>(HttpStatus.BAD_REQUEST);\n }\n logger.info(\"commerceItem \"+commerceItem.getCommerceItemId()+\" returned\");\n return new ResponseEntity<CommerceItem>(commerceItem, HttpStatus.OK);\n }\n\n @RequestMapping(value = \"/{id}\", method = RequestMethod.PUT)\n public ResponseEntity<CommerceItem> update(@RequestBody CommerceItem commerceItem, @PathVariable(\"id\") String id) {\n if (commerceItem == null) {\n logger.warn(\"commerceItem is null\");\n return new ResponseEntity<CommerceItem>(HttpStatus.BAD_REQUEST);\n }\n\n commerceItem = commerceItemService.updateCommerceItem(UUID.fromString(id), commerceItem);\n logger.info(\"Create commerceItem: \" + commerceItem);\n return new ResponseEntity<CommerceItem>(commerceItem, HttpStatus.CREATED);\n }\n\n @RequestMapping(method = RequestMethod.POST)\n public ResponseEntity<CommerceItem> save(@RequestBody CommerceItem commerceItem) {\n if (commerceItem == null) {\n logger.warn(\"commerceItem is null\");\n return new ResponseEntity<CommerceItem>(HttpStatus.BAD_REQUEST);\n }\n\n rabbitmqService.sendMessage(RabbitmqQueues.COMMERCE_ITEM_QUEUE, commerceItem);\n logger.info(\"Send message commerceItem: \" + commerceItem);\n return new ResponseEntity<CommerceItem>(commerceItem, HttpStatus.CREATED);\n }\n\n @DeleteMapping(\"/{id}\")\n public ResponseEntity<String> remover(@PathVariable(\"id\") String id) {\n try {\n commerceItemService.deleteCommerceItem(UUID.fromString(id));\n }catch (Exception ex){\n logger.error(\"Error to remove commerceItem\", ex);\n return new ResponseEntity<String>(id, HttpStatus.BAD_GATEWAY);\n }\n\n logger.info(\"Remove commerceItem: \" + id);\n return new ResponseEntity<String>(id, HttpStatus.OK);\n }\n}" }, { "identifier": "AuthenticationRequest", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/security/user/AuthenticationRequest.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AuthenticationRequest {\n\n private String email;\n String password;\n}" }, { "identifier": "AuthenticationResponse", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/security/user/AuthenticationResponse.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AuthenticationResponse {\n\n @JsonProperty(\"access_token\")\n private String accessToken;\n @JsonProperty(\"refresh_token\")\n private String refreshToken;\n}" }, { "identifier": "RegisterRequest", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/security/user/RegisterRequest.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class RegisterRequest {\n\n private String firstname;\n private String lastname;\n private String email;\n private String password;\n private Role role;\n}" }, { "identifier": "AuthenticationService", "path": "src/main/java/tech/noetzold/anPerformaticEcommerce/security/service/AuthenticationService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class AuthenticationService {\n private final UserRepository repository;\n private final TokenRepository tokenRepository;\n private final PasswordEncoder passwordEncoder;\n private final JwtService jwtService;\n private final AuthenticationManager authenticationManager;\n\n @Transactional\n public AuthenticationResponse register(RegisterRequest request) {\n var user = User.builder()\n .firstname(request.getFirstname())\n .lastname(request.getLastname())\n .email(request.getEmail())\n .password(passwordEncoder.encode(request.getPassword()))\n .role(request.getRole())\n .build();\n var savedUser = repository.save(user);\n var jwtToken = jwtService.generateToken(user);\n var refreshToken = jwtService.generateRefreshToken(user);\n saveUserToken(savedUser, jwtToken);\n return AuthenticationResponse.builder()\n .accessToken(jwtToken)\n .refreshToken(refreshToken)\n .build();\n }\n\n @Transactional\n public AuthenticationResponse authenticate(AuthenticationRequest request) {\n authenticationManager.authenticate(\n new UsernamePasswordAuthenticationToken(\n request.getEmail(),\n request.getPassword()\n )\n );\n var user = repository.findByEmail(request.getEmail())\n .orElseThrow();\n var jwtToken = jwtService.generateToken(user);\n var refreshToken = jwtService.generateRefreshToken(user);\n revokeAllUserTokens(user);\n saveUserToken(user, jwtToken);\n return AuthenticationResponse.builder()\n .accessToken(jwtToken)\n .refreshToken(refreshToken)\n .build();\n }\n\n @Transactional\n private void saveUserToken(User user, String jwtToken) {\n var token = Token.builder()\n .user(user)\n .token(jwtToken)\n .tokenType(TokenType.BEARER)\n .expired(false)\n .revoked(false)\n .build();\n tokenRepository.save(token);\n }\n\n @Transactional\n private void revokeAllUserTokens(User user) {\n var validUserTokens = tokenRepository.findAllValidTokenByUser(user.getId());\n if (validUserTokens.isEmpty())\n return;\n validUserTokens.forEach(token -> {\n token.setExpired(true);\n token.setRevoked(true);\n });\n tokenRepository.saveAll(validUserTokens);\n }\n\n @Transactional\n public void refreshToken(\n HttpServletRequest request,\n HttpServletResponse response\n ) throws IOException {\n final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);\n final String refreshToken;\n final String userEmail;\n if (authHeader == null ||!authHeader.startsWith(\"Bearer \")) {\n return;\n }\n refreshToken = authHeader.substring(7);\n userEmail = jwtService.extractUsername(refreshToken);\n if (userEmail != null) {\n var user = this.repository.findByEmail(userEmail)\n .orElseThrow();\n if (jwtService.isTokenValid(refreshToken, user)) {\n var accessToken = jwtService.generateToken(user);\n revokeAllUserTokens(user);\n saveUserToken(user, accessToken);\n var authResponse = AuthenticationResponse.builder()\n .accessToken(accessToken)\n .refreshToken(refreshToken)\n .build();\n new ObjectMapper().writeValue(response.getOutputStream(), authResponse);\n }\n }\n }\n}" } ]
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import tech.noetzold.anPerformaticEcommerce.controller.CommerceItemController; import tech.noetzold.anPerformaticEcommerce.security.user.AuthenticationRequest; import tech.noetzold.anPerformaticEcommerce.security.user.AuthenticationResponse; import tech.noetzold.anPerformaticEcommerce.security.user.RegisterRequest; import tech.noetzold.anPerformaticEcommerce.security.service.AuthenticationService; import java.io.IOException;
1,951
package tech.noetzold.anPerformaticEcommerce.security.controller; @RestController @RequestMapping("/ecommerce/v1/auth") @RequiredArgsConstructor public class AuthenticationController { private final AuthenticationService service; private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class); @PostMapping("/register")
package tech.noetzold.anPerformaticEcommerce.security.controller; @RestController @RequestMapping("/ecommerce/v1/auth") @RequiredArgsConstructor public class AuthenticationController { private final AuthenticationService service; private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class); @PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
2
2023-10-28 12:30:24+00:00
4k
gianlucameloni/shelly-em
src/main/java/com/gmeloni/shelly/service/ScheduledService.java
[ { "identifier": "GetEMStatusResponse", "path": "src/main/java/com/gmeloni/shelly/dto/rest/GetEMStatusResponse.java", "snippet": "@Data\npublic class GetEMStatusResponse {\n @JsonProperty(\"unixtime\")\n private Long unixTime;\n @JsonProperty(\"emeters\")\n private List<RawEMSample> rawEMSamples;\n}" }, { "identifier": "HourlyEMEnergy", "path": "src/main/java/com/gmeloni/shelly/model/HourlyEMEnergy.java", "snippet": "@Entity\n@Table(name = \"hourly_em_energy\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PUBLIC)\n@Getter\n@EqualsAndHashCode\n@NamedNativeQuery(\n name = \"SelectHourlyAggregateByYearMonthDay\",\n query = \"\"\"\n select\n hour(from_timestamp) as hour,\n grid_energy_in,\n grid_energy_out,\n pv_energy_in,\n pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and\n day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd'))\n order by\n hour desc\n \"\"\",\n resultSetMapping = \"SelectHourlyAggregateByYearMonthDayMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectHourlyAggregateByYearMonthDayMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"hour\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n },\n targetClass = HourlyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYearMonthDay\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd')) and\n day(from_timestamp) = day(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMonthDayMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMonthDayMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class),\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectDailyAggregateByYearMonth\",\n query = \"\"\"\n select\n day(from_timestamp) as day,\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd'))\n group by\n day(from_timestamp)\n order by\n day desc\n \"\"\",\n resultSetMapping = \"SelectDailyAggregateByYearMonthMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectDailyAggregateByYearMonthMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"day\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class)\n },\n targetClass = DailyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYearMonth\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd')) and\n month(from_timestamp) = month(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMonthMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMonthMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectMonthlyAggregateByYear\",\n query = \"\"\"\n select\n month(from_timestamp) as month,\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd'))\n group by\n year(from_timestamp), month(from_timestamp)\n order by\n month desc\n \"\"\",\n resultSetMapping = \"SelectMonthlyAggregateByYearMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectMonthlyAggregateByYearMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"month\", type = String.class),\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class)\n },\n targetClass = MonthlyAggregate.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotalsByYear\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n where\n year(from_timestamp) = year(to_date(:filterDate,'yyyy-MM-dd'))\n \"\"\",\n resultSetMapping = \"SelectTotalsByYearMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsByYearMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\n@NamedNativeQuery(\n name = \"SelectTotals\",\n query = \"\"\"\n select\n sum(grid_energy_in) as grid_energy_in,\n sum(grid_energy_out) as grid_energy_out,\n sum(pv_energy_in) as pv_energy_in,\n sum(pv_energy_out) as pv_energy_out,\n sum(pv_energy_out) - sum(grid_energy_out) as pv_energy_consumed\n from\n hourly_em_energy\n \"\"\",\n resultSetMapping = \"SelectTotalsMapping\"\n)\n@SqlResultSetMapping(\n name = \"SelectTotalsMapping\",\n classes = {\n @ConstructorResult(\n columns = {\n @ColumnResult(name = \"grid_energy_in\", type = Double.class),\n @ColumnResult(name = \"grid_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_in\", type = Double.class),\n @ColumnResult(name = \"pv_energy_out\", type = Double.class),\n @ColumnResult(name = \"pv_energy_consumed\", type = Double.class)\n },\n targetClass = EnergyTotals.class\n )\n }\n)\npublic class HourlyEMEnergy implements Serializable {\n @Id\n @Column(name = \"from_timestamp\")\n private LocalDateTime fromTimestamp;\n @Column(name = \"to_timestamp\")\n private LocalDateTime toTimestamp;\n @Column(name = \"grid_energy_in\")\n private Double gridEnergyIn;\n @Column(name = \"grid_energy_out\")\n private Double gridEnergyOut;\n @Column(name = \"pv_energy_in\")\n private Double pvEnergyIn;\n @Column(name = \"pv_energy_out\")\n private Double pvEnergyOut;\n @Column(name = \"max_grid_voltage\")\n private Double maxGridVoltage;\n @Column(name = \"min_grid_voltage\")\n private Double minGridVoltage;\n @Column(name = \"max_pv_voltage\")\n private Double maxPvVoltage;\n @Column(name = \"min_pv_voltage\")\n private Double minPvVoltage;\n}" }, { "identifier": "RawEMData", "path": "src/main/java/com/gmeloni/shelly/model/RawEMData.java", "snippet": "@Entity\n@Table(name = \"raw_em_data\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PUBLIC)\n@Getter\n@EqualsAndHashCode\npublic class RawEMData implements Serializable {\n @Id\n @Column(name = \"sample_timestamp\")\n private LocalDateTime sampleTimestamp;\n @Column(name = \"grid_power\")\n private Double gridPower;\n @Column(name = \"pv_power\")\n private Double pvPower;\n @Column(name = \"grid_voltage\")\n private Double gridVoltage;\n @Column(name = \"pv_voltage\")\n private Double pvVoltage;\n}" }, { "identifier": "HourlyEMEnergyRepository", "path": "src/main/java/com/gmeloni/shelly/repository/HourlyEMEnergyRepository.java", "snippet": "@Repository\npublic interface HourlyEMEnergyRepository extends CrudRepository<HourlyEMEnergy, LocalDateTime> {\n}" }, { "identifier": "RawEMDataRepository", "path": "src/main/java/com/gmeloni/shelly/repository/RawEMDataRepository.java", "snippet": "@Repository\npublic interface RawEMDataRepository extends CrudRepository<RawEMData, LocalDateTime> {\n\n @Query(value = \"select * from raw_em_data where sample_timestamp >= ?1 and sample_timestamp < ?2\", nativeQuery = true)\n List<RawEMData> findAllBySampleTimestampBetween(LocalDateTime from, LocalDateTime to);\n\n RawEMData findTopByOrderBySampleTimestampDesc();\n\n}" }, { "identifier": "DATE_AND_TIME_FORMAT", "path": "src/main/java/com/gmeloni/shelly/Constants.java", "snippet": "public static final String DATE_AND_TIME_FORMAT = \"yyyy-MM-dd HH:mm:ss\";" } ]
import com.gmeloni.shelly.dto.rest.GetEMStatusResponse; import com.gmeloni.shelly.model.HourlyEMEnergy; import com.gmeloni.shelly.model.RawEMData; import com.gmeloni.shelly.repository.HourlyEMEnergyRepository; import com.gmeloni.shelly.repository.RawEMDataRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.TimeZone; import static com.gmeloni.shelly.Constants.DATE_AND_TIME_FORMAT;
3,167
package com.gmeloni.shelly.service; @Service public class ScheduledService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); @Autowired private RawEMDataService rawEMDataService; @Autowired private RawEMDataRepository rawEmDataRepository; @Autowired private HourlyEMEnergyRepository hourlyEMEnergyRepository; @Value("${raw-em.sampling.period.milliseconds}") private String samplingPeriodInMilliseconds; @Value("${raw-em.sampling.threshold}") private Double samplingThreshold; @Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}") public void processRawEMData() {
package com.gmeloni.shelly.service; @Service public class ScheduledService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT); @Autowired private RawEMDataService rawEMDataService; @Autowired private RawEMDataRepository rawEmDataRepository; @Autowired private HourlyEMEnergyRepository hourlyEMEnergyRepository; @Value("${raw-em.sampling.period.milliseconds}") private String samplingPeriodInMilliseconds; @Value("${raw-em.sampling.threshold}") private Double samplingThreshold; @Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}") public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
0
2023-10-26 19:52:00+00:00
4k
DimitarDSimeonov/ShopApp
src/test/java/bg/softuni/shop_app/service/impl/ProductServiceImplTest.java
[ { "identifier": "MyTime", "path": "src/main/java/bg/softuni/shop_app/helper/MyTime.java", "snippet": "@Configuration\npublic class MyTime {\n @Bean\n public LocalDateTime getNow() {\n return LocalDateTime.now();\n }\n}" }, { "identifier": "AddProductDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/product/AddProductDTO.java", "snippet": "@Getter\n@Setter\npublic class AddProductDTO {\n\n @NotBlank(message = \"Моля въведете заглавие!\")\n private String title;\n\n @NotBlank(message = \"Моля въведете описание!\")\n private String description;\n\n @NotNull(message = \"Моля Въведете цена!\")\n @Positive(message = \"Цената не може да бъде отрицателна!\")\n private BigDecimal price;\n private Category category;\n private Location location;\n private String pictureURL;\n\n}" }, { "identifier": "ProductOwnerViewDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/product/ProductOwnerViewDTO.java", "snippet": "@Getter\n@Setter\npublic class ProductOwnerViewDTO {\n\n private Long id;\n private String title;\n private String description;\n private BigDecimal price;\n private Category category;\n private Location location;\n private List<Picture> pictures;\n\n public ProductOwnerViewDTO() {\n pictures = new ArrayList<>();\n }\n\n}" }, { "identifier": "ProductSearchDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/product/ProductSearchDTO.java", "snippet": "@Getter\n@Setter\npublic class ProductSearchDTO {\n\n private String title;\n @DecimalMin(value = \"0.1\", message = \"Цената не може да бъде отрицателна!\")\n private BigDecimal maxPrice;\n private Location location;\n private Category category;\n}" }, { "identifier": "ProductViewDTO", "path": "src/main/java/bg/softuni/shop_app/model/dto/product/ProductViewDTO.java", "snippet": "@Getter\n@Setter\npublic class ProductViewDTO {\n\n private Long id;\n private String title;\n private String description;\n private BigDecimal price;\n private Category category;\n private Location location;\n private List<Picture> pictures;\n private User seller;\n}" }, { "identifier": "Product", "path": "src/main/java/bg/softuni/shop_app/model/entity/Product.java", "snippet": "@Getter\n@Setter\n@Entity\n@Table(name = \"products\")\npublic class Product extends BaseEntity{\n\n @Column(nullable = false)\n private String title;\n\n @Column(columnDefinition = \"TEXT\", nullable = false)\n private String description;\n\n @Column(name = \"price\", nullable = false)\n private BigDecimal price;\n\n @Enumerated(EnumType.STRING)\n private Category category;\n\n @Column(name = \"date_of_post\")\n private LocalDateTime dateOfPost;\n\n @Enumerated(EnumType.STRING)\n private Location location;\n\n @OneToMany(mappedBy = \"product\")\n private List<Comment> comments;\n\n @OneToMany(mappedBy = \"product\", fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n private List<Picture> pictures;\n\n @ManyToOne\n private User seller;\n\n public Product() {\n pictures = new ArrayList<>();\n }\n}" }, { "identifier": "User", "path": "src/main/java/bg/softuni/shop_app/model/entity/User.java", "snippet": "@Getter\n@Setter\n@Entity\n@Table(name = \"users\")\npublic class User extends BaseEntity{\n\n @Column(nullable = false, unique = true)\n private String username;\n\n @Column(nullable = false)\n private String password;\n\n @Column(name = \"first_name\", nullable = false)\n private String firstName;\n\n @Column(name = \"last_name\", nullable = false)\n private String lastName;\n\n @Column(nullable = false, unique = true)\n private String email;\n\n @Column(name = \"phone_number\", nullable = false, unique = true)\n private String phoneNumber;\n\n @OneToOne(mappedBy = \"user\")\n private OrderHistory orderHistory;\n\n @OneToOne(mappedBy = \"user\")\n private Order order;\n\n @ManyToMany(fetch = FetchType.EAGER)\n private List<Role> roles;\n\n @OneToOne(mappedBy = \"user\")\n private Picture picture;\n\n @OneToMany(mappedBy = \"seller\", fetch = FetchType.EAGER)\n private List<Product> offerProduct;\n\n public User() {\n roles = new ArrayList<>();\n }\n}" }, { "identifier": "ProductRepository", "path": "src/main/java/bg/softuni/shop_app/repository/ProductRepository.java", "snippet": "@Repository\npublic interface ProductRepository extends JpaRepository<Product, Long> {\n\n Optional<List<Product>> findAllByDateOfPostBefore(LocalDateTime localDateTime);\n\n List<Product> findByTitleContainingIgnoreCaseAndPriceLessThanEqualAndLocationAndCategory(String title, BigDecimal price, Location location, Category category);\n\n @Query(\"SELECT p FROM Product p ORDER BY p.dateOfPost DESC LIMIT 10\")\n List<Product> findTop10OrderByDateOfPostDesc();\n}" }, { "identifier": "ProductService", "path": "src/main/java/bg/softuni/shop_app/service/ProductService.java", "snippet": "public interface ProductService {\n Long createProduct(AddProductDTO addProductDTO, String username);\n\n void deleteById(Long id);\n\n ProductOwnerViewDTO getOwnerViewById(Long id);\n\n Product getById(Long id);\n\n List<ProductViewDTO> searchByInput(ProductSearchDTO productSearchDTO);\n\n ProductViewDTO getDetailsViewById(Long id);\n\n void clearOldProduct();\n\n List<ProductViewDTO> getLastProducts();\n\n List<ProductViewDTO> getAllProducts();\n}" }, { "identifier": "UserService", "path": "src/main/java/bg/softuni/shop_app/service/UserService.java", "snippet": "public interface UserService {\n\n boolean existUsername(String username);\n\n boolean existEmail(String email);\n\n boolean existPhoneNumber(String phoneNumber);\n\n void register(UserRegisterDTO userRegisterDTO);\n\n User getByUsername(String username);\n\n List<ProductHomePageViewDTO> getMyOffers(String username);\n\n List<UserViewDTO> getAllUsers(String username);\n\n void addAdminRole(Long id);\n\n void removeAdminRole(Long id);\n}" } ]
import bg.softuni.shop_app.helper.MyTime; import bg.softuni.shop_app.model.dto.product.AddProductDTO; import bg.softuni.shop_app.model.dto.product.ProductOwnerViewDTO; import bg.softuni.shop_app.model.dto.product.ProductSearchDTO; import bg.softuni.shop_app.model.dto.product.ProductViewDTO; import bg.softuni.shop_app.model.entity.Product; import bg.softuni.shop_app.model.entity.User; import bg.softuni.shop_app.repository.ProductRepository; import bg.softuni.shop_app.service.ProductService; import bg.softuni.shop_app.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.modelmapper.ModelMapper; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*;
1,800
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class ProductServiceImplTest { private ProductService productServiceToTest; @Mock private UserService mockUserService; @Mock private ModelMapper mockModelMapper; @Mock private ProductRepository mockProductRepository; @Mock private MyTime mockMyTime; @BeforeEach void setUp() { productServiceToTest = new ProductServiceImpl(mockUserService, mockModelMapper, mockProductRepository, mockMyTime); } @Test void createProduct() { AddProductDTO addProductDTO = new AddProductDTO(); User user = new User();
package bg.softuni.shop_app.service.impl; @ExtendWith(MockitoExtension.class) class ProductServiceImplTest { private ProductService productServiceToTest; @Mock private UserService mockUserService; @Mock private ModelMapper mockModelMapper; @Mock private ProductRepository mockProductRepository; @Mock private MyTime mockMyTime; @BeforeEach void setUp() { productServiceToTest = new ProductServiceImpl(mockUserService, mockModelMapper, mockProductRepository, mockMyTime); } @Test void createProduct() { AddProductDTO addProductDTO = new AddProductDTO(); User user = new User();
Product product = new Product();
5
2023-10-27 13:33:23+00:00
4k
achrafaitibba/invoiceYou
src/main/java/com/onxshield/invoiceyou/invoicestatement/controller/invoiceController.java
[ { "identifier": "action", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/action.java", "snippet": "public enum action {\n ADDED,\n DELETED,\n NOT_YET\n}" }, { "identifier": "invoice", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/invoice.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\n@Component\n@Table(name = \"invoice_statement\")\npublic class invoice {\n\n @Id\n @Column(name = \"invoice_id\")\n private String invoiceId;\n\n @Column(name = \"invoice_date\")\n @NotNull\n @Temporal(TemporalType.DATE)\n private Date invoiceDate;\n\n\n @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})\n @JoinColumn(name = \"fk_client_id\", referencedColumnName = \"client_id\")\n @NotNull\n private client client;\n\n @NotNull\n private Long totalTTC;\n\n @NotNull\n private String spelledTotal;\n\n private Double TVA;\n\n @NotNull\n @Enumerated(EnumType.STRING)\n private paymentMethod paymentMethod;\n\n private String bankName;\n\n private Double discount;\n\n private Integer checkNumber;\n\n @Temporal(TemporalType.DATE)\n private Date paymentDate;\n\n @OneToMany(mappedBy = \"invoice\", cascade = CascadeType.ALL)\n private List<merchandise> merchandiseList;\n\n private Boolean printed = false;\n\n @Enumerated(EnumType.STRING)\n private action invoiceAction = action.NOT_YET;\n\n @Enumerated(EnumType.STRING)\n private status invoiceStatus = status.NOT_YET;\n\n private String invoiceFile = \"\"; //todo, link to file in localstorage\n}" }, { "identifier": "paymentMethod", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/paymentMethod.java", "snippet": "public enum paymentMethod {\n CHQ,\n EFF_LCN,\n BANK_TRANSFER,\n CASH\n}" }, { "identifier": "status", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/model/status.java", "snippet": "public enum status {\n DONE,\n NOT_YET\n}" }, { "identifier": "invoiceService", "path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/service/invoiceService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional\npublic class invoiceService {\n\n private final invoiceRepository invoiceRepository;\n private final clientRepository clientRepository;\n private final inventoryRepository inventoryRepository;\n private final productRepository productRepository;\n private final merchandiseRepository merchandiseRepository;\n private final invoiceNumberRepository invoiceNumberRepository;\n static long latestInvoiceNumber = 1225;\n\n public invoice createBasicInvoice(invoiceRequest request) {\n //find inventory by product id\n //check availability\n //get the sell price\n //calculate total by product = sell price * quantity\n //add the total by product to totalTTC\n //decrease availability in the inventory\n //BUILD the merchandise instances\n\n Optional<client> client = clientRepository.findById(request.clientId());\n if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {\n deleteInvoiceNumberByInvoiceNumber(request.invoiceId());\n List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);\n invoice invoiceToSave = new invoice();\n invoiceToSave.setInvoiceId(request.invoiceId());\n invoiceToSave.setInvoiceDate(request.invoiceDate());\n invoiceToSave.setClient(client.get());\n invoiceToSave.setTotalTTC(request.totalTTC());\n invoiceToSave.setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));\n invoiceToSave.setSpelledTotal(convertNumberToWords(request.totalTTC().longValue()));\n invoiceToSave.setMerchandiseList(savedMerchandise);\n invoiceToSave.setCheckNumber(request.checkNumber());\n invoiceToSave.setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));\n invoiceToSave.setDiscount(request.discount());\n invoice saved = invoiceRepository.save(invoiceToSave);\n\n for (merchandise merch : savedMerchandise\n ) {\n Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());\n toUpdate.get().setInvoice(saved);\n }\n return saved;\n } else {\n throw new requestException(\"The Id you provided already used by other invoice\", HttpStatus.CONFLICT);\n }\n }\n\n public String convertNumberToWords(Long total) {\n return numberToWordUtil.convert(total).toUpperCase();\n }\n\n public String[] getAvailableInvoiceNumbers() {\n List<String> numbers = invoiceNumberRepository.findAll()\n .stream()\n .map(invoiceNumber::getInvoiceNumber)\n .toList();\n return numbers.toArray(new String[0]);\n }\n\n public String generateInvoiceNumber() {\n int currentYear = Year.now().getValue();\n int lastTwoDigits = currentYear % 100;\n latestInvoiceNumber++;\n String toSave = \"ST\" + latestInvoiceNumber + \"/\" + String.format(\"%02d\", lastTwoDigits);\n invoiceNumberRepository.save(new invoiceNumber(toSave));\n latestInvoiceNumber++;\n return \"ST\" + latestInvoiceNumber + \"/\" + String.format(\"%02d\", lastTwoDigits);\n\n }\n\n public invoice getInvoiceById(String invoiceId) {\n Optional<invoice> invoice = invoiceRepository.findById(invoiceId);\n if (invoice.isPresent()) {\n return invoice.get();\n } else throw new requestException(\"The Id you provided doesn't exist\", HttpStatus.CONFLICT);\n }\n\n public basicInvoiceResponse getBasicInvoiceById(String invoiceId) {\n invoice invoice = getInvoiceById(invoiceId);\n return new basicInvoiceResponse(\n invoice.getClient().getName(),\n invoice.getInvoiceId(),\n invoice.getClient().getICE(),\n invoice.getInvoiceDate(),\n invoice.getMerchandiseList().stream().map(\n\n merchandise -> new merchandiseResponse(\n merchandise.getMerchId(),\n merchandise.getProduct().getName(),\n merchandise.getProduct().getUnit().toString(),\n merchandise.getQuantity(),\n inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice(),\n merchandise.getQuantity().longValue() * inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice().longValue()\n )\n )\n .toList(),\n invoice.getTotalTTC(),\n invoice.getTVA(),\n invoice.getSpelledTotal(),\n invoice.getPaymentMethod().toString(),\n invoice.getCheckNumber(),\n invoice.getDiscount()\n );\n }\n\n public Page<invoice> getAllInvoices(Integer pageNumber, Integer size, String direction, String sortBy) {\n Sort soring = Sort.by(Sort.Direction.valueOf(direction.toUpperCase()), sortBy);\n Pageable page = PageRequest.of(pageNumber, size, soring);\n return invoiceRepository.findAll(page);\n }\n\n public List<merchandise> merchandiseRequestToMerchandise(invoiceRequest request) {\n return request.merchandiseList().stream()\n .map(\n\n merchandiseRequest -> {\n merchandise merchandiseToSave;\n Optional<inventory> inventory = inventoryRepository.findByProductProductId(merchandiseRequest.productId());\n Double availability = inventory.get().getAvailability();\n if (availability >= merchandiseRequest.quantity() && availability > 0) {\n Double totalByProduct = merchandiseRequest.quantity() * inventory.get().getSellPrice();\n inventory.get().setAvailability(availability - merchandiseRequest.quantity());\n merchandiseToSave = new merchandise();\n merchandiseToSave.setProduct(productRepository.findById(merchandiseRequest.productId()).get());\n merchandiseToSave.setQuantity(merchandiseRequest.quantity());\n merchandiseToSave.setTotal(totalByProduct);\n return merchandiseRepository.save(merchandiseToSave);\n } else {\n throw new requestException(\"Product isn't available in the inventory, out of stock\", HttpStatus.CONFLICT);\n }\n }\n )\n .toList();\n }\n\n public invoice createInvoice(invoiceRequest request) {\n Optional<client> client = clientRepository.findById(request.clientId());\n if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {\n deleteInvoiceNumberByInvoiceNumber(request.invoiceId());\n List<merchandise> savedMerchandise = null;\n if (request.merchandiseList() != null) {\n savedMerchandise = merchandiseRequestToMerchandise(request);\n }\n invoice invoiceToSave = invoice.builder()\n .invoiceId(request.invoiceId())\n .invoiceDate(request.invoiceDate())\n .client(client.get())\n .totalTTC(request.totalTTC())\n .TVA(twoDigitTVA(request.totalTTC().doubleValue() / 6))\n .spelledTotal(numberToWordUtil.convert(request.totalTTC()))\n .paymentMethod(paymentMethod.valueOf(request.paymentMethod()))\n .bankName(request.bankName())\n .checkNumber(request.checkNumber())\n .paymentDate(request.paymentDate())\n .printed(Boolean.valueOf(request.printed()))\n .invoiceAction(action.valueOf(request.invoiceAction()))\n .invoiceStatus(status.valueOf(request.invoiceStatus()))\n .invoiceFile(request.invoiceFile())\n .merchandiseList(savedMerchandise)\n .discount(request.discount())\n .build();\n invoice saved = invoiceRepository.save(invoiceToSave);\n if (request.merchandiseList() != null) {\n //savedMerchandise = merchandiseRequestToMerchandise(request);\n for (merchandise merch : savedMerchandise\n ) {\n Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());\n toUpdate.get().setInvoice(saved);\n }\n }\n\n return saved;\n } else throw new requestException(\"Invoice already exist\", HttpStatus.CONFLICT);\n }\n\n private void deleteInvoiceNumberByInvoiceNumber(String invoiceNumber) {\n Optional<invoiceNumber> invoiceN = invoiceNumberRepository.findById(invoiceNumber);\n if (invoiceN.isPresent()) {\n invoiceNumberRepository.deleteById(invoiceNumber);\n }\n }\n\n\n public invoice updateInvoice(invoiceRequest request) {\n\n // update the invoice ID? if yes (merchandise should be updated also)\n // and the list of available ID should have a new record (the previous Invoice id)\n /////////////////////////////////////////\n Optional<invoice> toUpdate = invoiceRepository.findById(request.invoiceId());\n if (toUpdate.isPresent()) {\n Optional<client> client = clientRepository.findById(request.clientId());\n toUpdate.get().setInvoiceDate(request.invoiceDate());\n toUpdate.get().setClient(client.get());\n toUpdate.get().setTotalTTC(request.totalTTC());\n toUpdate.get().setSpelledTotal(convertNumberToWords(request.totalTTC()));\n toUpdate.get().setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));\n toUpdate.get().setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));\n toUpdate.get().setBankName(request.bankName());\n toUpdate.get().setCheckNumber(request.checkNumber());\n toUpdate.get().setPaymentDate(request.paymentDate());\n toUpdate.get().setPrinted(Boolean.valueOf(request.printed()));\n toUpdate.get().setInvoiceAction(action.valueOf(request.invoiceAction()));\n toUpdate.get().setInvoiceStatus(status.valueOf(request.invoiceStatus()));\n toUpdate.get().setInvoiceFile(request.invoiceFile());\n toUpdate.get().setDiscount(request.discount());\n\n if (merchandiseRepository.findAllByInvoice_InvoiceId(request.invoiceId()) != null) {\n deleteAllMerchandiseUpdateInventory(request.invoiceId());\n List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);\n for (merchandise merch : savedMerchandise\n ) {\n Optional<merchandise> merchToUpdate = merchandiseRepository.findById(merch.getMerchId());\n merchToUpdate.get().setInvoice(toUpdate.get());\n }\n }\n\n return invoiceRepository.save(toUpdate.get());\n } else throw new requestException(\"The invoice doesn't exist\", HttpStatus.NOT_FOUND);\n }\n\n public void deleteAllMerchandiseUpdateInventory(String invoiceId) {\n List<merchandise> merchandiseList = merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId);\n if (merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId) != null) {\n for (merchandise merch : merchandiseList\n ) {\n Optional<inventory> toUpdate = inventoryRepository.findByProductProductId(merch.getProduct().getProductId());\n Double availableQuantity = toUpdate.get().getAvailability();\n toUpdate.get().setAvailability(availableQuantity + merch.getQuantity());\n }\n merchandiseRepository.deleteByInvoice_InvoiceId(invoiceId);\n }\n }\n\n public double twoDigitTVA(Double tva) {\n\n return doubleTwoDigitConverter.twoDigitTVA(tva);\n }\n\n public void deleteInvoiceById(String invoiceId) {\n Optional<invoice> toDelete = invoiceRepository.findById(invoiceId);\n if (toDelete.isPresent()) {\n deleteAllMerchandiseUpdateInventory(invoiceId);\n invoiceRepository.deleteById(invoiceId);\n invoiceNumberRepository.save(invoiceNumber.builder().invoiceNumber(invoiceId).build());\n } else throw new requestException(\"The invoice id you provided doesn't exist\", HttpStatus.NOT_FOUND);\n }\n\n\n}" } ]
import com.onxshield.invoiceyou.invoicestatement.dto.request.invoiceRequest; import com.onxshield.invoiceyou.invoicestatement.dto.response.basicInvoiceResponse; import com.onxshield.invoiceyou.invoicestatement.dto.response.merchandiseResponse; import com.onxshield.invoiceyou.invoicestatement.model.action; import com.onxshield.invoiceyou.invoicestatement.model.invoice; import com.onxshield.invoiceyou.invoicestatement.model.paymentMethod; import com.onxshield.invoiceyou.invoicestatement.model.status; import com.onxshield.invoiceyou.invoicestatement.service.invoiceService; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
3,352
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/invoices") @RequiredArgsConstructor public class invoiceController { private final invoiceService invoiceService; @GetMapping("/status") public ResponseEntity<status[]> allStatus() { return ResponseEntity.ok(status.values()); } @GetMapping("/payMethods")
package com.onxshield.invoiceyou.invoicestatement.controller; @RestController @RequestMapping("/api/v1/invoices") @RequiredArgsConstructor public class invoiceController { private final invoiceService invoiceService; @GetMapping("/status") public ResponseEntity<status[]> allStatus() { return ResponseEntity.ok(status.values()); } @GetMapping("/payMethods")
public ResponseEntity<paymentMethod[]> paymentMethods() {
2
2023-10-29 11:16:37+00:00
4k
Melledy/LunarCore
src/main/java/emu/lunarcore/data/excel/RelicExcel.java
[ { "identifier": "GameData", "path": "src/main/java/emu/lunarcore/data/GameData.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class GameData {\n // Excels\n @Getter private static Int2ObjectMap<AvatarExcel> avatarExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemExcel> itemExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemUseExcel> itemUseExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<EquipmentExcel> equipExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RelicExcel> relicExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PropExcel> propExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<NpcExcel> npcExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<SummonUnitExcel> summonUnitExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MonsterExcel> monsterExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<NpcMonsterExcel> npcMonsterExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<StageExcel> stageExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MazePlaneExcel> mazePlaneExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<MapEntranceExcel> mapEntranceExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<HeroExcel> heroExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ShopExcel> shopExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RewardExcel> rewardExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<InteractExcel> interactExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PlayerIconExcel> playerIconExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ItemComposeExcel> itemComposeExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ActivityPanelExcel> activityPanelExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<BackGroundMusicExcel> backGroundMusicExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<QuestExcel> questExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<TextJoinExcel> textJoinExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChatBubbleExcel> chatBubbleExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<PhoneThemeExcel> phoneThemeExcelMap = new Int2ObjectOpenHashMap<>();\n\n @Getter private static Int2ObjectMap<ChallengeGroupExcel> challengeGroupExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChallengeExcel> challengeExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<ChallengeTargetExcel> challengeTargetExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<ChallengeRewardExcel> challengeRewardExcelMap = new Int2ObjectOpenHashMap<>();\n \n @Getter private static Int2ObjectMap<RogueManagerExcel> rogueManagerExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueTalentExcel> rogueTalentExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueAeonExcel> rogueAeonExcelMap = new Int2ObjectLinkedOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueAreaExcel> rogueAreaExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueRoomExcel> rogueRoomExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueMapExcel> rogueMapExcelMap = new Int2ObjectOpenHashMap<>();\n @Getter private static Int2ObjectMap<RogueMonsterExcel> rogueMonsterExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RogueBuffExcel> rogueBuffExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<AvatarPromotionExcel> avatarPromotionExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<AvatarSkillTreeExcel> avatarSkillTreeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<AvatarRankExcel> avatarRankExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<EquipmentPromotionExcel> equipmentPromotionExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MazeBuffExcel> mazeBuffExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<CocoonExcel> cocoonExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MappingInfoExcel> mappingInfoExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<MonsterDropExcel> monsterDropExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<PlayerLevelExcel> playerLevelExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<ExpTypeExcel> expTypeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<EquipmentExpTypeExcel> equipmentExpTypeExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicExpTypeExcel> relicExpTypeExcelMap = new Int2ObjectOpenHashMap<>();\n \n private static Int2ObjectMap<RelicMainAffixExcel> relicMainAffixExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicSubAffixExcel> relicSubAffixExcelMap = new Int2ObjectOpenHashMap<>();\n private static Int2ObjectMap<RelicSetExcel> relicSetExcelMap = new Int2ObjectOpenHashMap<>();\n \n // Configs (Bin)\n @Getter private static Object2ObjectMap<String, FloorInfo> floorInfos = new Object2ObjectOpenHashMap<>();\n\n public static Int2ObjectMap<?> getMapForExcel(Class<?> resourceDefinition) {\n Int2ObjectMap<?> map = null;\n\n try {\n Field field = GameData.class.getDeclaredField(Utils.lowerCaseFirstChar(resourceDefinition.getSimpleName()) + \"Map\");\n field.setAccessible(true);\n\n map = (Int2ObjectMap<?>) field.get(null);\n\n field.setAccessible(false);\n } catch (Exception e) {\n\n }\n\n return map;\n }\n\n public static List<Integer> getAllRelicIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<RelicExcel> entry : relicExcelMap.int2ObjectEntrySet()) {\n RelicExcel relicExcel = entry.getValue();\n allIds.add(relicExcel.getId());\n }\n\n return allIds;\n }\n\n public static int getRelicSetFromId(int relicId) {\n RelicExcel relicExcel = GameData.getRelicExcelMap().get(relicId);\n\n if (relicExcel == null) {\n return 0;\n }\n return relicExcel.getSetId();\n }\n\n public static List<Integer> getAllMusicIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<BackGroundMusicExcel> entry : backGroundMusicExcelMap.int2ObjectEntrySet()) {\n BackGroundMusicExcel backGroundMusicExcel = entry.getValue();\n allIds.add(backGroundMusicExcel.getId());\n }\n\n return allIds;\n }\n\n public static int TextJoinItemFromId(int id) {\n for (Int2ObjectMap.Entry<TextJoinExcel> entry : textJoinExcelMap.int2ObjectEntrySet()) {\n TextJoinExcel textJoinExcel = entry.getValue();\n if (textJoinExcel.getId() == id) {\n IntArrayList textJoinItemList = textJoinExcel.getTextJoinItemList();\n if (textJoinItemList.size() > 0) {\n return textJoinItemList.getInt(textJoinItemList.size() - 1);\n }\n }\n }\n return id * 10; // or return a default value if needed\n }\n \n public static List<Integer> getAllMonsterIds() {\n List<Integer> allIds = new ArrayList<>();\n\n for (Int2ObjectMap.Entry<MonsterExcel> entry : monsterExcelMap.int2ObjectEntrySet()) {\n MonsterExcel monsterExcel = entry.getValue();\n allIds.add(monsterExcel.getId());\n }\n\n return allIds;\n }\n\n public static int getMusicGroupId(int musicId) {\n var excel = backGroundMusicExcelMap.get(musicId);\n return excel != null ? excel.getGroupId() : 0;\n }\n \n public static AvatarPromotionExcel getAvatarPromotionExcel(int id, int promotion) {\n return avatarPromotionExcelMap.get((id << 8) + promotion);\n }\n\n public static AvatarSkillTreeExcel getAvatarSkillTreeExcel(int skill, int level) {\n return avatarSkillTreeExcelMap.get((skill << 4) + level);\n }\n\n public static AvatarRankExcel getAvatarRankExcel(int rankId) {\n return avatarRankExcelMap.get(rankId);\n }\n\n public static EquipmentPromotionExcel getEquipmentPromotionExcel(int id, int promotion) {\n return equipmentPromotionExcelMap.get((id << 8) + promotion);\n }\n\n public static int getPlayerExpRequired(int level) {\n var excel = playerLevelExcelMap.get(level);\n return excel != null ? excel.getPlayerExp() : 0;\n }\n\n public static int getAvatarExpRequired(int expGroup, int level) {\n var excel = expTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n\n public static int getEquipmentExpRequired(int expGroup, int level) {\n var excel = equipmentExpTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n\n public static int getRelicExpRequired(int expGroup, int level) {\n var excel = relicExpTypeExcelMap.get((expGroup << 16) + level);\n return excel != null ? excel.getExp() : 0;\n }\n \n public static RelicMainAffixExcel getRelicMainAffixExcel(int groupId, int affixId) {\n return relicMainAffixExcelMap.get((groupId << 16) + affixId);\n }\n\n public static RelicSubAffixExcel getRelicSubAffixExcel(int groupId, int affixId) {\n return relicSubAffixExcelMap.get((groupId << 16) + affixId);\n }\n \n public static FloorInfo getFloorInfo(int planeId, int floorId) {\n return floorInfos.get(\"P\" + planeId + \"_F\" + floorId);\n }\n\n public static MazeBuffExcel getMazeBuffExcel(int buffId, int level) {\n return mazeBuffExcelMap.get((buffId << 4) + level);\n }\n \n public static CocoonExcel getCocoonExcel(int cocoonId, int worldLevel) {\n return cocoonExcelMap.get((cocoonId << 8) + worldLevel);\n }\n \n public static MappingInfoExcel getMappingInfoExcel(int mappingInfoId, int worldLevel) {\n return mappingInfoExcelMap.get((mappingInfoId << 8) + worldLevel);\n }\n \n public static MonsterDropExcel getMonsterDropExcel(int monsterNpcId, int worldLevel) {\n return monsterDropExcelMap.get((monsterNpcId << 4) + worldLevel);\n }\n \n public static ChallengeRewardExcel getChallengeRewardExcel(int groupId, int starCount) {\n return challengeRewardExcelMap.get((groupId << 16) + starCount);\n }\n \n public static RogueMapExcel getRogueMapExcel(int rogueMapId, int siteId) {\n return rogueMapExcelMap.get((rogueMapId << 8) + siteId);\n }\n \n public static RogueBuffExcel getRogueBuffExcel(int rogueBuffId, int level) {\n return rogueBuffExcelMap.get((rogueBuffId << 4) + level);\n }\n}" }, { "identifier": "GameResource", "path": "src/main/java/emu/lunarcore/data/GameResource.java", "snippet": "public abstract class GameResource implements Comparable<GameResource> {\n\n public abstract int getId();\n\n public void onLoad() {\n\n }\n\n @Override\n public int compareTo(GameResource o) {\n return this.getId() - o.getId();\n }\n}" }, { "identifier": "RelicType", "path": "src/main/java/emu/lunarcore/game/enums/RelicType.java", "snippet": "@Getter\npublic enum RelicType {\n Unknow (0),\n HEAD (1),\n HAND (2),\n BODY (3),\n FOOT (4),\n NECK (5),\n OBJECT (6);\n\n private int val;\n\n private RelicType(int value) {\n this.val = value;\n }\n}" } ]
import emu.lunarcore.data.GameData; import emu.lunarcore.data.GameResource; import emu.lunarcore.data.ResourceType; import emu.lunarcore.data.ResourceType.LoadPriority; import emu.lunarcore.game.enums.RelicType; import lombok.Getter;
3,352
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicConfig.json"}, loadPriority = LoadPriority.LOW) public class RelicExcel extends GameResource { private int ID; private int SetID; private RelicType Type; private int MainAffixGroup; private int SubAffixGroup; private int MaxLevel; private int ExpType; private int ExpProvide; private int CoinCost; @Override public int getId() { return ID; } public int getSetId() { return SetID; } @Override public void onLoad() {
package emu.lunarcore.data.excel; @Getter @ResourceType(name = {"RelicConfig.json"}, loadPriority = LoadPriority.LOW) public class RelicExcel extends GameResource { private int ID; private int SetID; private RelicType Type; private int MainAffixGroup; private int SubAffixGroup; private int MaxLevel; private int ExpType; private int ExpProvide; private int CoinCost; @Override public int getId() { return ID; } public int getSetId() { return SetID; } @Override public void onLoad() {
ItemExcel excel = GameData.getItemExcelMap().get(this.getId());
0
2023-10-10 12:57:35+00:00
4k
jar-analyzer/jar-analyzer
src/test/java/me/n1ar4/jar/analyzer/test/ClassJDBCTest.java
[ { "identifier": "ConfigFile", "path": "src/main/java/me/n1ar4/jar/analyzer/config/ConfigFile.java", "snippet": "public class ConfigFile {\n private String jarPath;\n private String dbPath;\n private String tempPath;\n private String dbSize;\n private String totalJar;\n private String totalClass;\n private String totalMethod;\n private String gptHost;\n private String gptKey;\n private String gptProxyHost;\n private String gptProxyPort;\n\n public String getJarPath() {\n return jarPath;\n }\n\n public void setJarPath(String jarPath) {\n this.jarPath = jarPath;\n }\n\n public String getDbPath() {\n return dbPath;\n }\n\n public void setDbPath(String dbPath) {\n this.dbPath = dbPath;\n }\n\n public String getTempPath() {\n return tempPath;\n }\n\n public void setTempPath(String tempPath) {\n this.tempPath = tempPath;\n }\n\n public String getDbSize() {\n return dbSize;\n }\n\n public void setDbSize(String dbSize) {\n this.dbSize = dbSize;\n }\n\n public String getTotalJar() {\n return totalJar;\n }\n\n public void setTotalJar(String totalJar) {\n this.totalJar = totalJar;\n }\n\n public String getTotalClass() {\n return totalClass;\n }\n\n public void setTotalClass(String totalClass) {\n this.totalClass = totalClass;\n }\n\n public String getTotalMethod() {\n return totalMethod;\n }\n\n public void setTotalMethod(String totalMethod) {\n this.totalMethod = totalMethod;\n }\n\n public String getGptHost() {\n return gptHost;\n }\n\n public void setGptHost(String gptHost) {\n this.gptHost = gptHost;\n }\n\n public String getGptKey() {\n return gptKey;\n }\n\n public void setGptKey(String gptKey) {\n this.gptKey = gptKey;\n }\n\n public String getGptProxyHost() {\n return gptProxyHost;\n }\n\n public void setGptProxyHost(String gptProxyHost) {\n this.gptProxyHost = gptProxyHost;\n }\n\n public String getGptProxyPort() {\n return gptProxyPort;\n }\n\n public void setGptProxyPort(String gptProxyPort) {\n this.gptProxyPort = gptProxyPort;\n }\n\n @Override\n public String toString() {\n return \"ConfigFile{\" +\n \"jarPath='\" + jarPath + '\\'' +\n \", dbPath='\" + dbPath + '\\'' +\n \", tempPath='\" + tempPath + '\\'' +\n \", dbSize='\" + dbSize + '\\'' +\n \", totalJar='\" + totalJar + '\\'' +\n \", totalClass='\" + totalClass + '\\'' +\n \", totalMethod='\" + totalMethod + '\\'' +\n \", gptHost='\" + gptHost + '\\'' +\n \", gptKey='\" + gptKey + '\\'' +\n \", gptProxyHost='\" + gptProxyHost + '\\'' +\n \", gptProxyPort='\" + gptProxyPort + '\\'' +\n '}';\n }\n}" }, { "identifier": "ClassResult", "path": "src/main/java/me/n1ar4/jar/analyzer/entity/ClassResult.java", "snippet": "public class ClassResult {\n private String jarName;\n private String className;\n private String superClassName;\n private int isInterfaceInt;\n\n public String getJarName() {\n return jarName;\n }\n\n public void setJarName(String jarName) {\n this.jarName = jarName;\n }\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public String getSuperClassName() {\n return superClassName;\n }\n\n public void setSuperClassName(String superClassName) {\n this.superClassName = superClassName;\n }\n\n public int getIsInterfaceInt() {\n return isInterfaceInt;\n }\n\n public void setIsInterfaceInt(int isInterfaceInt) {\n this.isInterfaceInt = isInterfaceInt;\n }\n\n @Override\n public String toString() {\n return \"ClassResult{\" +\n \"jarName='\" + jarName + '\\'' +\n \", className='\" + className + '\\'' +\n \", superClassName='\" + superClassName + '\\'' +\n \", isInterfaceInt=\" + isInterfaceInt +\n '}';\n }\n}" }, { "identifier": "CoreEngine", "path": "src/main/java/me/n1ar4/jar/analyzer/engine/CoreEngine.java", "snippet": "public class CoreEngine {\n private static final Logger logger = LogManager.getLogger();\n private final SqlSessionFactory factory;\n\n public CoreEngine(ConfigFile configFile) {\n if (StringUtil.isNull(configFile.getDbPath())) {\n Path dbPath = Paths.get(configFile.getDbPath());\n if (!dbPath.getFileName().toString().equals(\"jar-analyzer.db\") ||\n !Files.exists(dbPath)) {\n throw new RuntimeException(\"start engine error\");\n }\n }\n factory = SqlSessionFactoryUtil.sqlSessionFactory;\n logger.info(\"init core engine finish\");\n }\n\n public ArrayList<MethodResult> getMethodsByClass(String className) {\n SqlSession session = factory.openSession(true);\n MethodMapper methodMapper = session.getMapper(MethodMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(methodMapper.selectMethodsByClassName(className));\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n session.close();\n return results;\n }\n\n public ClassResult getClassByClass(String className) {\n SqlSession session = factory.openSession(true);\n ClassMapper classMapper = session.getMapper(ClassMapper.class);\n ArrayList<ClassResult> results = new ArrayList<>(classMapper.selectClassByClassName(className));\n session.close();\n return results.isEmpty() ? null : results.get(0);\n }\n\n public String getAbsPath(String className) {\n SqlSession session = factory.openSession(true);\n ClassFileMapper classMapper = session.getMapper(ClassFileMapper.class);\n className = className + \".class\";\n String res = classMapper.selectPathByClass(className);\n session.close();\n return res;\n }\n\n public ArrayList<MethodResult> getCallers(String calleeClass, String calleeMethod, String calleeDesc) {\n SqlSession session = factory.openSession(true);\n MethodCallMapper methodCallMapper = session.getMapper(MethodCallMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(methodCallMapper.selectCallers(\n calleeMethod, calleeDesc, calleeClass));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getCallersLike(String calleeClass, String calleeMethod, String calleeDesc) {\n SqlSession session = factory.openSession(true);\n MethodCallMapper methodCallMapper = session.getMapper(MethodCallMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(methodCallMapper.selectCallersLike(\n calleeMethod, calleeDesc, calleeClass));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getCallee(String callerClass, String callerMethod, String callerDesc) {\n SqlSession session = factory.openSession(true);\n MethodCallMapper methodCallMapper = session.getMapper(MethodCallMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(methodCallMapper.selectCallee(\n callerMethod, callerDesc, callerClass));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getMethod(String className, String methodName, String methodDesc) {\n SqlSession session = factory.openSession(true);\n MethodMapper methodMapper = session.getMapper(MethodMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(\n methodMapper.selectMethods(className, methodName, methodDesc));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getMethodLike(String className, String methodName, String methodDesc) {\n SqlSession session = factory.openSession(true);\n MethodMapper methodMapper = session.getMapper(MethodMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(\n methodMapper.selectMethodsLike(className, methodName, methodDesc));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getMethodsByStr(String val) {\n SqlSession session = factory.openSession(true);\n StringMapper stringMapper = session.getMapper(StringMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(\n stringMapper.selectMethodByString(val));\n session.close();\n return results;\n }\n\n public ArrayList<String> getJarsPath() {\n SqlSession session = factory.openSession(true);\n JarMapper jarMapper = session.getMapper(JarMapper.class);\n ArrayList<String> results = new ArrayList<>(\n jarMapper.selectAllJars());\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getImpls(String className,\n String methodName,\n String methodDesc) {\n SqlSession session = factory.openSession(true);\n MethodImplMapper methodMapper = session.getMapper(MethodImplMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(\n methodMapper.selectImplClassName(className, methodName, methodDesc));\n session.close();\n return results;\n }\n\n public ArrayList<MethodResult> getSuperImpls(String className, String methodName, String methodDesc) {\n SqlSession session = factory.openSession(true);\n MethodImplMapper methodMapper = session.getMapper(MethodImplMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(\n methodMapper.selectSuperImpls(className, methodName, methodDesc));\n session.close();\n return results;\n }\n\n public String getJarByClass(String className) {\n SqlSession session = factory.openSession(true);\n ClassMapper classMapper = session.getMapper(ClassMapper.class);\n String result = classMapper.selectJarByClass(className);\n session.close();\n return result;\n }\n\n public ArrayList<ClassResult> getAllSpringC() {\n SqlSession session = factory.openSession(true);\n SpringControllerMapper springControllerMapper = session.getMapper(SpringControllerMapper.class);\n List<ClassResult> res = springControllerMapper.selectAllSpringC();\n session.close();\n return new ArrayList<>(res);\n }\n\n public ArrayList<MethodResult> getSpringM(String className) {\n SqlSession session = factory.openSession(true);\n SpringMethodMapper springMethodMapper = session.getMapper(SpringMethodMapper.class);\n List<MethodResult> res = springMethodMapper.selectMappingsByClassName(className);\n session.close();\n return new ArrayList<>(res);\n }\n\n public ArrayList<String> getStrings(int page) {\n SqlSession session = factory.openSession(true);\n StringMapper stringMapper = session.getMapper(StringMapper.class);\n int offset = (page - 1) * 100;\n List<String> res = stringMapper.selectStrings(offset);\n session.close();\n return new ArrayList<>(res);\n }\n\n public int getStringCount() {\n SqlSession session = factory.openSession(true);\n StringMapper stringMapper = session.getMapper(StringMapper.class);\n int res = stringMapper.selectCount();\n session.close();\n return res;\n }\n\n public ArrayList<MethodResult> getMethodsByClassNoJar(String className) {\n SqlSession session = factory.openSession(true);\n MethodMapper methodMapper = session.getMapper(MethodMapper.class);\n ArrayList<MethodResult> results = new ArrayList<>(methodMapper.selectMethodsByClassNameNoJar(className));\n results.sort(Comparator.comparing(MethodResult::getMethodName));\n session.close();\n return results;\n }\n\n public int updateMethod(String className, String methodName, String methodDesc, String newItem) {\n SqlSession session = factory.openSession(true);\n MethodMapper methodMapper = session.getMapper(MethodMapper.class);\n int res = methodMapper.updateMethod(className, methodName, methodDesc, newItem);\n session.close();\n return res;\n }\n}" }, { "identifier": "Const", "path": "src/main/java/me/n1ar4/jar/analyzer/starter/Const.java", "snippet": "public interface Const {\n String app = \"Jar Analyzer V2 - 4ra1n\";\n String version = \"2.9\";\n String checkUpdateUrl = \"http://47.97.182.120/version.txt\";\n String authorUrl = \"https://github.com/4ra1n\";\n String projectUrl = \"https://github.com/jar-analyzer/jar-analyzer\";\n String newIssueUrl = \"https://github.com/jar-analyzer/jar-analyzer/issues/new\";\n String dbFile = \"jar-analyzer.db\";\n String tempDir = \"jar-analyzer-temp\";\n String OpcodeForm = \"Jar Analyzer V2 - Method Opcode\";\n String ChangeLogForm = \"Jar Analyzer V2 - CHANGELOG\";\n String CFGForm = \"Jar Analyzer V2 - CFG\";\n String FrameForm = \"Jar Analyzer V2 - Frame\";\n String SQLiteForm = \"Jar Analyzer V2 - SQLite\";\n String ChatGPTForm = \"Jar Analyzer V2 - ChatGPT\";\n String StringForm = \"Jar Analyzer V2 - String\";\n String blackAreaText = \"java.lang.Object;\\njava.lang.Integer;\\n\";\n String classBlackAreaText = \"com.test.a;\\ncom.test.a.;\\ncom.test.a.TestClass;\\n\";\n}" } ]
import me.n1ar4.jar.analyzer.config.ConfigFile; import me.n1ar4.jar.analyzer.entity.ClassResult; import me.n1ar4.jar.analyzer.engine.CoreEngine; import me.n1ar4.jar.analyzer.starter.Const;
3,287
package me.n1ar4.jar.analyzer.test; public class ClassJDBCTest { public static void main(String[] args) {
package me.n1ar4.jar.analyzer.test; public class ClassJDBCTest { public static void main(String[] args) {
ConfigFile configFile = new ConfigFile();
0
2023-10-07 15:42:35+00:00
4k
EasyProgramming/easy-mqtt
server/src/main/java/com/ep/mqtt/server/processor/PubRelMqttProcessor.java
[ { "identifier": "MqttUtil", "path": "server/src/main/java/com/ep/mqtt/server/util/MqttUtil.java", "snippet": "public class MqttUtil {\n\n public static void sendPublish(ChannelHandlerContext channelHandlerContext, MessageVo messageVo) {\n MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, messageVo.getIsDup(),\n MqttQoS.valueOf(messageVo.getToQos()), YesOrNo.valueOf(messageVo.getIsRetained()), 0);\n MqttPublishVariableHeader mqttVariableHeader =\n new MqttPublishVariableHeader(messageVo.getTopic(), Integer.parseInt(messageVo.getToMessageId()));\n MqttPublishMessage mqttPublishMessage = new MqttPublishMessage(mqttFixedHeader, mqttVariableHeader,\n Unpooled.buffer().writeBytes(messageVo.getPayload().getBytes()));\n channelHandlerContext.writeAndFlush(mqttPublishMessage);\n }\n\n public static void sendPubRel(ChannelHandlerContext channelHandlerContext, Integer messageId) {\n MqttFixedHeader mqttFixedHeader =\n new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_MOST_ONCE, false, 0);\n MqttMessageIdVariableHeader mqttMessageIdVariableHeader = MqttMessageIdVariableHeader.from(messageId);\n channelHandlerContext\n .writeAndFlush(MqttMessageFactory.newMessage(mqttFixedHeader, mqttMessageIdVariableHeader, null));\n }\n\n public static void sendPubRec(ChannelHandlerContext channelHandlerContext, Integer messageId) {\n MqttFixedHeader mqttFixedHeader =\n new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0);\n MqttMessageIdVariableHeader mqttMessageIdVariableHeader = MqttMessageIdVariableHeader.from(messageId);\n channelHandlerContext\n .writeAndFlush(MqttMessageFactory.newMessage(mqttFixedHeader, mqttMessageIdVariableHeader, null));\n }\n}" }, { "identifier": "NettyUtil", "path": "server/src/main/java/com/ep/mqtt/server/util/NettyUtil.java", "snippet": "public class NettyUtil {\n\n private static final AttributeKey<String> CLIENT_ID_ATTR_KEY = AttributeKey.valueOf(\"clientId\");\n\n public static void setClientId(ChannelHandlerContext channelHandlerContext, String clientId) {\n channelHandlerContext.channel().attr(CLIENT_ID_ATTR_KEY).set(clientId);\n }\n\n public static String getClientId(ChannelHandlerContext channelHandlerContext) {\n return channelHandlerContext.channel().attr(CLIENT_ID_ATTR_KEY).get();\n }\n\n public static String getSessionId(ChannelHandlerContext channelHandlerContext) {\n return channelHandlerContext.channel().id().asLongText();\n }\n\n}" }, { "identifier": "WorkerThreadPool", "path": "server/src/main/java/com/ep/mqtt/server/util/WorkerThreadPool.java", "snippet": "@Slf4j\npublic class WorkerThreadPool {\n\n public static Vertx VERTX;\n\n private static WorkerExecutor DEFAULT_WORKER_EXECUTOR;\n\n private static WorkerExecutor DEAL_MESSAGE_WORKER_EXECUTOR;\n\n private static final Long MAX_EXECUTE_TIME = 20L;\n\n private static final TimeUnit MAX_EXECUTE_TIME_UNIT = TimeUnit.MILLISECONDS;\n\n public static void init(Integer dealMessageThreadPoolSize){\n VertxOptions vertxOptions = new VertxOptions();\n vertxOptions.setWarningExceptionTime(MAX_EXECUTE_TIME * 2);\n vertxOptions.setWarningExceptionTimeUnit(MAX_EXECUTE_TIME_UNIT);\n VERTX = Vertx.vertx(vertxOptions);\n DEFAULT_WORKER_EXECUTOR =\n VERTX.createSharedWorkerExecutor(\"worker-thread-pool\", Runtime.getRuntime().availableProcessors() * 2, MAX_EXECUTE_TIME,\n MAX_EXECUTE_TIME_UNIT);\n DEAL_MESSAGE_WORKER_EXECUTOR =\n VERTX.createSharedWorkerExecutor(\"deal-message-thread-pool\", dealMessageThreadPoolSize, MAX_EXECUTE_TIME, MAX_EXECUTE_TIME_UNIT);\n }\n\n public static <T> void execute(Consumer<Promise<T>> blockingHandlerConsumer) {\n Handler<Promise<T>> blockingCodeHandler = (promise)->{\n blockingHandlerConsumer.accept(promise);\n promise.complete();\n };\n execute(blockingCodeHandler, null, DEFAULT_WORKER_EXECUTOR);\n }\n\n\n public static <T> void dealMessage(Consumer<Promise<T>> blockingHandlerConsumer, Runnable resultHandlerRunnable,\n ChannelHandlerContext channelHandlerContext) {\n Handler<Promise<T>> blockingCodeHandler = (promise)->{\n blockingHandlerConsumer.accept(promise);\n promise.complete();\n };\n Handler<AsyncResult<T>> asyncResultHandler = result -> {\n if (result.cause() != null) {\n log.error(\"deal message execute error, client id: [{}]\", NettyUtil.getClientId(channelHandlerContext),\n result.cause());\n channelHandlerContext.disconnect();\n return;\n }\n if (resultHandlerRunnable != null) {\n resultHandlerRunnable.run();\n }\n };\n execute(blockingCodeHandler, asyncResultHandler, DEAL_MESSAGE_WORKER_EXECUTOR);\n }\n\n public static <T> void execute(Handler<Promise<T>> blockingCodeHandler, Handler<AsyncResult<T>> resultHandler, WorkerExecutor workerExecutor) {\n if (resultHandler == null) {\n resultHandler = result -> {\n if (result.cause() != null) {\n log.error(\"worker thread execute error\", result.cause());\n }\n };\n }\n workerExecutor.executeBlocking(blockingCodeHandler, false, resultHandler);\n }\n}" }, { "identifier": "MessageVo", "path": "server/src/main/java/com/ep/mqtt/server/vo/MessageVo.java", "snippet": "@Data\npublic class MessageVo {\n\n /**\n * 收到的qos等级\n */\n private Integer fromQos;\n\n /**\n * 发送的qos等级\n */\n private Integer toQos;\n\n /**\n * 主题\n */\n private String topic;\n\n /**\n * 发送的消息id\n */\n private String toMessageId;\n\n /**\n * 收到的消息id\n */\n private Integer fromMessageId;\n\n /**\n * 保留消息标志\n */\n private Integer isRetained;\n\n /**\n * 消息来源客户端id\n */\n private String fromClientId;\n\n /**\n * 消息目的地客户端id\n */\n private String toClientId;\n\n /**\n * 消息内容\n */\n private String payload;\n\n /**\n * 是否重复\n */\n private Boolean isDup;\n\n}" } ]
import com.ep.mqtt.server.util.MqttUtil; import com.ep.mqtt.server.util.NettyUtil; import com.ep.mqtt.server.util.WorkerThreadPool; import com.ep.mqtt.server.vo.MessageVo; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.mqtt.*; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component;
1,687
package com.ep.mqtt.server.processor; /** * 发布释放 * * @author zbz * @date 2023/7/31 9:47 */ @Slf4j @Component public class PubRelMqttProcessor extends AbstractMqttProcessor<MqttMessage> { @Override protected void process(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) { Integer messageId = getMessageId(mqttMessage);
package com.ep.mqtt.server.processor; /** * 发布释放 * * @author zbz * @date 2023/7/31 9:47 */ @Slf4j @Component public class PubRelMqttProcessor extends AbstractMqttProcessor<MqttMessage> { @Override protected void process(ChannelHandlerContext channelHandlerContext, MqttMessage mqttMessage) { Integer messageId = getMessageId(mqttMessage);
String clientId = NettyUtil.getClientId(channelHandlerContext);
1
2023-10-08 06:41:33+00:00
4k
jjenkov/parsers
src/test/java/com/jenkov/parsers/tokenizers/BasicTokenizerMethodizedTest.java
[ { "identifier": "Utf8Buffer", "path": "src/main/java/com/jenkov/parsers/unicode/Utf8Buffer.java", "snippet": "public class Utf8Buffer {\n\n public byte[] buffer;\n public int offset;\n public int length;\n public int endOffset;\n\n /** A field that can be used during parsing of the data in this Utf8Source */\n public int tempOffset;\n\n /** A field that can point to the beginning of a token parsed from UTF-8 characters\n * See the parseToken() method.\n * */\n public int tokenOffset;\n\n\n public Utf8Buffer(byte[] data) {\n this(data, 0, data.length);\n }\n public Utf8Buffer(byte [] data, int offset, int length) {\n this.buffer = data;\n this.offset = offset;\n this.tempOffset = offset;\n this.length = length;\n this.endOffset = offset + length;\n }\n\n public Utf8Buffer clear() {\n this.offset = 0;\n this.tempOffset = 0;\n this.length = 0;\n this.endOffset = 0;\n return this;\n }\n\n public Utf8Buffer rewind() {\n this.tempOffset = this.offset;\n return this;\n }\n\n public Utf8Buffer calculateLengthAndEndOffset() {\n this.length = this.tempOffset - this.offset;\n this.endOffset = this.tempOffset;\n return this;\n }\n\n public boolean hasMoreBytes() {\n //todo optimize this? No reason to subtract 1 every time hasMoreBytes() is called.\n //return this.tempOffset < this.endOffset - 1;\n return this.tempOffset < this.endOffset;\n }\n\n public int writeCodepoints(String characters) {\n int bytesWritten = 0;\n for( int i = 0; i < characters.length(); i++){\n bytesWritten += writeCodepoint(characters.codePointAt(i));\n }\n return bytesWritten;\n }\n\n public int writeCodepoint(int codepoint) {\n if(codepoint < 0x00_00_00_80){\n // This is a one byte UTF-8 char\n buffer[this.tempOffset++] = (byte) (0xFF & codepoint);\n return 1;\n } else if (codepoint < 0x00_00_08_00) {\n // This is a two byte UTF-8 char. Value is 11 bits long (less than 12 bits in value).\n // Get highest 5 bits into first byte\n buffer[this.tempOffset] = (byte) (0xFF & (0b1100_0000 | (0b0001_1111 & (codepoint >> 6))));\n buffer[this.tempOffset + 1] = (byte) (0xFF & (0b1000_0000 | (0b0011_1111 & codepoint)));\n this.tempOffset+=2;\n return 2;\n } else if (codepoint < 0x00_01_00_00){\n // This is a three byte UTF-8 char. Value is 16 bits long (less than 17 bits in value).\n // Get the highest 4 bits into the first byte\n buffer[this.tempOffset] = (byte) (0xFF & (0b1110_0000 | (0b0000_1111 & (codepoint >> 12))));\n buffer[this.tempOffset + 1] = (byte) (0xFF & (0b1000_0000 | (0b00111111 & (codepoint >> 6))));\n buffer[this.tempOffset + 2] = (byte) (0xFF & (0b1000_0000 | (0b00111111 & codepoint)));\n this.tempOffset+=3;\n return 3;\n } else if (codepoint < 0x00_11_00_00) {\n // This is a four byte UTF-8 char. Value is 21 bits long (less than 22 bits in value).\n // Get the highest 3 bits into the first byte\n buffer[this.tempOffset] = (byte) (0xFF & (0b1111_0000 | (0b0000_0111 & (codepoint >> 18))));\n buffer[this.tempOffset + 1] = (byte) (0xFF & (0b1000_0000 | (0b0011_1111 & (codepoint >> 12))));\n buffer[this.tempOffset + 2] = (byte) (0xFF & (0b1000_0000 | (0b0011_1111 & (codepoint >> 6))));\n buffer[this.tempOffset + 3] = (byte) (0xFF & (0b1000_0000 | (0b0011_1111 & codepoint)));\n this.tempOffset+=4;\n return 4;\n }\n throw new IllegalArgumentException(\"Unknown Unicode codepoint: \" + codepoint);\n }\n\n public int nextCodepoint() {\n int firstByteOfChar = 0xFF & buffer[tempOffset];\n\n if(firstByteOfChar < 0b1000_0000) { // 128\n //this is a single byte UTF-8 char (an ASCII char)\n tempOffset++;\n return firstByteOfChar;\n } else if(firstByteOfChar < 0b1110_0000) { // 224\n int nextCodepoint = 0;\n //this is a two byte UTF-8 char\n nextCodepoint = 0b0001_1111 & firstByteOfChar; //0x1F\n nextCodepoint <<= 6;\n nextCodepoint |= 0b0011_1111 & (0xFF & buffer[tempOffset + 1]); //0x3F\n tempOffset +=2;\n return nextCodepoint;\n } else if(firstByteOfChar < 0b1111_0000) { // 240\n //this is a three byte UTF-8 char\n int nextCodepoint = 0;\n //this is a two byte UTF-8 char\n nextCodepoint = 0b0000_1111 & firstByteOfChar; // 0x0F\n nextCodepoint <<= 6;\n nextCodepoint |= 0x3F & buffer[tempOffset + 1];\n nextCodepoint <<= 6;\n nextCodepoint |= 0x3F & buffer[tempOffset + 2];\n tempOffset +=3;\n return nextCodepoint;\n } else if(firstByteOfChar < 0b1111_1000) { // 248\n //this is a four byte UTF-8 char\n int nextCodepoint = 0;\n //this is a two byte UTF-8 char\n nextCodepoint = 0b0000_0111 & firstByteOfChar; // 0x07\n nextCodepoint <<= 6;\n nextCodepoint |= 0x3F & buffer[tempOffset + 1];\n nextCodepoint <<= 6;\n nextCodepoint |= 0x3F & buffer[tempOffset + 2];\n nextCodepoint <<= 6;\n nextCodepoint |= 0x3F & buffer[tempOffset + 3];\n tempOffset +=4;\n return nextCodepoint;\n }\n\n throw new IllegalStateException(\"Codepoint not recognized from first byte: \" + firstByteOfChar);\n }\n\n /*\n public void skipWhitespace() {\n int tempOffsetMark = this.tempOffset;\n int nextCodepoint = nextCodepoint();\n\n while(hasMoreBytes() && isWhiteSpaceCodepoint(nextCodepoint)){\n tempOffsetMark = this.tempOffset;\n nextCodepoint = nextCodepoint();\n }\n if(hasMoreBytes()) {\n // Latest code point was not a whitespace code point, and end-of-buffer was not found.\n // Push the tempOffset back so that latest code point is returned by next call to nextCodepoint()\n this.tempOffset = tempOffsetMark;\n }\n }\n\n public boolean isWhiteSpaceCodepoint(int nextCodepoint) {\n return nextCodepoint == ' ' || nextCodepoint == '\\t' || nextCodepoint == '\\r' || nextCodepoint == '\\n';\n }\n\n public void parseIntegerToken() {\n this.tokenOffset = this.tempOffset;\n int tokenCodepointLength = 0;\n\n while( hasMoreBytes() ) {\n int previousCodepointOffset = this.tempOffset;\n int nextCodepoint = nextCodepoint();\n\n switch(nextCodepoint) {\n case '0' : ;\n case '1' : ;\n case '2' : ;\n case '3' : ;\n case '4' : ;\n case '5' : ;\n case '6' : ;\n case '7' : ;\n case '8' : ;\n case '9' : ; tokenCodepointLength++; break;\n default: {\n if(tokenCodepointLength == 0){\n // No integer character codepoint found.\n throw new RuntimeException(\"Integer token expected, but found: \" + (char) nextCodepoint);\n } else {\n // 1+ integer character codepoints found. Set tempOffset back to previousCodepointOffset,\n // so the demarcation character codepoint (this codepoint) is returned as next codepoint.\n this.tempOffset = previousCodepointOffset;\n return; // end of integer token found - so return.\n }\n }\n }\n }\n }\n\n public void parseDecimalToken() {\n this.tokenOffset = this.tempOffset;\n int tokenCodepointLength = 0;\n\n //todo Should the number of . be counted, and an exception be thrown if the number is greater than 1?\n\n while( hasMoreBytes() ) {\n int previousCodepointOffset = this.tempOffset;\n int nextCodepoint = nextCodepoint();\n\n switch(nextCodepoint) {\n case '0' : ;\n case '1' : ;\n case '2' : ;\n case '3' : ;\n case '4' : ;\n case '5' : ;\n case '6' : ;\n case '7' : ;\n case '8' : ;\n case '9' : ;\n case '.' : ; tokenCodepointLength++; break;\n default: {\n if(tokenCodepointLength == 0){\n // No integer character codepoint found.\n throw new RuntimeException(\"Decimal token expected, but found: \" + (char) nextCodepoint);\n } else {\n // 1+ integer character codepoints found. Set tempOffset back to previousCodepointOffset,\n // so the demarcation character codepoint (this codepoint) is returned as next codepoint.\n this.tempOffset = previousCodepointOffset;\n return; // end of integer token found - so return.\n }\n }\n }\n }\n }\n\n public void parseToken() {\n this.tokenOffset = this.tempOffset;\n int tokenCodepointLength = 1;\n\n while( hasMoreBytes()) {\n int previousCodepointOffset = this.tempOffset;\n int nextCodepoint = nextCodepoint();\n\n if(isWhiteSpaceCodepoint(nextCodepoint)) {\n // Boundary of token found (a whitespace char). Go 1 codepoint back and return here.\n this.tempOffset = previousCodepointOffset;\n return;\n\n } else if (isSingleCodepointToken(nextCodepoint)){\n if(tokenCodepointLength == 1) {\n // This is the first codepoint found - return this as a single codepoint token\n return;\n } else {\n // This is not the first codepoint found - this single codepoint token functions as a \"separator\"\n // from the earlier found codepoints - meaning there are two tokens: A multi-codepoint + a single-codepoint token\n // Set tempOffset back to before the single-token codepoint, so it will be found at the next parseToken() call,\n // and return with markers pointing to the multi-codepoint token.\n this.tempOffset = previousCodepointOffset;\n return;\n }\n } else {\n // continue to the next codepoint - as end of token is not yet found.\n tokenCodepointLength++;\n }\n }\n\n }\n\n public boolean isSingleCodepointToken(int nextCodepoint) {\n switch(nextCodepoint) {\n case '(' :\n case ')' :\n case '{' :\n case '}' :\n case '<' :\n case '>' :\n case '[' :\n case ']' :\n case '|' :\n case ':' :\n case ';' :\n case '.' :\n case ',' :\n case '\"' :\n case '\\'' :\n case '!' :\n case '#' :\n case '$' :\n case '%' :\n case '&' :\n case '/' :\n case '\\\\' :\n case '*' :\n case '+' :\n case '-' :\n case '_' :\n case '^' :\n case '~' :\n case '@' : return true;\n\n default : return false;\n }\n }\n*/\n\n}" }, { "identifier": "assertToken", "path": "src/test/java/com/jenkov/parsers/tokenizers/TokenizerTestUtil.java", "snippet": "public static void assertToken(TokenizerListenerIndexImpl listenerImpl, int tokenIndex, int startOffset, int endOffset, int tokenType) {\n assertEquals(startOffset, listenerImpl.startOffsets[tokenIndex]);\n assertEquals(endOffset, listenerImpl.endOffsets[tokenIndex]);\n assertEquals(tokenType, listenerImpl.tokenTypes[tokenIndex]);\n}" } ]
import com.jenkov.parsers.unicode.Utf8Buffer; import org.junit.jupiter.api.Test; import static com.jenkov.parsers.tokenizers.TokenizerTestUtil.assertToken; import static org.junit.jupiter.api.Assertions.assertEquals;
3,367
package com.jenkov.parsers.tokenizers; public class BasicTokenizerMethodizedTest { @Test public void testTokenize() { String data = " + - \"this is a quoted token \" * &abc()def349.87iuy:899/*abc*/"; System.out.println(data.length());
package com.jenkov.parsers.tokenizers; public class BasicTokenizerMethodizedTest { @Test public void testTokenize() { String data = " + - \"this is a quoted token \" * &abc()def349.87iuy:899/*abc*/"; System.out.println(data.length());
Utf8Buffer utf8Buffer = new Utf8Buffer(new byte[1024], 0, 1024);
0
2023-10-12 18:46:04+00:00
4k
egorolegovichyakovlev/DroidRec
app/src/main/java/com/yakovlevegor/DroidRec/MainActivity.java
[ { "identifier": "OnShakeEventHelper", "path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java", "snippet": "public class OnShakeEventHelper {\n private SensorEventListener currentListener;\n private boolean hasListenerChanged;\n private Context context;\n private ScreenRecorder.RecordingBinder recordingBinder;\n private float acceleration = 10f;\n private float currentAcceleration = SensorManager.GRAVITY_EARTH;\n private float lastAcceleration = SensorManager.GRAVITY_EARTH;\n private SensorManager sensorManager;\n private Toast toast;\n private SensorEventListener emptyListener = new SensorEventListener() {\n\n @Override\n public void onSensorChanged(SensorEvent sensorEvent) { }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) { }\n };\n\n public OnShakeEventHelper(ScreenRecorder.RecordingBinder recordingBinder, AppCompatActivity activity) {\n this.recordingBinder = recordingBinder;\n String initialValue = activity.getSharedPreferences(ScreenRecorder.prefsident, 0).getString(\"onshake\", \"Do nothing\");\n currentListener = giveMeSensorListenerFor(initialValue);\n sensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);\n context = activity.getApplicationContext();\n\n EventBus.getDefault().register(this);\n }\n\n public void registerListener() {\n sensorManager.registerListener(\n currentListener,\n sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),\n SensorManager.SENSOR_DELAY_NORMAL\n );\n hasListenerChanged = false;\n }\n\n public void unregisterListener() {\n sensorManager.unregisterListener(currentListener);\n }\n\n @Subscribe\n public void onShakePreferenceChanged(OnShakePreferenceChangeEvent event) {\n currentListener = giveMeSensorListenerFor(event.getState());\n hasListenerChanged = true;\n }\n\n public boolean hasListenerChanged() {\n return hasListenerChanged;\n }\n\n private SensorEventListener giveMeSensorListenerFor(Runnable action, String msg) {\n return new SensorEventListener() {\n @Override\n public void onSensorChanged(SensorEvent event) {\n // Fetching x,y,z values\n float x = event.values[0];\n float y = event.values[1];\n float z = event.values[2];\n lastAcceleration = currentAcceleration;\n\n // Getting current accelerations\n // with the help of fetched x,y,z values\n currentAcceleration = (float) sqrt(x * x + y * y + z * z);\n float delta = currentAcceleration - lastAcceleration;\n acceleration = acceleration * 0.9f + delta;\n\n // Display a Toast message if\n // acceleration value is over 12\n if (acceleration > 12 && recordingBinder.isStarted()) {\n action.run();\n showToast(msg);\n }\n }\n\n @Override\n public void onAccuracyChanged(Sensor sensor, int i) {\n\n }\n };\n }\n private SensorEventListener giveMeSensorListenerFor(String state) {\n if(\"Do nothing\".equals(state)) return emptyListener;\n\n if(\"Pause\".equals(state)) return giveMeSensorListenerFor(() -> recordingBinder.recordingPause(), \"Recording is paused\");\n\n if(\"Stop\".equals(state)) return giveMeSensorListenerFor(() -> recordingBinder.stopService(), \"Recording is stopped\");\n\n throw new IllegalArgumentException(\"Should never occur\");\n }\n\n private void showToast(String msg) {\n if(toast != null) toast.cancel();\n toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);\n toast.show();\n }\n}" }, { "identifier": "ServiceConnectedEvent", "path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/event/ServiceConnectedEvent.java", "snippet": "public class ServiceConnectedEvent {\n private boolean isServiceConnected;\n\n public ServiceConnectedEvent(boolean isServiceConnected) {\n this.isServiceConnected = isServiceConnected;\n }\n\n public boolean isServiceConnected() {\n return isServiceConnected;\n }\n}" } ]
import android.Manifest; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.VectorDrawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.AnimationDrawable; import android.hardware.display.DisplayManager; import android.media.projection.MediaProjectionManager; import android.net.Uri; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.SystemClock; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.Display; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.MotionEvent; import android.widget.RelativeLayout; import android.widget.ImageView; import android.widget.ImageButton; import android.widget.Chronometer; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import android.widget.RelativeLayout; import android.widget.LinearLayout; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.animation.AnimatorInflater; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat; import androidx.vectordrawable.graphics.drawable.Animatable2Compat; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.TooltipCompat; import com.yakovlevegor.DroidRec.shake.OnShakeEventHelper; import com.yakovlevegor.DroidRec.shake.event.ServiceConnectedEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList;
1,972
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package com.yakovlevegor.DroidRec; public class MainActivity extends AppCompatActivity { private static final int REQUEST_MICROPHONE = 56808; private static final int REQUEST_MICROPHONE_PLAYBACK = 59465; private static final int REQUEST_MICROPHONE_RECORD = 58467; private static final int REQUEST_STORAGE = 58593; private static final int REQUEST_STORAGE_AUDIO = 58563; private static final int REQUEST_MODE_CHANGE = 58857; private ScreenRecorder.RecordingBinder recordingBinder; boolean screenRecorderStarted = false; private MediaProjectionManager activityProjectionManager; private SharedPreferences appSettings; private SharedPreferences.Editor appSettingsEditor; Display display; ImageButton mainRecordingButton; ImageButton startRecordingButton; ImageButton recordScreenSetting; ImageButton recordMicrophoneSetting; ImageButton recordAudioSetting; ImageButton recordInfo; ImageButton recordSettings; ImageButton recordShare; ImageButton recordDelete; ImageButton recordOpen; ImageButton recordStop; LinearLayout timerPanel; LinearLayout modesPanel; LinearLayout finishedPanel; LinearLayout optionsPanel; Chronometer timeCounter; TextView audioPlaybackUnavailable; Intent serviceIntent; public static String appName = "com.yakovlevegor.DroidRec"; public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING"; private boolean stateActivated = false; private boolean serviceToRecording = false; private AlertDialog dialog; private boolean recordModeChosen;
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package com.yakovlevegor.DroidRec; public class MainActivity extends AppCompatActivity { private static final int REQUEST_MICROPHONE = 56808; private static final int REQUEST_MICROPHONE_PLAYBACK = 59465; private static final int REQUEST_MICROPHONE_RECORD = 58467; private static final int REQUEST_STORAGE = 58593; private static final int REQUEST_STORAGE_AUDIO = 58563; private static final int REQUEST_MODE_CHANGE = 58857; private ScreenRecorder.RecordingBinder recordingBinder; boolean screenRecorderStarted = false; private MediaProjectionManager activityProjectionManager; private SharedPreferences appSettings; private SharedPreferences.Editor appSettingsEditor; Display display; ImageButton mainRecordingButton; ImageButton startRecordingButton; ImageButton recordScreenSetting; ImageButton recordMicrophoneSetting; ImageButton recordAudioSetting; ImageButton recordInfo; ImageButton recordSettings; ImageButton recordShare; ImageButton recordDelete; ImageButton recordOpen; ImageButton recordStop; LinearLayout timerPanel; LinearLayout modesPanel; LinearLayout finishedPanel; LinearLayout optionsPanel; Chronometer timeCounter; TextView audioPlaybackUnavailable; Intent serviceIntent; public static String appName = "com.yakovlevegor.DroidRec"; public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING"; private boolean stateActivated = false; private boolean serviceToRecording = false; private AlertDialog dialog; private boolean recordModeChosen;
private OnShakeEventHelper onShakeEventHelper;
0
2023-10-09 00:04:13+00:00
4k
fuzhengwei/chatglm-sdk-java
src/main/java/cn/bugstack/chatglm/session/defaults/DefaultOpenAiSession.java
[ { "identifier": "IOpenAiApi", "path": "src/main/java/cn/bugstack/chatglm/IOpenAiApi.java", "snippet": "public interface IOpenAiApi {\n\n String v3_completions = \"api/paas/v3/model-api/{model}/sse-invoke\";\n String v3_completions_sync = \"api/paas/v3/model-api/{model}/invoke\";\n\n @POST(v3_completions)\n Single<ChatCompletionResponse> completions(@Path(\"model\") String model, @Body ChatCompletionRequest chatCompletionRequest);\n\n @POST(v3_completions_sync)\n Single<ChatCompletionSyncResponse> completions(@Body ChatCompletionRequest chatCompletionRequest);\n\n}" }, { "identifier": "ChatCompletionRequest", "path": "src/main/java/cn/bugstack/chatglm/model/ChatCompletionRequest.java", "snippet": "@Data\n@Slf4j\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ChatCompletionRequest {\n\n /**\n * 模型\n */\n private Model model = Model.CHATGLM_6B_SSE;\n\n /**\n * 请求ID\n */\n @JsonProperty(\"request_id\")\n private String requestId = String.format(\"xfg-%d\", System.currentTimeMillis());\n /**\n * 控制温度【随机性】\n */\n private float temperature = 0.9f;\n /**\n * 多样性控制;\n */\n @JsonProperty(\"top_p\")\n private float topP = 0.7f;\n /**\n * 输入给模型的会话信息\n * 用户输入的内容;role=user\n * 挟带历史的内容;role=assistant\n */\n private List<Prompt> prompt;\n /**\n * 智普AI sse 固定参数 incremental = true 【增量返回】\n */\n private boolean incremental = true;\n /**\n * sseformat, 用于兼容解决sse增量模式okhttpsse截取data:后面空格问题, [data: hello]。只在增量模式下使用sseFormat。\n */\n private String sseFormat = \"data\";\n\n @Data\n @Builder\n @NoArgsConstructor\n @AllArgsConstructor\n public static class Prompt {\n private String role;\n private String content;\n }\n\n @Override\n public String toString() {\n Map<String, Object> paramsMap = new HashMap<>();\n paramsMap.put(\"request_id\", requestId);\n paramsMap.put(\"prompt\", prompt);\n paramsMap.put(\"incremental\", incremental);\n paramsMap.put(\"temperature\", temperature);\n paramsMap.put(\"top_p\", topP);\n paramsMap.put(\"sseFormat\", sseFormat);\n try {\n return new ObjectMapper().writeValueAsString(paramsMap);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n}" }, { "identifier": "ChatCompletionResponse", "path": "src/main/java/cn/bugstack/chatglm/model/ChatCompletionResponse.java", "snippet": "@Data\npublic class ChatCompletionResponse {\n\n private String data;\n private String meta;\n\n @Data\n public static class Meta {\n private String task_status;\n private Usage usage;\n private String task_id;\n private String request_id;\n }\n\n @Data\n public static class Usage {\n private int completion_tokens;\n private int prompt_tokens;\n private int total_tokens;\n }\n\n}" }, { "identifier": "ChatCompletionSyncResponse", "path": "src/main/java/cn/bugstack/chatglm/model/ChatCompletionSyncResponse.java", "snippet": "@Data\npublic class ChatCompletionSyncResponse {\n\n private Integer code;\n private String msg;\n private Boolean success;\n private ChatGLMData data;\n\n @Data\n public static class ChatGLMData {\n private List<Choice> choices;\n private String task_status;\n private Usage usage;\n private String task_id;\n private String request_id;\n }\n\n @Data\n public static class Usage {\n private int completion_tokens;\n private int prompt_tokens;\n private int total_tokens;\n }\n\n @Data\n public static class Choice {\n private String role;\n private String content;\n }\n\n}" }, { "identifier": "EventType", "path": "src/main/java/cn/bugstack/chatglm/model/EventType.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum EventType {\n\n add(\"add\", \"增量\"),\n finish(\"finish\", \"结束\"),\n error(\"error\", \"错误\"),\n interrupted(\"interrupted\", \"中断\"),\n\n ;\n private final String code;\n private final String info;\n\n}" }, { "identifier": "Configuration", "path": "src/main/java/cn/bugstack/chatglm/session/Configuration.java", "snippet": "@Slf4j\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Configuration {\n\n // 智普Ai ChatGlM 请求地址\n @Getter\n @Setter\n private String apiHost = \"https://open.bigmodel.cn/api/paas/\";\n\n // 智普Ai https://open.bigmodel.cn/usercenter/apikeys - apiSecretKey = {apiKey}.{apiSecret}\n private String apiSecretKey;\n\n public void setApiSecretKey(String apiSecretKey) {\n this.apiSecretKey = apiSecretKey;\n String[] arrStr = apiSecretKey.split(\"\\\\.\");\n if (arrStr.length != 2) {\n throw new RuntimeException(\"invalid apiSecretKey\");\n }\n this.apiKey = arrStr[0];\n this.apiSecret = arrStr[1];\n }\n\n @Getter\n private String apiKey;\n @Getter\n private String apiSecret;\n\n // Api 服务\n @Setter\n @Getter\n private IOpenAiApi openAiApi;\n\n @Getter\n @Setter\n private OkHttpClient okHttpClient;\n\n public EventSource.Factory createRequestFactory() {\n return EventSources.createFactory(okHttpClient);\n }\n\n // OkHttp 配置信息\n @Setter\n @Getter\n private HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.HEADERS;\n @Setter\n @Getter\n private long connectTimeout = 450;\n @Setter\n @Getter\n private long writeTimeout = 450;\n @Setter\n @Getter\n private long readTimeout = 450;\n\n // http keywords\n public static final String SSE_CONTENT_TYPE = \"text/event-stream\";\n public static final String DEFAULT_USER_AGENT = \"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\";\n public static final String APPLICATION_JSON = \"application/json\";\n public static final String JSON_CONTENT_TYPE = APPLICATION_JSON + \"; charset=utf-8\";\n\n}" }, { "identifier": "OpenAiSession", "path": "src/main/java/cn/bugstack/chatglm/session/OpenAiSession.java", "snippet": "public interface OpenAiSession {\n\n EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException;\n\n CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException;\n\n ChatCompletionSyncResponse completionsSync(ChatCompletionRequest chatCompletionRequest) throws IOException;\n\n}" } ]
import cn.bugstack.chatglm.IOpenAiApi; import cn.bugstack.chatglm.model.ChatCompletionRequest; import cn.bugstack.chatglm.model.ChatCompletionResponse; import cn.bugstack.chatglm.model.ChatCompletionSyncResponse; import cn.bugstack.chatglm.model.EventType; import cn.bugstack.chatglm.session.Configuration; import cn.bugstack.chatglm.session.OpenAiSession; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okhttp3.sse.EventSource; import okhttp3.sse.EventSourceListener; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch;
2,366
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话服务 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Slf4j public class DefaultOpenAiSession implements OpenAiSession { /** * OpenAi 接口 */ private final Configuration configuration; /** * 工厂事件 */ private final EventSource.Factory factory; public DefaultOpenAiSession(Configuration configuration) { this.configuration = configuration; this.factory = configuration.createRequestFactory(); } @Override public EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 返回事件结果 return factory.newEventSource(request, eventSourceListener); } @Override public CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException { // 用于执行异步任务并获取结果 CompletableFuture<String> future = new CompletableFuture<>(); StringBuffer dataBuffer = new StringBuffer(); // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 异步响应请求 factory.newEventSource(request, new EventSourceListener() { @Override public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
package cn.bugstack.chatglm.session.defaults; /** * @author 小傅哥,微信:fustack * @description 会话服务 * @github https://github.com/fuzhengwei * @Copyright 公众号:bugstack虫洞栈 | 博客:https://bugstack.cn - 沉淀、分享、成长,让自己和他人都能有所收获! */ @Slf4j public class DefaultOpenAiSession implements OpenAiSession { /** * OpenAi 接口 */ private final Configuration configuration; /** * 工厂事件 */ private final EventSource.Factory factory; public DefaultOpenAiSession(Configuration configuration) { this.configuration = configuration; this.factory = configuration.createRequestFactory(); } @Override public EventSource completions(ChatCompletionRequest chatCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 返回事件结果 return factory.newEventSource(request, eventSourceListener); } @Override public CompletableFuture<String> completions(ChatCompletionRequest chatCompletionRequest) throws InterruptedException { // 用于执行异步任务并获取结果 CompletableFuture<String> future = new CompletableFuture<>(); StringBuffer dataBuffer = new StringBuffer(); // 构建请求信息 Request request = new Request.Builder() .url(configuration.getApiHost().concat(IOpenAiApi.v3_completions).replace("{model}", chatCompletionRequest.getModel().getCode())) .post(RequestBody.create(MediaType.parse("application/json"), chatCompletionRequest.toString())) .build(); // 异步响应请求 factory.newEventSource(request, new EventSourceListener() { @Override public void onEvent(EventSource eventSource, @Nullable String id, @Nullable String type, String data) {
ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class);
2
2023-10-10 13:49:59+00:00
4k
lunasaw/gb28181-proxy
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipProcessorObserver.java
[ { "identifier": "Event", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/Event.java", "snippet": "public interface Event {\n /**\n * 回调\n * \n * @param eventResult\n */\n void response(EventResult eventResult);\n}" }, { "identifier": "EventResult", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/EventResult.java", "snippet": "@Data\npublic class EventResult<T> {\n public int statusCode;\n public EventResultType type;\n public String msg;\n public String callId;\n public Dialog dialog;\n public T event;\n\n public EventResult() {}\n\n public EventResult(T event) {\n this.event = event;\n if (event instanceof ResponseEvent) {\n ResponseEvent responseEvent = (ResponseEvent)event;\n Response response = responseEvent.getResponse();\n this.type = EventResultType.response;\n if (response != null) {\n this.msg = response.getReasonPhrase();\n this.statusCode = response.getStatusCode();\n }\n assert response != null;\n this.callId = ((CallIdHeader)response.getHeader(CallIdHeader.NAME)).getCallId();\n } else if (event instanceof TimeoutEvent) {\n TimeoutEvent timeoutEvent = (TimeoutEvent)event;\n this.type = EventResultType.timeout;\n this.msg = \"消息超时未回复\";\n this.statusCode = -1024;\n if (timeoutEvent.isServerTransaction()) {\n this.callId = ((SIPRequest)timeoutEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId();\n this.dialog = timeoutEvent.getServerTransaction().getDialog();\n } else {\n this.callId = ((SIPRequest)timeoutEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();\n this.dialog = timeoutEvent.getClientTransaction().getDialog();\n }\n } else if (event instanceof TransactionTerminatedEvent) {\n TransactionTerminatedEvent transactionTerminatedEvent = (TransactionTerminatedEvent)event;\n this.type = EventResultType.transactionTerminated;\n this.msg = \"事务已结束\";\n this.statusCode = -1024;\n if (transactionTerminatedEvent.isServerTransaction()) {\n this.callId = ((SIPRequest)transactionTerminatedEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId();\n this.dialog = transactionTerminatedEvent.getServerTransaction().getDialog();\n } else {\n this.callId = ((SIPRequest) transactionTerminatedEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();\n this.dialog = transactionTerminatedEvent.getClientTransaction().getDialog();\n this.dialog = transactionTerminatedEvent.getClientTransaction().getDialog();\n }\n } else if (event instanceof DialogTerminatedEvent) {\n DialogTerminatedEvent dialogTerminatedEvent = (DialogTerminatedEvent)event;\n this.type = EventResultType.dialogTerminated;\n this.msg = \"会话已结束\";\n this.statusCode = -1024;\n this.callId = dialogTerminatedEvent.getDialog().getCallId().getCallId();\n this.dialog = dialogTerminatedEvent.getDialog();\n\n } else if (event instanceof RequestEvent) {\n RequestEvent requestEvent = (RequestEvent) event;\n this.type = EventResultType.ack;\n this.msg = \"ack event\";\n this.callId = requestEvent.getDialog().getCallId().getCallId();\n this.dialog = requestEvent.getDialog();\n } else if (event instanceof DeviceNotFoundEvent) {\n this.type = EventResultType.deviceNotFoundEvent;\n this.msg = \"设备未找到\";\n this.statusCode = -1024;\n this.callId = ((DeviceNotFoundEvent)event).getCallId();\n }\n }\n}" }, { "identifier": "SipSubscribe", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/SipSubscribe.java", "snippet": "@Slf4j\n@Component\npublic class SipSubscribe {\n\n private static final Map<String, Event> errorSubscribes = new ConcurrentHashMap<>();\n\n private static final Map<String, Event> okSubscribes = new ConcurrentHashMap<>();\n\n private static final Map<String, Instant> okTimeSubscribes = new ConcurrentHashMap<>();\n\n private static final Map<String, Instant> errorTimeSubscribes = new ConcurrentHashMap<>();\n\n public synchronized static void addErrorSubscribe(String key, Event event) {\n errorSubscribes.put(key, event);\n errorTimeSubscribes.put(key, Instant.now());\n }\n\n public synchronized static void addOkSubscribe(String key, Event event) {\n okSubscribes.put(key, event);\n okTimeSubscribes.put(key, Instant.now());\n }\n\n public static Event getErrorSubscribe(String key) {\n return errorSubscribes.get(key);\n }\n\n public synchronized static void removeErrorSubscribe(String key) {\n if (key == null) {\n return;\n }\n errorSubscribes.remove(key);\n errorTimeSubscribes.remove(key);\n }\n\n public static Event getOkSubscribe(String key) {\n return okSubscribes.get(key);\n }\n\n public synchronized static void removeOkSubscribe(String key) {\n if (key == null) {\n return;\n }\n okSubscribes.remove(key);\n okTimeSubscribes.remove(key);\n }\n\n public static int getErrorSubscribesSize() {\n return errorSubscribes.size();\n }\n\n public static int getOkSubscribesSize() {\n return okSubscribes.size();\n }\n\n public static void publishOkEvent(ResponseEvent evt) {\n Response response = evt.getResponse();\n CallIdHeader callIdHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME);\n String callId = callIdHeader.getCallId();\n Event event = okSubscribes.get(callId);\n if (event != null) {\n removeOkSubscribe(callId);\n event.response(new EventResult(evt));\n }\n }\n\n public static void publishAckEvent(RequestEvent evt) {\n String callId = evt.getDialog().getCallId().getCallId();\n Event event = okSubscribes.get(callId);\n if (event != null) {\n removeOkSubscribe(callId);\n event.response(new EventResult(evt));\n }\n }\n\n // @Scheduled(cron=\"*/5 * * * * ?\") //每五秒执行一次\n // @Scheduled(fixedRate= 100 * 60 * 60 )\n @Scheduled(cron = \"0 0/5 * * * ?\") // 每5分钟执行一次\n public void execute() {\n log.info(\"[定时任务] 清理过期的SIP订阅信息\");\n\n Instant instant = Instant.now().minusMillis(TimeUnit.MINUTES.toMillis(5));\n\n for (String key : okTimeSubscribes.keySet()) {\n if (okTimeSubscribes.get(key).isBefore(instant)) {\n okSubscribes.remove(key);\n okTimeSubscribes.remove(key);\n }\n }\n for (String key : errorTimeSubscribes.keySet()) {\n if (errorTimeSubscribes.get(key).isBefore(instant)) {\n errorSubscribes.remove(key);\n errorTimeSubscribes.remove(key);\n }\n }\n log.debug(\"okTimeSubscribes.size:{}\", okTimeSubscribes.size());\n log.debug(\"okSubscribes.size:{}\", okSubscribes.size());\n log.debug(\"errorTimeSubscribes.size:{}\", errorTimeSubscribes.size());\n log.debug(\"errorSubscribes.size:{}\", errorSubscribes.size());\n }\n}" }, { "identifier": "SipRequestProcessor", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/request/SipRequestProcessor.java", "snippet": "public interface SipRequestProcessor {\n\n /**\n * 对SIP事件进行处理\n * \n * @param event SIP事件\n */\n void process(RequestEvent event);\n\n}" }, { "identifier": "SipResponseProcessor", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/response/SipResponseProcessor.java", "snippet": "public interface SipResponseProcessor {\n\n\t/**\n\t * 处理接收IPCamera发来的SIP协议响应消息\n\t * @param evt 消息对象\n\t */\n\tvoid process(ResponseEvent evt);\n\n\n}" }, { "identifier": "ITimeoutProcessor", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/timeout/ITimeoutProcessor.java", "snippet": "public interface ITimeoutProcessor {\n void process(TimeoutEvent event);\n}" } ]
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.sip.*; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.commons.collections4.CollectionUtils; import com.alibaba.fastjson.JSON; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.event.SipSubscribe; import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessor; import io.github.lunasaw.sip.common.transmit.event.response.SipResponseProcessor; import io.github.lunasaw.sip.common.transmit.event.timeout.ITimeoutProcessor; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.apm.toolkit.trace.Trace; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
2,315
package io.github.lunasaw.sip.common.transmit; /** * SIP信令处理类观察者 * * @author luna */ @Slf4j @Component public class SipProcessorObserver implements SipListener { @Autowired private SipProcessorInject sipProcessorInject; /** * 对SIP事件进行处理 */
package io.github.lunasaw.sip.common.transmit; /** * SIP信令处理类观察者 * * @author luna */ @Slf4j @Component public class SipProcessorObserver implements SipListener { @Autowired private SipProcessorInject sipProcessorInject; /** * 对SIP事件进行处理 */
private static final Map<String, List<SipRequestProcessor>> REQUEST_PROCESSOR_MAP = new ConcurrentHashMap<>();
3
2023-10-11 06:56:28+00:00
4k
1415181920/yamis-admin
cocoyam-common/src/main/java/io/xiaoyu/common/req/CommonPageRequest.java
[ { "identifier": "PageResp", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/resp/PageResp.java", "snippet": "@Getter\n@Setter\npublic class PageResp<T> extends Page<T>{\n\n /**\n * 当前页的列表\n */\n private List<T> items;\n /**\n * 当前页码\n */\n private long pageNum;\n /**\n * 每页条数\n */\n private long perPage;\n\n\n public PageResp(){\n super();\n }\n\n public PageResp(long page,long perPage,long total){\n super(page,perPage,total);\n this.pageNum = page;\n this.perPage = perPage;\n this.total = total;\n }\n\n public PageResp(long page,long perPage,long total,List<T> items){\n super(page,perPage,total);\n this.pageNum = page;\n this.perPage = perPage;\n this.total = total;\n this.items = items;\n }\n\n public PageResp(IPage<T> page){\n super(page.getCurrent(), page.getSize(), page.getTotal());\n this.items = page.getRecords();\n this.pageNum = page.getCurrent();\n this.perPage = page.getSize();\n this.total = page.getTotal();\n }\n\n public PageResp(long page,long perPage){\n super(page,perPage);\n this.pageNum = page;\n this.perPage = perPage;\n }\n\n @Override\n @JsonIgnore\n public long getSize() {\n return this.perPage;\n }\n\n @Override\n public PageResp<T> setSize(long size) {\n this.size = size;\n this.perPage = size;\n return this;\n }\n\n\n @Override\n @JsonIgnore\n public long getCurrent() {\n return this.pageNum;\n }\n\n @Override\n public PageResp<T> setCurrent(long current) {\n this.current = current;\n this.pageNum = current;\n return this;\n }\n\n @Override\n @JsonIgnore\n public List<T> getRecords() {\n return this.records;\n }\n\n @Override\n public PageResp<T> setRecords(List<T> records) {\n this.records = records;\n this.items = records;\n return this;\n }\n\n}" }, { "identifier": "CommonServletUtil", "path": "cocoyam-common/src/main/java/io/xiaoyu/common/util/CommonServletUtil.java", "snippet": "@Slf4j\npublic class CommonServletUtil {\n\n /**\n * 从请求中中获取参数\n **/\n public static String getParamFromRequest(String paramName) {\n HttpServletRequest request = getRequest();\n\n // 1. 尝试从请求体里面读取\n String paramValue = request.getParameter(paramName);\n\n // 2. 尝试从header里读取\n if (ObjectUtil.isEmpty(paramValue)) {\n paramValue = request.getHeader(paramName);\n }\n // 3. 尝试从cookie里读取\n if (ObjectUtil.isEmpty(paramValue)) {\n Cookie[] cookies = request.getCookies();\n if(ObjectUtil.isNotEmpty(cookies)) {\n for (Cookie cookie : cookies) {\n String cookieName = cookie.getName();\n if (cookieName.equals(paramName)) {\n return cookie.getValue();\n }\n }\n }\n }\n // 4. 返回\n return paramValue;\n }\n\n public static HttpServletRequest getRequest() {\n ServletRequestAttributes servletRequestAttributes;\n try {\n servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n } catch (Exception e) {\n log.error(\">>> 非Web上下文无法获取Request:\", e);\n throw new CommonException(\"非Web上下文无法获取Request\");\n }\n if (servletRequestAttributes == null) {\n throw new CommonException(\"非Web上下文无法获取Request\");\n } else {\n return servletRequestAttributes.getRequest();\n }\n }\n\n public static HttpServletResponse getResponse() {\n ServletRequestAttributes servletRequestAttributes;\n try {\n servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n } catch (Exception e) {\n log.error(\">>> 非Web上下文无法获取Response:\", e);\n throw new CommonException(\"非Web上下文无法获取Response\");\n }\n if (servletRequestAttributes == null) {\n throw new CommonException(\"非Web上下文无法获取Response\");\n } else {\n return servletRequestAttributes.getResponse();\n }\n }\n\n public static boolean isWeb() {\n return RequestContextHolder.getRequestAttributes() != null;\n }\n}" } ]
import cn.hutool.core.convert.Convert; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import io.xiaoyu.common.resp.PageResp; import io.xiaoyu.common.util.CommonServletUtil; import lombok.extern.slf4j.Slf4j; import java.util.List;
1,631
/* * Copyright [2022] [https://www.xiaonuo.vip] * * Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Snowy源码头部的版权声明。 * 3.本项目代码可免费商业使用,商业使用请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://www.xiaonuo.vip * 5.不可二次分发开源参与同类竞品,如有想法可联系团队[email protected]商议合作。 * 6.若您的项目无法满足以上几点,需要更多功能代码,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip */ package io.xiaoyu.common.req; /** * 通用分页请求 * * @author xiaoyu * @date 2021/12/18 14:43 */ @Slf4j public class CommonPageRequest { private static final String PAGE_SIZE_PARAM_NAME = "perPage"; private static final String PAGE_PARAM_NAME = "page"; private static final Integer PAGE_SIZE_MAX_VALUE = 100; public static <T> PageResp<T> defaultPage() { return defaultPage(null); } public static <T> PageResp<T> defaultPage(List<OrderItem> orderItemList) { int perPage = 20; int page = 1; //每页条数
/* * Copyright [2022] [https://www.xiaonuo.vip] * * Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Snowy源码头部的版权声明。 * 3.本项目代码可免费商业使用,商业使用请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://www.xiaonuo.vip * 5.不可二次分发开源参与同类竞品,如有想法可联系团队[email protected]商议合作。 * 6.若您的项目无法满足以上几点,需要更多功能代码,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip */ package io.xiaoyu.common.req; /** * 通用分页请求 * * @author xiaoyu * @date 2021/12/18 14:43 */ @Slf4j public class CommonPageRequest { private static final String PAGE_SIZE_PARAM_NAME = "perPage"; private static final String PAGE_PARAM_NAME = "page"; private static final Integer PAGE_SIZE_MAX_VALUE = 100; public static <T> PageResp<T> defaultPage() { return defaultPage(null); } public static <T> PageResp<T> defaultPage(List<OrderItem> orderItemList) { int perPage = 20; int page = 1; //每页条数
String pageSizeString = CommonServletUtil.getParamFromRequest(PAGE_SIZE_PARAM_NAME);
1
2023-10-09 06:04:30+00:00
4k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/subtypes/subCommand_reloadconfig.java
[ { "identifier": "CommandCooldown", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/CommandCooldown.java", "snippet": "public interface CommandCooldown {\n long cooldownSeconds();\n\n default long getCooldown() {\n return cooldownSeconds() * 1000;\n }\n}" }, { "identifier": "CommandSource", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/CommandSource.java", "snippet": "@Getter\npublic class CommandSource {\n private final CommandSender sender;\n private final Player player;\n\n public CommandSource(CommandSender sender) {\n this.sender = sender;\n this.player = sender instanceof Player ? (Player) sender : null;\n }\n\n public void send(String message) {\n sender.sendMessage(message);\n }\n}" }, { "identifier": "SWMCommand", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/commands/SWMCommand.java", "snippet": "public abstract class SWMCommand implements CommandExecutor, TabCompleter {\n private static final Map<UUID, HashMap<SWMCommand, Long>> CMD_COOLDOWN = new HashMap<>();\n @Getter\n private static final Set<String> worldsInUse = new HashSet<>();\n\n public static final String COMMAND_SUFFIX = \"subCommand_\";\n\n private final CommandParameters params;\n private final String name;\n private final String description;\n private final String usage;\n private final Boolean inGameOnly;\n private final List<String> aliases;\n private final String permission;\n\n private CommandSource sender;\n\n protected SWMCommand() {\n this.params = this.getClass().getAnnotation(CommandParameters.class);\n this.name = this.getClass().getSimpleName().replace(COMMAND_SUFFIX, \"\").toLowerCase();\n this.description = this.params.description();\n this.usage = this.params.usage();\n this.aliases = Arrays.asList(this.params.aliases().split(\",\"));\n this.permission = this.params.permission();\n this.inGameOnly = this.params.inGameOnly();\n }\n\n public abstract void run(CommandSource sender, String[] args);\n\n @Override\n public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {\n return false;\n }\n\n @Override\n public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {\n return null;\n }\n\n public static void register() {\n SWMPlugin.getInstance().commandMap.register(\"cswm\", \"cswm\", new SlimeCommandHandler());\n SWMPlugin.getInstance().commandMap.register(\"swm\", \"swm\", new SlimeCommandHandler());\n }\n\n public static class SlimeCommandHandler extends Command {\n\n public SWMCommand command;\n\n public SlimeCommandHandler() {\n super(\"swm\", \"Manage SwoftyWorldManager\", \"\", new ArrayList<>(Collections.singletonList(\"cswm\")));\n }\n\n @Override\n public boolean execute(CommandSender sender, String commandLabel, String[] args) {\n if (args.length == 0) {\n sender.sendMessage((sender instanceof Player) ?\n Logging.COMMAND_PREFIX + \"§dContinued Slime World Manager §7is a plugin by §cSwofty-Developments §7that implements the Slime Region Format based on §bSlime World Manager. §7To check out the help page, type §e/cswm help§7.\" :\n Logging.CONSOLE_PREFIX + \"Continued World Manager is a plugin by SwoftyDevelopments that implements the Slime Region Format based on Slime World Manager. To check out the help page, type /cswm help.\");\n return false;\n }\n\n for (SWMCommand swmCommand : CommandLoader.commands) {\n if (swmCommand.name.equals(args[0]) || swmCommand.aliases.contains(args[0])) {\n this.command = swmCommand;\n }\n }\n\n if (this.command == null) {\n sender.sendMessage((sender instanceof Player) ?\n Logging.COMMAND_PREFIX + \"§cUnknown command. To check out the help page, type §e/swm help§c.\" :\n Logging.CONSOLE_PREFIX + \" Unknown command. To check out the help page, type /swm help.\");\n return false;\n }\n\n if (this.command.inGameOnly && !(sender instanceof Player)) {\n sender.sendMessage(Logging.CONSOLE_PREFIX + \"This command can only be run in-game.\");\n return false;\n }\n\n command.sender = new CommandSource(sender);\n\n if (!command.permission.equals(\"\") && !sender.hasPermission(command.permission)) {\n sender.sendMessage(\"§cYou do not have permission to perform this command.\");\n return false;\n }\n\n if (command instanceof CommandCooldown && sender instanceof Player) {\n HashMap<SWMCommand, Long> cooldowns = new HashMap<>();\n if (CMD_COOLDOWN.containsKey(((Player) sender).getUniqueId())) {\n cooldowns = CMD_COOLDOWN.get(((Player) sender).getUniqueId());\n if (cooldowns.containsKey(command)) {\n if (System.currentTimeMillis() - cooldowns.get(command) < ((CommandCooldown) command).getCooldown()) {\n sender.sendMessage(\"§cYou are on cooldown for $SECONDSs.\".replace(\"$SECONDS\", String.valueOf((double) (System.currentTimeMillis() - cooldowns.get(command)) / 1000)));\n return false;\n }\n }\n }\n cooldowns.put(command, System.currentTimeMillis() + ((CommandCooldown) command).getCooldown());\n CMD_COOLDOWN.put(((Player) sender).getUniqueId(), cooldowns);\n }\n\n String[] argsWithFirstRemoved = Arrays.stream(args).skip(1).toArray(String[]::new);\n command.run(command.sender, argsWithFirstRemoved);\n return false;\n }\n\n @Override\n public List<String> tabComplete(CommandSender sender, String alias, String[] args) {\n if (args.length <= 1) {\n List<String> list = new ArrayList<>();\n CommandLoader.commands.stream().forEach(entry -> {\n if (entry.name.startsWith(args[0]) || entry.aliases.contains(args[0]))\n list.add(entry.name);\n });\n return list;\n } else {\n for (SWMCommand swmCommand : CommandLoader.commands) {\n if (swmCommand.name.equals(args[0]) || swmCommand.aliases.contains(args[0])) {\n this.command = swmCommand;\n return swmCommand.tabCompleters(sender, alias, args);\n }\n }\n\n this.command = null;\n return new ArrayList<>();\n }\n }\n }\n\n public abstract List<String> tabCompleters(CommandSender sender, String alias, String[] args);\n\n public void send(String message, CommandSource sender) {\n sender.send(ChatColor.GRAY + message.replace(\"&\", \"§\"));\n }\n\n public void send(String message) {\n send(ChatColor.translateAlternateColorCodes('&', message), sender);\n }\n}" }, { "identifier": "ConfigManager", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/config/ConfigManager.java", "snippet": "public class ConfigManager implements net.swofty.swm.api.world.data.ConfigManager {\n\n private static final File PLUGIN_DIR = new File(\"plugins\", \"SwoftyWorldManager\");\n private static final File MAIN_FILE = new File(PLUGIN_DIR, \"main.yml\");\n private static final File WORLDS_FILE = new File(PLUGIN_DIR, \"worlds.yml\");\n private static final File SOURCES_FILE = new File(PLUGIN_DIR, \"sources.yml\");\n\n @Getter\n private static MainConfig mainConfig;\n @Getter(value = AccessLevel.PACKAGE)\n private static YAMLConfigurationLoader mainConfigLoader;\n\n private static net.swofty.swm.plugin.config.WorldsConfig worldConfig;\n @Getter(value = AccessLevel.PACKAGE)\n private static YAMLConfigurationLoader worldConfigLoader;\n\n @Getter\n private static DatasourcesConfig datasourcesConfig;\n\n public static void initialize() throws IOException, ObjectMappingException {\n copyDefaultConfigs();\n\n mainConfigLoader = YAMLConfigurationLoader.builder().setPath(MAIN_FILE.toPath())\n .setFlowStyle(DumperOptions.FlowStyle.BLOCK).setHeaderMode(HeaderMode.PRESERVE).build();\n mainConfig = mainConfigLoader.load().getValue(TypeToken.of(MainConfig.class));\n\n worldConfigLoader = YAMLConfigurationLoader.builder().setPath(WORLDS_FILE.toPath())\n .setFlowStyle(DumperOptions.FlowStyle.BLOCK).setHeaderMode(HeaderMode.PRESERVE).build();\n worldConfig = worldConfigLoader.load().getValue(TypeToken.of(net.swofty.swm.plugin.config.WorldsConfig.class));\n\n YAMLConfigurationLoader datasourcesConfigLoader = YAMLConfigurationLoader.builder().setPath(SOURCES_FILE.toPath())\n .setFlowStyle(DumperOptions.FlowStyle.BLOCK).setHeaderMode(HeaderMode.PRESERVE).build();\n datasourcesConfig = datasourcesConfigLoader.load().getValue(TypeToken.of(DatasourcesConfig.class));\n\n mainConfigLoader.save(mainConfigLoader.createEmptyNode().setValue(TypeToken.of(MainConfig.class), mainConfig));\n worldConfig.save();\n datasourcesConfigLoader.save(datasourcesConfigLoader.createEmptyNode().setValue(TypeToken.of(DatasourcesConfig.class), datasourcesConfig));\n }\n\n private static void copyDefaultConfigs() throws IOException {\n PLUGIN_DIR.mkdirs();\n\n if (!MAIN_FILE.exists()) {\n Files.copy(SWMPlugin.getInstance().getResource(\"main.yml\"), MAIN_FILE.toPath());\n }\n\n if (!WORLDS_FILE.exists()) {\n Files.copy(SWMPlugin.getInstance().getResource(\"worlds.yml\"), WORLDS_FILE.toPath());\n }\n\n if (!SOURCES_FILE.exists()) {\n Files.copy(SWMPlugin.getInstance().getResource(\"worlds.yml\"), SOURCES_FILE.toPath());\n }\n }\n\n public WorldsConfig getWorldConfig() {\n return worldConfig;\n }\n}" }, { "identifier": "Logging", "path": "swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/log/Logging.java", "snippet": "public class Logging {\n\n public static final String COMMAND_PREFIX = ChatColor.LIGHT_PURPLE + ChatColor.BOLD.toString() + \"CSWM \" + ChatColor.GRAY + \">> \";\n public static final String CONSOLE_PREFIX = ChatColor.LIGHT_PURPLE + \"[CSWM] \";\n\n public static void info(String message) {\n Bukkit.getConsoleSender().sendMessage(CONSOLE_PREFIX + ChatColor.GRAY + message);\n }\n\n public static void warning(String message) {\n Bukkit.getConsoleSender().sendMessage(CONSOLE_PREFIX + ChatColor.YELLOW + message);\n }\n\n public static void error(String message) {\n Bukkit.getConsoleSender().sendMessage(CONSOLE_PREFIX + ChatColor.RED + message);\n }\n}" } ]
import net.swofty.swm.plugin.commands.CommandCooldown; import net.swofty.swm.plugin.commands.CommandParameters; import net.swofty.swm.plugin.commands.CommandSource; import net.swofty.swm.plugin.commands.SWMCommand; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.log.Logging; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import java.io.IOException; import java.util.List;
2,676
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Reloads the config files", inGameOnly = false, permission = "swm.reload") public class subCommand_reloadconfig extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 3; } @Override
package net.swofty.swm.plugin.commands.subtypes; @CommandParameters(description = "Reloads the config files", inGameOnly = false, permission = "swm.reload") public class subCommand_reloadconfig extends SWMCommand implements CommandCooldown { @Override public long cooldownSeconds() { return 3; } @Override
public void run(CommandSource sender, String[] args) {
1
2023-10-08 10:54:28+00:00
4k
calicosun258/5c-client-N
src/main/java/fifthcolumn/n/mixins/TextVisitFactoryMixin.java
[ { "identifier": "LarpModule", "path": "src/main/java/fifthcolumn/n/modules/LarpModule.java", "snippet": "public class LarpModule extends Module {\n private final SettingGroup sgGeneral = this.settings.getDefaultGroup();\n\n public final Setting<String> alias = this.sgGeneral.add(new StringSetting.Builder()\n .name(\"player uid\")\n .description(\"player uuid to larp as\")\n .defaultValue(\"24b82429-15f2-4d7f-91f6-d277a1858949\")\n .build());\n\n public final Setting<String> aliasName = this.sgGeneral.add(new StringSetting.Builder()\n .name(\"player name\")\n .description(\"player name to larp as\")\n .defaultValue(\"orsond\").build());\n\n public LarpModule() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Larping\", \"Make all griefers larp as another player\");\n }\n\n public static @Nullable String modifyPlayerNameInstances(String text) {\n\n for (CopeService.Griefer entity : NMod.getCopeService().griefers()) {\n if (entity.playerNameAlias != null) {\n Optional<GameProfile> profile = NMod.profileCache.findPlayerName(entity.playerNameAlias);\n if (profile.isPresent()) {\n text = StringUtils.replace(text, entity.playerName, entity.playerNameAlias);\n }\n }\n }\n\n if (MeteorClient.mc != null && MeteorClient.mc.player != null) {\n LarpModule larpModule = Modules.get().get(LarpModule.class);\n if (larpModule.isActive()) {\n String aliasName = larpModule.aliasName.get();\n text = StringUtils.replace(text, MeteorClient.mc.player.getEntityName(), aliasName);\n }\n }\n\n return text;\n }\n\n public static Optional<String> getPlayerEntityName(PlayerEntity player) {\n if (MeteorClient.mc.player != null && player.getGameProfile().getId().equals(MeteorClient.mc.player.getUuid())) {\n LarpModule larpModule = Modules.get().get(LarpModule.class);\n if (larpModule.isActive()) {\n UUID uuid = UUID.fromString(larpModule.alias.get());\n Optional<GameProfile>profile = NMod.profileCache.findByUUID(uuid);\n if (profile.isPresent()) {\n return profile.map(GameProfile::getName);\n }\n }\n } else {\n for (CopeService.Griefer griefer : NMod.getCopeService().griefers()) {\n if (player.getGameProfile().getId().equals(griefer.playerId)) {\n Optional<GameProfile> profile = NMod.profileCache.findByUUID(griefer.playerId);\n if (profile.isPresent()) {\n return profile.map(GameProfile::getName);\n }\n }\n }\n }\n\n return Optional.empty();\n }\n}" }, { "identifier": "StreamerMode", "path": "src/main/java/fifthcolumn/n/modules/StreamerMode.java", "snippet": "public class StreamerMode extends Module {\n private final SettingGroup sgGeneral;\n private final Setting<Boolean> hideServerInfo;\n private final Setting<Boolean> hideAccount;\n private final Setting<Boolean> generifyPlayerNames;\n private final Setting<Integer> addFakePlayers;\n private final Setting<String> spoofServerBrand;\n public final Setting<Boolean> useRandomIpOffset;\n\n public StreamerMode() {\n super(NAddOn.FIFTH_COLUMN_CATEGORY, \"Streamer mode\", \"Hides sensitive info from stream viewers\");\n this.sgGeneral = this.settings.getDefaultGroup();\n this.hideServerInfo = this.sgGeneral.add((new BoolSetting.Builder()).name(\"hide server info\").defaultValue(true).build());\n this.hideAccount = this.sgGeneral.add((new BoolSetting.Builder()).name(\"hide Logged in account text\").defaultValue(true).build());\n this.generifyPlayerNames = this.sgGeneral.add(new BoolSetting.Builder().name(\"use a generic name for non-griefers\")\n .defaultValue(true).build());\n this.addFakePlayers = this.sgGeneral.add(new IntSetting.Builder()\n .name(\"add fake players to tablist\")\n .sliderRange(0, 10).defaultValue(5)\n .build());\n this.spoofServerBrand = this.sgGeneral.add((new StringSetting.Builder()).name(\"spoof server brand\").description(\"Change server brand label in F3, blank to disable.\").defaultValue(\"Paper devs are ops\").build());\n this.useRandomIpOffset = this.sgGeneral.add((new BoolSetting.Builder()).name(\"use a random ip header offset\").defaultValue(true).build());\n }\n\n @EventHandler\n public void onMessage(PacketEvent.Receive event) {\n if (event.packet instanceof GameMessageS2CPacket packet) {\n if (packet.content().getString().contains(\"join\") && isGenerifyNames()) {\n event.cancel();\n Text text = Text.literal(\"A player has joined the game\").formatted(Formatting.YELLOW);\n this.mc.inGameHud.getChatHud().addMessage(text);\n }\n }\n\n }\n\n public static boolean isStreaming() {\n return Modules.get().get(StreamerMode.class).isActive();\n }\n\n public static boolean isHideServerInfoEnabled() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.hideServerInfo.get();\n }\n\n public static boolean isHideAccountEnabled() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.hideAccount.get();\n }\n\n public static boolean isGenerifyNames() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() && streamerMode.generifyPlayerNames.get();\n }\n\n public static int addFakePlayers() {\n StreamerMode streamerMode = Modules.get().get(StreamerMode.class);\n return streamerMode != null && streamerMode.isActive() ? streamerMode.addFakePlayers.get() : 0;\n }\n\n public static String spoofServerBrand() {\n return Modules.get().get(StreamerMode.class).spoofServerBrand.get();\n }\n\n public static @Nullable String anonymizePlayerNameInstances(String text) {\n if (MeteorClient.mc != null && MeteorClient.mc.player != null && MeteorClient.mc.getNetworkHandler() != null && isGenerifyNames()) {\n\n for (PlayerListEntry player : MeteorClient.mc.getNetworkHandler().getPlayerList()) {\n if (player.getProfile() != null) {\n String fakeName = NMod.genericNames.getName(player.getProfile().getId());\n text = StringUtils.replace(text, player.getProfile().getName(), fakeName);\n if (player.getDisplayName() != null) {\n text = StringUtils.replace(text, player.getDisplayName().getString(), fakeName);\n }\n }\n }\n }\n\n return text;\n }\n\n public static Optional<String> getPlayerEntityName(PlayerEntity player) {\n return isGenerifyNames() && MeteorClient.mc.getNetworkHandler() != null && !player.getGameProfile().getId().equals(MeteorClient.mc.player.getUuid()) && MeteorClient.mc.getNetworkHandler() != null && isGenerifyNames() ? Optional.of(NMod.genericNames.getName(player.getGameProfile().getId())) : Optional.empty();\n }\n}" } ]
import fifthcolumn.n.modules.LarpModule; import fifthcolumn.n.modules.StreamerMode; import net.minecraft.text.TextVisitFactory; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable;
1,881
package fifthcolumn.n.mixins; @Mixin({TextVisitFactory.class}) public class TextVisitFactoryMixin { @ModifyVariable( method = {"visitFormatted(Ljava/lang/String;ILnet/minecraft/text/Style;Lnet/minecraft/text/Style;Lnet/minecraft/text/CharacterVisitor;)Z"}, at = @At("HEAD"), ordinal = 0, index = 0, argsOnly = true ) private static String n$modifyAllPlayerNameInstances(String text) { text = LarpModule.modifyPlayerNameInstances(text);
package fifthcolumn.n.mixins; @Mixin({TextVisitFactory.class}) public class TextVisitFactoryMixin { @ModifyVariable( method = {"visitFormatted(Ljava/lang/String;ILnet/minecraft/text/Style;Lnet/minecraft/text/Style;Lnet/minecraft/text/CharacterVisitor;)Z"}, at = @At("HEAD"), ordinal = 0, index = 0, argsOnly = true ) private static String n$modifyAllPlayerNameInstances(String text) { text = LarpModule.modifyPlayerNameInstances(text);
text = StreamerMode.anonymizePlayerNameInstances(text);
1
2023-10-14 19:18:35+00:00
4k
shenmejianghu/bili-downloader
src/main/java/com/bilibili/downloader/controller/MainController.java
[ { "identifier": "LiveConfig", "path": "src/main/java/com/bilibili/downloader/pojo/LiveConfig.java", "snippet": "public class LiveConfig {\n //推流地址\n private String url;\n private String secret;\n //循环次数,-1表示无限循环\n private Integer loop;\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public Integer getLoop() {\n return loop;\n }\n\n public void setLoop(Integer loop) {\n this.loop = loop;\n }\n\n public String getSecret() {\n return secret;\n }\n\n public void setSecret(String secret) {\n this.secret = secret;\n }\n}" }, { "identifier": "Result", "path": "src/main/java/com/bilibili/downloader/pojo/Result.java", "snippet": "public class Result<T> {\n private int code;\n private String message;\n private T data;\n\n public static <T> Result<T> success(T data){\n return new Result<>(200,\"操作成功\",data);\n }\n public static <T> Result<T> fail(T data,String message){\n return new Result<>(204,message,data);\n }\n\n public Result(int code, String message, T data) {\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public Result() {\n this.code = 200;\n }\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}" }, { "identifier": "HttpFile", "path": "src/main/java/com/bilibili/downloader/util/HttpFile.java", "snippet": "public class HttpFile {\n\n public static void downloadFile(String destFileName, String srcFilePath,\n HttpServletResponse response) {\n downloadFile(\"application/octet-stream\",destFileName,srcFilePath,response);\n }\n\n public static void downloadFile(String contentType,String destFileName, String srcFilePath,\n HttpServletResponse response){\n try {\n destFileName = new String(destFileName.getBytes(), \"ISO8859-1\");\n } catch (UnsupportedEncodingException e) {\n }\n response.addHeader(\"Content-Disposition\", \"attachment; filename=\" + destFileName);\n response.setContentType(contentType);\n try (FileInputStream fis = new FileInputStream(new File(srcFilePath));\n InputStream is = new BufferedInputStream(fis);\n BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {\n\n byte[] buffer = new byte[2048];\n int read = -1;\n while ((read = is.read(buffer)) != -1) {\n bos.write(buffer, 0, read);\n }\n bos.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" } ]
import cn.hutool.core.io.FileUtil; import cn.hutool.crypto.digest.MD5; import cn.hutool.http.HttpRequest; import cn.hutool.json.JSON; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.bilibili.downloader.pojo.LiveConfig; import com.bilibili.downloader.pojo.Result; import com.bilibili.downloader.util.HttpFile; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.http.client.ClientHttpRequest; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
3,005
if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(videoUrl, HttpMethod.GET,videoRequestCallback,videoResponseExtractor); if ((Boolean)result){ videoFile = finalFileName; break; } } } if (audioList != null){ for (Object audio:audioList){ JSONObject map = (JSONObject)audio; String audioUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object audioSize = restTemplate.execute(audioUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("音频地址:{}",audioUrl); logger.info("音频大小:{}",audioSize); RequestCallback audioRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+audioSize); } }; String fileName = StringUtils.substringBefore(audioUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp3"; ResponseExtractor audioResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载音频文件:{}", finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("音频文件下载完成:{}", finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(audioUrl, HttpMethod.GET,audioRequestCallback,audioResponseExtractor); if ((Boolean)result){ audioFile = finalFileName; break; } } } if (StringUtils.isEmpty(videoFile)&&StringUtils.isEmpty(audioFile)){ logger.warn("未找到视频:{}",url); return Result.fail(null,"未找到视频"); } if (StringUtils.isNotEmpty(videoFile) && StringUtils.isNotEmpty(audioFile)){ //ffmpeg -i 视频文件名.mp4 -i 音频文件名.mp3 -c:v copy -c:a copy 输出文件名.mp4 List<String> commands = new ArrayList<>(); commands.add(ffmpegPath); commands.add("-i"); commands.add(dir+videoFile); commands.add("-i"); commands.add(dir+audioFile); commands.add("-c:v"); commands.add("copy"); commands.add("-c:a"); commands.add("copy"); commands.add(dir+"final-file.mp4"); logger.info("开始合成视频音频"); ProcessBuilder builder = new ProcessBuilder(); builder.command(commands); try { builder.inheritIO().start().waitFor(); logger.info("视频合成完成"); } catch (InterruptedException | IOException e) { logger.info("视频合成失败:{}", ExceptionUtils.getStackTrace(e)); } return Result.success(uuid+"_"+"final-file.mp4"); } if (StringUtils.isNotEmpty(videoFile)){ return Result.success(uuid+"_"+videoFile); } if (StringUtils.isNotEmpty(audioFile)){ return Result.success(uuid+"_"+audioFile); } return Result.fail(null,"未找到视频"); }else { logger.warn("视频地址解析错误"); return Result.fail(null,"视频地址解析错误"); } }catch (Exception e){ logger.error(ExceptionUtils.getStackTrace(e)); return Result.fail(null,"视频地址解析错误"); } } @RequestMapping("/live") @ResponseBody
package com.bilibili.downloader.controller; @Controller public class MainController { private static Logger logger = LoggerFactory.getLogger(MainController.class); @Autowired private RestTemplate restTemplate; @Value("${server.tomcat.basedir}") private String baseDir; @Value("${application.ffmpeg-path}") private String ffmpegPath; @RequestMapping("/download") public void download(HttpServletResponse response, String file){ logger.info("下载视频文件:{}",file); if (StringUtils.isEmpty(file)){ return; } String[] arr = file.split("_"); if (arr.length != 2){ return; } String filePath = baseDir+File.separator+arr[0]+File.separator+arr[1]; if (!FileUtil.exist(filePath)){ return; } HttpFile.downloadFile(arr[1],filePath,response); FileUtil.del(baseDir+File.separator+arr[0]); } @RequestMapping("/parse") @ResponseBody public Result<String> parse(String url){ try { logger.info("开始解析视频地址:{}",url); String html = restTemplate.getForObject(url,String.class); String regex = "(?<=<script>window.__playinfo__=).*?(?=</script>)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.find()) { String uuid = UUID.randomUUID().toString().replace("-",""); String dir = baseDir + File.separator + uuid +File.separator; if (!FileUtil.exist(dir)){ FileUtil.mkdir(dir); } String videoFile = ""; String audioFile = ""; String jsonStr = matcher.group(); JSON json = JSONUtil.parse(jsonStr); JSONArray videoList = (JSONArray)json.getByPath("data.dash.video"); JSONArray audioList = (JSONArray)json.getByPath("data.dash.audio"); if (videoList != null){ for (Object video:videoList){ JSONObject map = (JSONObject)video; String videoUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object videoSize = restTemplate.execute(videoUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("视频地址:{}",videoUrl); logger.info("视频大小:{}",videoSize); RequestCallback videoRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+videoSize); } }; String fileName = StringUtils.substringBefore(videoUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp4"; ResponseExtractor videoResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载视频文件:{}",finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("视频文件下载完成:{}",finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(videoUrl, HttpMethod.GET,videoRequestCallback,videoResponseExtractor); if ((Boolean)result){ videoFile = finalFileName; break; } } } if (audioList != null){ for (Object audio:audioList){ JSONObject map = (JSONObject)audio; String audioUrl = map.get("baseUrl").toString(); String segmentInit = map.getByPath("SegmentBase.Initialization").toString(); RequestCallback requestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes="+segmentInit); } }; ResponseExtractor responseExtractor = new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getHeaders().get("Content-Range").get(0).split("/")[1]; } }; Object audioSize = restTemplate.execute(audioUrl, HttpMethod.GET,requestCallback,responseExtractor); logger.info("音频地址:{}",audioUrl); logger.info("音频大小:{}",audioSize); RequestCallback audioRequestCallback = new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { clientHttpRequest.getHeaders().add("Referer",url); clientHttpRequest.getHeaders().add("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"); clientHttpRequest.getHeaders().add("Range","bytes=0-"+audioSize); } }; String fileName = StringUtils.substringBefore(audioUrl,".m4s"); fileName = StringUtils.substringAfterLast(fileName,"/"); final String finalFileName = fileName +".mp3"; ResponseExtractor audioResponseExtractor = new ResponseExtractor<Boolean>() { @Override public Boolean extractData(ClientHttpResponse clientHttpResponse) throws IOException { OutputStream output = null; try { output = new FileOutputStream(dir+ finalFileName); logger.info("开始下载音频文件:{}", finalFileName); IOUtils.copy(clientHttpResponse.getBody(),output); logger.info("音频文件下载完成:{}", finalFileName); return Boolean.TRUE; }catch (Exception e){ e.printStackTrace(); return Boolean.FALSE; }finally { if (output != null){ output.close(); } } } }; Object result = restTemplate.execute(audioUrl, HttpMethod.GET,audioRequestCallback,audioResponseExtractor); if ((Boolean)result){ audioFile = finalFileName; break; } } } if (StringUtils.isEmpty(videoFile)&&StringUtils.isEmpty(audioFile)){ logger.warn("未找到视频:{}",url); return Result.fail(null,"未找到视频"); } if (StringUtils.isNotEmpty(videoFile) && StringUtils.isNotEmpty(audioFile)){ //ffmpeg -i 视频文件名.mp4 -i 音频文件名.mp3 -c:v copy -c:a copy 输出文件名.mp4 List<String> commands = new ArrayList<>(); commands.add(ffmpegPath); commands.add("-i"); commands.add(dir+videoFile); commands.add("-i"); commands.add(dir+audioFile); commands.add("-c:v"); commands.add("copy"); commands.add("-c:a"); commands.add("copy"); commands.add(dir+"final-file.mp4"); logger.info("开始合成视频音频"); ProcessBuilder builder = new ProcessBuilder(); builder.command(commands); try { builder.inheritIO().start().waitFor(); logger.info("视频合成完成"); } catch (InterruptedException | IOException e) { logger.info("视频合成失败:{}", ExceptionUtils.getStackTrace(e)); } return Result.success(uuid+"_"+"final-file.mp4"); } if (StringUtils.isNotEmpty(videoFile)){ return Result.success(uuid+"_"+videoFile); } if (StringUtils.isNotEmpty(audioFile)){ return Result.success(uuid+"_"+audioFile); } return Result.fail(null,"未找到视频"); }else { logger.warn("视频地址解析错误"); return Result.fail(null,"视频地址解析错误"); } }catch (Exception e){ logger.error(ExceptionUtils.getStackTrace(e)); return Result.fail(null,"视频地址解析错误"); } } @RequestMapping("/live") @ResponseBody
public Result<String> live(@RequestBody LiveConfig live){
0
2023-10-08 01:32:06+00:00
4k
Robothy/sdwebui-java-sdk
src/main/java/io/github/robothy/sdwebui/sdk/services/DefaultTxt2ImageService.java
[ { "identifier": "SdWebuiBeanContainer", "path": "src/main/java/io/github/robothy/sdwebui/sdk/SdWebuiBeanContainer.java", "snippet": "public interface SdWebuiBeanContainer {\n\n static SdWebuiBeanContainer create(SdWebuiOptions options) {\n return new DefaultSdWebuiBeanContainer(options);\n }\n\n <T> T getBean(Class<T> serviceClass);\n\n void register(Class<?> serviceClass, Object service);\n\n}" }, { "identifier": "Txt2Image", "path": "src/main/java/io/github/robothy/sdwebui/sdk/Txt2Image.java", "snippet": "public interface Txt2Image {\n\n /**\n * Generate images from text.\n *\n * @param options The options to generate images.\n * @return The result of the generation.\n *\n * @throws io.github.robothy.sdwebui.sdk.exceptions.SdWebuiServerValidationException\n * @throws io.github.robothy.sdwebui.sdk.exceptions.SdWebuiBadRequestException\n */\n Txt2ImgResult txt2Img(Txt2ImageOptions options);\n\n}" }, { "identifier": "SdWebuiOptions", "path": "src/main/java/io/github/robothy/sdwebui/sdk/models/SdWebuiOptions.java", "snippet": "@Getter\npublic class SdWebuiOptions {\n\n private final String endpoint;\n\n public SdWebuiOptions(String endpoint) {\n this.endpoint = endpoint;\n }\n\n}" }, { "identifier": "SystemInfo", "path": "src/main/java/io/github/robothy/sdwebui/sdk/models/SystemInfo.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class SystemInfo {\n\n @JsonProperty(\"Platform\")\n private String platform;\n\n @JsonProperty(\"Python\")\n private String pythonVersion;\n\n @JsonProperty(\"Version\")\n private String sdwebuiVersion;\n\n}" }, { "identifier": "Txt2ImageOptions", "path": "src/main/java/io/github/robothy/sdwebui/sdk/models/options/Txt2ImageOptions.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class Txt2ImageOptions {\n\n\n @Builder.Default\n @JsonProperty(\"enable_hr\")\n private boolean enableHr = false;\n\n @Builder.Default\n @JsonProperty(\"denoising_strength\")\n private double denoisingStrength = 0.7;\n\n @Builder.Default\n @JsonProperty(\"firstphase_width\")\n private int firstphaseWidth = 0;\n\n @Builder.Default\n @JsonProperty(\"firstphase_height\")\n private int firstphaseHeight = 0;\n\n @Builder.Default\n @JsonProperty(\"hr_scale\")\n private int hrScale = 2;\n\n @Builder.Default\n @JsonProperty(\"hr_upscaler\")\n private HiResUpscaler hrUpscaler = HiResUpscaler.Latent;\n\n @Builder.Default\n @JsonProperty(\"hr_second_pass_steps\")\n private int hrSecondPassSteps = 0;\n\n @Builder.Default\n @JsonProperty(\"hr_resize_x\")\n private int hrResizeX = 0;\n\n @Builder.Default\n @JsonProperty(\"hr_resize_y\")\n private int hrResizeY = 0;\n\n @Builder.Default\n @JsonProperty(\"prompt\")\n private String prompt = \"\";\n\n @Builder.Default\n @JsonProperty(\"styles\")\n private List<String> styles = new ArrayList<>();\n\n @Builder.Default\n @JsonProperty(\"seed\")\n private long seed = -1L;\n\n @Builder.Default\n @JsonProperty(\"subseed\")\n private long subseed = -1L;\n\n @Builder.Default\n @JsonProperty(\"subseed_strength\")\n private double subseedStrength = 0.0;\n\n @Builder.Default\n @JsonProperty(\"seed_resize_from_h\")\n private int seedResizeFromH = 0;\n\n @Builder.Default\n @JsonProperty(\"seed_resize_from_w\")\n private int seedResizeFromW = 0;\n\n @Builder.Default\n @JsonProperty(\"sampler_name\")\n private String samplerName = \"DPM++ 2M Karras\";\n\n @Builder.Default\n @JsonProperty(\"batch_size\")\n private int batchSize = 1;\n\n @Builder.Default\n @JsonProperty(\"n_iter\")\n private int nIter = 1;\n\n @Builder.Default\n @JsonProperty(\"steps\")\n private Integer steps = null;\n\n @Builder.Default\n @JsonProperty(\"cfg_scale\")\n private double cfgScale = 7.0;\n\n @Builder.Default\n @JsonProperty(\"width\")\n private int width = 512;\n\n @Builder.Default\n @JsonProperty(\"height\")\n private int height = 512;\n\n @Builder.Default\n @JsonProperty(\"restore_faces\")\n private boolean restoreFaces = false;\n\n @Builder.Default\n @JsonProperty(\"tiling\")\n private boolean tiling = false;\n\n @Builder.Default\n @JsonProperty(\"do_not_save_samples\")\n private boolean doNotSaveSamples = false;\n\n @Builder.Default\n @JsonProperty(\"do_not_save_grid\")\n private boolean doNotSaveGrid = false;\n\n @Builder.Default\n @JsonProperty(\"negative_prompt\")\n private String negativePrompt = \"\";\n\n @Builder.Default\n @JsonProperty(\"eta\")\n private double eta = 1.0;\n\n @Builder.Default\n @JsonProperty(\"s_churn\")\n private int sChurn = 0;\n\n @Builder.Default\n @JsonProperty(\"s_tmax\")\n private int sTmax = 0;\n\n @Builder.Default\n @JsonProperty(\"s_tmin\")\n private int sTmin = 0;\n\n @Builder.Default\n @JsonProperty(\"s_noise\")\n private int sNoise = 1;\n\n @Builder.Default\n @JsonProperty(\"override_settings\")\n private Map<String, Object> overrideSettings = null;\n\n @Builder.Default\n @JsonProperty(\"override_settings_restore_afterwards\")\n private boolean overrideSettingsRestoreAfterwards = true;\n\n @Builder.Default\n @JsonProperty(\"script_args\")\n private List<String> scriptArgs = new ArrayList<>();\n\n @Builder.Default\n @JsonProperty(\"script_name\")\n private String scriptName = null;\n\n @Builder.Default\n @JsonProperty(\"send_images\")\n private boolean sendImages = true;\n\n @Builder.Default\n @JsonProperty(\"save_images\")\n private boolean saveImages = false;\n\n @Builder.Default\n @JsonProperty(\"alwayson_scripts\")\n private Map<String, Object> alwaysonScripts = null;\n\n @Builder.Default\n @JsonProperty(\"sampler_index\")\n @Deprecated\n private String samplerIndex = null;\n\n @Builder.Default\n @JsonProperty(\"use_deprecated_controlnet\")\n private boolean useDeprecatedControlnet = false;\n\n}" }, { "identifier": "Txt2ImgResult", "path": "src/main/java/io/github/robothy/sdwebui/sdk/models/results/Txt2ImgResult.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Txt2ImgResult {\n\n @JsonProperty(\"images\")\n private List<String> images;\n\n @JsonProperty(\"parameters\")\n private Txt2ImageOptions parameters;\n\n @JsonProperty(\"info\")\n private String info;\n\n}" }, { "identifier": "SdWebuiResponseUtils", "path": "src/main/java/io/github/robothy/sdwebui/sdk/utils/SdWebuiResponseUtils.java", "snippet": "public class SdWebuiResponseUtils {\n\n public static void checkResponseStatus(ClassicHttpResponse response) {\n if (response.getCode() == HttpStatus.SC_OK) {\n return;\n }\n\n try {\n if (response.getCode() == HttpStatus.SC_UNPROCESSABLE_ENTITY) {\n JsonUtils.fromJson(response.getEntity().getContent(), SdWebuiServerValidationException.class);\n }\n\n throw JsonUtils.fromJson(response.getEntity().getContent(), SdWebuiBadRequestException.class);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n }\n\n public static <T> T parseResponse(ClassicHttpResponse response, Class<T> clazz) {\n checkResponseStatus(response);\n try {\n return JsonUtils.fromJson(response.getEntity().getContent(), clazz);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.robothy.sdwebui.sdk.SdWebuiBeanContainer; import io.github.robothy.sdwebui.sdk.Txt2Image; import io.github.robothy.sdwebui.sdk.models.SdWebuiOptions; import io.github.robothy.sdwebui.sdk.models.SystemInfo; import io.github.robothy.sdwebui.sdk.models.options.Txt2ImageOptions; import io.github.robothy.sdwebui.sdk.models.results.Txt2ImgResult; import io.github.robothy.sdwebui.sdk.utils.SdWebuiResponseUtils; import org.apache.hc.client5.http.classic.HttpClient; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.StringEntity; import java.io.IOException;
2,315
package io.github.robothy.sdwebui.sdk.services; public class DefaultTxt2ImageService implements Txt2Image { private static final String TXT2IMG_PATH = "/sdapi/v1/txt2img"; private final SdWebuiBeanContainer beanContainer; public DefaultTxt2ImageService(SdWebuiBeanContainer beanContainer) { this.beanContainer = beanContainer; } @Override
package io.github.robothy.sdwebui.sdk.services; public class DefaultTxt2ImageService implements Txt2Image { private static final String TXT2IMG_PATH = "/sdapi/v1/txt2img"; private final SdWebuiBeanContainer beanContainer; public DefaultTxt2ImageService(SdWebuiBeanContainer beanContainer) { this.beanContainer = beanContainer; } @Override
public Txt2ImgResult txt2Img(Txt2ImageOptions options) {
4
2023-10-10 14:55:42+00:00
4k
dadegrande99/HikeMap
app/src/main/java/com/usi/hikemap/ui/authentication/LoginFragment.java
[ { "identifier": "MainActivity", "path": "app/src/main/java/com/usi/hikemap/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n private ActivityMainBinding binding;\n\n private GoogleMap mMap;\n\n MeowBottomNavigation bottomNavigation;\n\n String userId;\n\n FusedLocationProviderClient fusedLocationProviderClient;\n FirebaseAuth fAuth;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n //userId = FirebaseAuth.getInstance().getCurrentUser().getUid();\n //fAuth = FirebaseAuth.getInstance();\n\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n\n Toolbar toolbar = findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n\n bottomNavigation = findViewById(R.id.bottomNavigation);\n bottomNavigation.show(2, true); // show go fragment first\n\n bottomNavigation.add(new MeowBottomNavigation.Model(1, R.drawable.chart));\n bottomNavigation.add(new MeowBottomNavigation.Model(2, R.drawable.icon_go));\n bottomNavigation.add(new MeowBottomNavigation.Model(3, R.drawable.icon_profile));\n\n meowBottomNavigation();\n\n //userId = FirebaseAuth.getInstance().getCurrentUser().getUid();\n\n replaceFragment(new GoFragment());\n //onMapReady(mMap);\n\n }\n\n\n\n private void meowBottomNavigation() {\n bottomNavigation.setOnClickMenuListener(model -> {\n switch (model.getId()) {\n case 1:\n replaceFragment(new StatisticsFragment());\n break;\n case 2:\n replaceFragment(new GoFragment());\n break;\n case 3:\n replaceFragment(new ProfileFragment());\n break;\n }\n return null;\n });\n }\n\n /**@Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n replaceFragment(new GoFragment());\n }\n }*/\n\n\n private void replaceFragment(Fragment fragment) {\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();\n fragmentTransaction.replace(R.id.frame_layout, fragment);\n fragmentTransaction.commit();\n }\n\n\n\n //@Override\n /**public void onMapReady(GoogleMap googleMap) {\n // Assign the GoogleMap instance to the local variable mMap\n mMap = googleMap;\n\n // Enable the location layer. Request permission if needed.\n if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)\n == PackageManager.PERMISSION_GRANTED) {\n // Enable the \"My Location\" layer on the map\n mMap.setMyLocationEnabled(true);\n fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);\n zoomToUserLocation();\n\n // Request location updates from the GPS provider\n LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);\n if (locationManager != null) {\n locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 10F, (LocationListener) this);\n }\n } else {\n // Request permission if it's not granted\n ActivityCompat.requestPermissions(this,\n new String[]{Manifest.permission.ACCESS_FINE_LOCATION},\n 1);\n }\n }\n\n private void zoomToUserLocation() {\n @SuppressLint(\"MissingPermission\") Task<Location> locationTask = fusedLocationProviderClient.getLastLocation();\n locationTask.addOnSuccessListener(new OnSuccessListener<Location>() {\n @Override\n public void onSuccess(Location location) {\n LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());\n mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));\n //mMap.addMarker(new MarkerOptions().position(latLng));\n }\n });\n }*/\n\n}" }, { "identifier": "AuthViewModel", "path": "app/src/main/java/com/usi/hikemap/ui/viewmodel/AuthViewModel.java", "snippet": "public class AuthViewModel extends AndroidViewModel {\n\n private MutableLiveData<AuthenticationResponse> mAuthenticationResponse;\n private final IAuthenticationRepository mAuthenticationRepository;\n\n public AuthViewModel(@NonNull Application application) {\n super(application);\n this.mAuthenticationRepository = new AuthenticationRepository(application);\n }\n\n public MutableLiveData<AuthenticationResponse> createUserWithEmail(User user) {\n mAuthenticationResponse = mAuthenticationRepository.createUserWithEmail(user);\n return mAuthenticationResponse;\n }\n\n public MutableLiveData<AuthenticationResponse> loginWithEmail(String email, String password) {\n mAuthenticationResponse = mAuthenticationRepository.loginWithEmail(email, password);\n return mAuthenticationResponse;\n }\n\n public MutableLiveData<AuthenticationResponse> createUserWithPhone(User user, PhoneAuthCredential credential) {\n mAuthenticationResponse = mAuthenticationRepository.createUserWithPhone(user, credential);\n return mAuthenticationResponse;\n }\n\n public MutableLiveData<AuthenticationResponse> createUserWithGoogle(GoogleSignInAccount account) {\n mAuthenticationResponse = mAuthenticationRepository.createUserWithGoogle(account);\n return mAuthenticationResponse;\n }\n\n}" }, { "identifier": "Constants", "path": "app/src/main/java/com/usi/hikemap/utils/Constants.java", "snippet": "public class Constants {\n\n public static final int RC_SIGN_IN = 100;\n public static String USER_COLLECTION = \"users\";\n public static String DEFAULT_WEB_CLIENT_ID = \"35606227968-7fthbhiudp0tnpn9tae31qaln3d605j2.apps.googleusercontent.com\";\n public static String FIREBASE_DATABASE_URL = \"https://hikemap-e9d2a-default-rtdb.firebaseio.com/\";\n public static String URL_LINK_EMAIL =\"https://hikemap-e9d2a.firebaseapp.com/__/auth/action?mode=verifyEmail&oobCode=fDaMeWEq62kAEyc39IeKW0mq3vOi0Pge-zGbszAXCZgAAAF9V0SOmg&apiKey=AIzaSyDqkEUl0euzeZog1uF4dorcp7z2aE-DXH8&lang=en\";\n\n\n}" } ]
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.fragment.NavHostFragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.usi.hikemap.MainActivity; import com.usi.hikemap.R; import com.usi.hikemap.databinding.FragmentLoginBinding; import com.usi.hikemap.ui.viewmodel.AuthViewModel; import com.usi.hikemap.utils.Constants;
2,029
package com.usi.hikemap.ui.authentication; public class LoginFragment extends Fragment { EditText mEmailEditText; EditText mPasswordEditText; Button mLoginButton; ImageView mGoogleButton, mReturnStartPage; private GoogleSignInClient mGoogleSignInClient; AuthViewModel mAuthViewModel; private final String TAG = "LoginFragment"; private FragmentLoginBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAuthViewModel = new ViewModelProvider(requireActivity()).get(AuthViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLoginBinding.inflate(inflater, container, false); View root = binding.getRoot(); mEmailEditText = root.findViewById(R.id.email_log_editText); mPasswordEditText = root.findViewById(R.id.password_log_editText); mLoginButton = root.findViewById(R.id.access_button); //*********************** mReturnStartPage = root.findViewById(R.id.return_to_startPage_from_login); mReturnStartPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.login_to_startpage); } }); //*********************** mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email, password; email = mEmailEditText.getText().toString().trim(); password = mPasswordEditText.getText().toString().trim(); if (TextUtils.isEmpty(email)) { mEmailEditText.setError("Email is required"); return; } if (TextUtils.isEmpty(password) || password.length() < 8) { mEmailEditText.setError("Password is required"); return; } mAuthViewModel.loginWithEmail(email, password).observe(getViewLifecycleOwner(), authenticationResponse -> { if (authenticationResponse != null) { if (authenticationResponse.isSuccess()) { Log.d(TAG, "onClick: Access to main Activity");
package com.usi.hikemap.ui.authentication; public class LoginFragment extends Fragment { EditText mEmailEditText; EditText mPasswordEditText; Button mLoginButton; ImageView mGoogleButton, mReturnStartPage; private GoogleSignInClient mGoogleSignInClient; AuthViewModel mAuthViewModel; private final String TAG = "LoginFragment"; private FragmentLoginBinding binding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAuthViewModel = new ViewModelProvider(requireActivity()).get(AuthViewModel.class); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLoginBinding.inflate(inflater, container, false); View root = binding.getRoot(); mEmailEditText = root.findViewById(R.id.email_log_editText); mPasswordEditText = root.findViewById(R.id.password_log_editText); mLoginButton = root.findViewById(R.id.access_button); //*********************** mReturnStartPage = root.findViewById(R.id.return_to_startPage_from_login); mReturnStartPage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.login_to_startpage); } }); //*********************** mLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email, password; email = mEmailEditText.getText().toString().trim(); password = mPasswordEditText.getText().toString().trim(); if (TextUtils.isEmpty(email)) { mEmailEditText.setError("Email is required"); return; } if (TextUtils.isEmpty(password) || password.length() < 8) { mEmailEditText.setError("Password is required"); return; } mAuthViewModel.loginWithEmail(email, password).observe(getViewLifecycleOwner(), authenticationResponse -> { if (authenticationResponse != null) { if (authenticationResponse.isSuccess()) { Log.d(TAG, "onClick: Access to main Activity");
Intent intent = new Intent(getActivity(), MainActivity.class);
0
2023-10-09 14:23:22+00:00
4k
xiaoymin/LlmInAction
llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/command/AddTxtCommand.java
[ { "identifier": "TxtChunk", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/compoents/TxtChunk.java", "snippet": "@Slf4j\n@Component\n@AllArgsConstructor\npublic class TxtChunk {\n\n public List<ChunkResult> chunk(String docId){\n String path=\"data/\"+docId+\".txt\";\n log.info(\"start chunk---> docId:{},path:{}\",docId,path);\n ClassPathResource classPathResource=new ClassPathResource(path);\n try {\n String txt=IoUtil.read(classPathResource.getInputStream(), StandardCharsets.UTF_8);\n //按固定字数分割,256\n String[] lines=StrUtil.split(txt,256);\n log.info(\"chunk size:{}\", ArrayUtil.length(lines));\n List<ChunkResult> results=new ArrayList<>();\n AtomicInteger atomicInteger=new AtomicInteger(0);\n for (String line:lines){\n ChunkResult chunkResult=new ChunkResult();\n chunkResult.setDocId(docId);\n chunkResult.setContent(line);\n chunkResult.setChunkId(atomicInteger.incrementAndGet());\n results.add(chunkResult);\n }\n return results;\n } catch (IOException e) {\n log.error(e.getMessage());\n }\n return new ArrayList<>();\n }\n\n}" }, { "identifier": "VectorStorage", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/compoents/VectorStorage.java", "snippet": "@Slf4j\n@Component\n@AllArgsConstructor\npublic class VectorStorage {\n\n final ElasticsearchRestTemplate elasticsearchRestTemplate;\n\n public String getCollectionName(){\n //演示效果使用,固定前缀+日期\n return \"llm_action_rag_\"+ DateUtil.format(Date.from(Instant.now()),\"yyyyMMdd\");\n }\n\n /**\n * 初始化向量数据库index\n * @param collectionName 名称\n * @param dim 维度\n */\n public boolean initCollection(String collectionName,int dim){\n log.info(\"collection:{}\", collectionName);\n // 查看向量索引是否存在,此方法为固定默认索引字段\n IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(collectionName));\n if (!indexOperations.exists()) {\n // 索引不存在,直接创建\n log.info(\"index not exists,create\");\n //创建es的结构,简化处理\n Document document = Document.from(this.elasticMapping(dim));\n // 创建\n indexOperations.create(new HashMap<>(), document);\n return true;\n }\n return true;\n }\n\n public void store(String collectionName,List<EmbeddingResult> embeddingResults){\n //保存向量\n log.info(\"save vector,collection:{},size:{}\",collectionName, CollectionUtil.size(embeddingResults));\n\n List<IndexQuery> results = new ArrayList<>();\n for (EmbeddingResult embeddingResult : embeddingResults) {\n ElasticVectorData ele = new ElasticVectorData();\n ele.setVector(embeddingResult.getEmbedding());\n ele.setChunkId(embeddingResult.getRequestId());\n ele.setContent(embeddingResult.getPrompt());\n results.add(new IndexQueryBuilder().withObject(ele).build());\n }\n // 构建数据包\n List<IndexedObjectInformation> bulkedResult = elasticsearchRestTemplate.bulkIndex(results, IndexCoordinates.of(collectionName));\n int size = CollectionUtil.size(bulkedResult);\n log.info(\"保存向量成功-size:{}\", size);\n }\n\n public String retrieval(String collectionName,double[] vector){\n // Build the script,查询向量\n Map<String, Object> params = new HashMap<>();\n params.put(\"query_vector\", vector);\n // 计算cos值+1,避免出现负数的情况,得到结果后,实际score值在减1再计算\n Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, \"cosineSimilarity(params.query_vector, 'vector')+1\", params);\n ScriptScoreQueryBuilder scriptScoreQueryBuilder = new ScriptScoreQueryBuilder(QueryBuilders.boolQuery(), script);\n // 构建请求\n NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()\n .withQuery(scriptScoreQueryBuilder)\n .withPageable(Pageable.ofSize(3)).build();\n SearchHits<ElasticVectorData> dataSearchHits = this.elasticsearchRestTemplate.search(nativeSearchQuery, ElasticVectorData.class, IndexCoordinates.of(collectionName));\n //log.info(\"检索成功,size:{}\", dataSearchHits.getTotalHits());\n List<SearchHit<ElasticVectorData>> data = dataSearchHits.getSearchHits();\n List<String> results = new LinkedList<>();\n for (SearchHit<ElasticVectorData> ele : data) {\n results.add(ele.getContent().getContent());\n }\n return CollectionUtil.join(results,\"\");\n }\n\n private Map<String, Object> elasticMapping(int dims) {\n Map<String, Object> properties = new HashMap<>();\n properties.put(\"_class\", MapUtil.builder(\"type\", \"keyword\").put(\"doc_values\", \"false\").put(\"index\", \"false\").build());\n properties.put(\"chunkId\", MapUtil.builder(\"type\", \"keyword\").build());\n properties.put(\"content\", MapUtil.builder(\"type\", \"keyword\").build());\n properties.put(\"docId\", MapUtil.builder(\"type\", \"keyword\").build());\n // 向量\n properties.put(\"vector\", MapUtil.builder(\"type\", \"dense_vector\").put(\"dims\", Objects.toString(dims)).build());\n Map<String, Object> root = new HashMap<>();\n root.put(\"properties\", properties);\n return root;\n }\n\n}" }, { "identifier": "ChunkResult", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/domain/llm/ChunkResult.java", "snippet": "@Data\npublic class ChunkResult {\n private String docId;\n private int chunkId;\n private String content;\n\n}" }, { "identifier": "EmbeddingResult", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/domain/llm/EmbeddingResult.java", "snippet": "@Getter\n@Setter\npublic class EmbeddingResult {\n\n /**\n * 原始文本内容\n */\n private String prompt;\n /**\n * embedding的处理结果,返回向量化表征的数组,数组长度为1024\n */\n private double[] embedding;\n /**\n * 用户在客户端请求时提交的任务编号或者平台生成的任务编号\n */\n private String requestId;\n /**\n * 智谱AI开放平台生成的任务订单号,调用请求结果接口时请使用此订单号\n */\n private String taskId;\n /**\n * 处理状态,PROCESSING(处理中),SUCCESS(成功),FAIL(失败)\n * 注:处理中状态需通过查询获取结果\n */\n private String taskStatus;\n}" }, { "identifier": "ZhipuAI", "path": "llm_chat_java_hello/src/main/java/com/github/xiaoymin/llm/llm/ZhipuAI.java", "snippet": "@Component\n@AllArgsConstructor\n@Slf4j\npublic class ZhipuAI {\n\n final LLmProperties lLmProperties;\n\n final Gson GSON=new Gson();\n\n public String getApiKey(){\n String apiKey= lLmProperties.getZpKey();\n if (StrUtil.isBlank(apiKey)){\n apiKey=System.getenv(\"CHAT2CMD_KEY_ZP\");\n }\n return apiKey;\n }\n\n public void chat(String prompt){\n try {\n OkHttpClient.Builder builder = new OkHttpClient.Builder()\n .connectTimeout(20000, TimeUnit.MILLISECONDS)\n .readTimeout(20000, TimeUnit.MILLISECONDS)\n .writeTimeout(20000, TimeUnit.MILLISECONDS)\n .addInterceptor(new ZhipuHeaderInterceptor(this.getApiKey()));\n OkHttpClient okHttpClient = builder.build();\n\n ZhipuChatCompletion zhipuChatCompletion=new ZhipuChatCompletion();\n zhipuChatCompletion.addPrompt(prompt);\n // 采样温度,控制输出的随机性,必须为正数\n // 值越大,会使输出更随机,更具创造性;值越小,输出会更加稳定或确定\n zhipuChatCompletion.setTemperature(0.7f);\n zhipuChatCompletion.setTop_p(0.7f);\n\n EventSource.Factory factory = EventSources.createFactory(okHttpClient);\n ObjectMapper mapper = new ObjectMapper();\n String requestBody = mapper.writeValueAsString(zhipuChatCompletion);\n Request request = new Request.Builder()\n .url(\"https://open.bigmodel.cn/api/paas/v3/model-api/chatglm_std/sse-invoke\")\n .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))\n .build();\n CountDownLatch countDownLatch=new CountDownLatch(1);\n // 创建事件,控制台输出\n EventSource eventSource = factory.newEventSource(request, new ConsoleEventSourceListener(countDownLatch));\n countDownLatch.await();\n\n } catch (Exception e) {\n log.error(\"llm-chat异常:{}\", e.getMessage());\n }\n }\n\n /**\n * 获取句子的向量\n * @param sentence 句子\n * @return 向量\n */\n public double[] sentence(String sentence){\n ChunkResult chunkResult=new ChunkResult();\n chunkResult.setContent(sentence);\n chunkResult.setChunkId(RandomUtil.randomInt());\n EmbeddingResult embeddingResult=this.embedding(chunkResult);\n return embeddingResult.getEmbedding();\n }\n\n /**\n * 批量\n * @param chunkResults 批量文本\n * @return 向量\n */\n public List<EmbeddingResult> embedding(List<ChunkResult> chunkResults){\n log.info(\"start embedding,size:{}\",CollectionUtil.size(chunkResults));\n if (CollectionUtil.isEmpty(chunkResults)){\n return new ArrayList<>();\n }\n List<EmbeddingResult> embeddingResults=new ArrayList<>();\n for (ChunkResult chunkResult:chunkResults){\n embeddingResults.add(this.embedding(chunkResult));\n }\n return embeddingResults;\n }\n\n public EmbeddingResult embedding(ChunkResult chunkResult){\n String apiKey= this.getApiKey();\n //log.info(\"zp-key:{}\",apiKey);\n OkHttpClient.Builder builder = new OkHttpClient.Builder()\n .connectTimeout(20000, TimeUnit.MILLISECONDS)\n .readTimeout(20000, TimeUnit.MILLISECONDS)\n .writeTimeout(20000, TimeUnit.MILLISECONDS)\n .addInterceptor(new ZhipuHeaderInterceptor(apiKey));\n OkHttpClient okHttpClient = builder.build();\n EmbeddingResult embedRequest=new EmbeddingResult();\n embedRequest.setPrompt(chunkResult.getContent());\n embedRequest.setRequestId(Objects.toString(chunkResult.getChunkId()));\n // 智谱embedding\n Request request = new Request.Builder()\n .url(\"https://open.bigmodel.cn/api/paas/v3/model-api/text_embedding/invoke\")\n .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), GSON.toJson(embedRequest)))\n .build();\n try {\n Response response= okHttpClient.newCall(request).execute();\n String result=response.body().string();\n ZhipuResult zhipuResult= GSON.fromJson(result, ZhipuResult.class);\n EmbeddingResult ret= zhipuResult.getData();\n ret.setPrompt(embedRequest.getPrompt());\n ret.setRequestId(embedRequest.getRequestId());\n return ret;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n }\n\n @AllArgsConstructor\n private static class ZhipuHeaderInterceptor implements Interceptor {\n\n final String apiKey;\n\n @NotNull\n @Override\n public Response intercept(@NotNull Chain chain) throws IOException {\n Request original = chain.request();\n String authorization=LLMUtils.gen(apiKey,60);\n //log.info(\"authorization:{}\",authorization);\n Request request = original.newBuilder()\n .header(Header.AUTHORIZATION.getValue(), authorization)\n .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())\n .method(original.method(), original.body())\n .build();\n return chain.proceed(request);\n }\n }\n}" } ]
import com.github.xiaoymin.llm.compoents.TxtChunk; import com.github.xiaoymin.llm.compoents.VectorStorage; import com.github.xiaoymin.llm.domain.llm.ChunkResult; import com.github.xiaoymin.llm.domain.llm.EmbeddingResult; import com.github.xiaoymin.llm.llm.ZhipuAI; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import java.util.List;
3,128
package com.github.xiaoymin.llm.command; /** * @author <a href="[email protected]">[email protected]</a> * 2023/10/06 12:50 * @since llm_chat_java_hello */ @Slf4j @AllArgsConstructor @ShellComponent public class AddTxtCommand { final TxtChunk txtChunk; final VectorStorage vectorStorage; final ZhipuAI zhipuAI; @ShellMethod(value = "add local txt data") public String add(String doc){ log.info("start add doc."); // 加载 List<ChunkResult> chunkResults= txtChunk.chunk(doc); // embedding
package com.github.xiaoymin.llm.command; /** * @author <a href="[email protected]">[email protected]</a> * 2023/10/06 12:50 * @since llm_chat_java_hello */ @Slf4j @AllArgsConstructor @ShellComponent public class AddTxtCommand { final TxtChunk txtChunk; final VectorStorage vectorStorage; final ZhipuAI zhipuAI; @ShellMethod(value = "add local txt data") public String add(String doc){ log.info("start add doc."); // 加载 List<ChunkResult> chunkResults= txtChunk.chunk(doc); // embedding
List<EmbeddingResult> embeddingResults=zhipuAI.embedding(chunkResults);
3
2023-10-10 23:25:33+00:00
4k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/config/Config.java
[ { "identifier": "Project", "path": "src/main/java/zju/cst/aces/api/Project.java", "snippet": "public interface Project {\n Project getParent();\n File getBasedir();\n /**\n * Get the project packaging type.\n */\n String getPackaging();\n String getGroupId();\n String getArtifactId();\n List<String> getCompileSourceRoots();\n Path getArtifactPath();\n Path getBuildPath();\n\n}" }, { "identifier": "Validator", "path": "src/main/java/zju/cst/aces/api/Validator.java", "snippet": "public interface Validator {\n\n boolean syntacticValidate(String code);\n boolean semanticValidate(String code, String className, Path outputPath, PromptInfo promptInfo);\n boolean runtimeValidate(String fullTestName);\n public boolean compile(String className, Path outputPath, PromptInfo promptInfo);\n public TestExecutionSummary execute(String fullTestName);\n}" }, { "identifier": "LoggerImpl", "path": "src/main/java/zju/cst/aces/api/impl/LoggerImpl.java", "snippet": "public class LoggerImpl implements zju.cst.aces.api.Logger {\n\n java.util.logging.Logger log;\n\n public LoggerImpl() {\n this.log = java.util.logging.Logger.getLogger(\"ChatUniTest\");\n Handler consoleHandler = new ConsoleHandler();\n consoleHandler.setLevel(Level.ALL);\n consoleHandler.setFormatter(new LogFormatter());\n this.log.addHandler(consoleHandler);\n this.log.setUseParentHandlers(false);\n }\n\n @Override\n public void info(String msg) {\n log.info(msg);\n }\n\n @Override\n public void warn(String msg) {\n log.warning(msg);\n }\n\n @Override\n public void error(String msg) {\n log.severe(msg);\n }\n\n @Override\n public void debug(String msg) {\n log.config(msg);\n }\n}" }, { "identifier": "Logger", "path": "src/main/java/zju/cst/aces/api/Logger.java", "snippet": "public interface Logger {\n\n void info(String msg);\n void warn(String msg);\n void error(String msg);\n void debug(String msg);\n}" }, { "identifier": "ValidatorImpl", "path": "src/main/java/zju/cst/aces/api/impl/ValidatorImpl.java", "snippet": "@Data\npublic class ValidatorImpl implements Validator {\n\n TestCompiler compiler;\n\n public ValidatorImpl(Path testOutputPath, Path compileOutputPath, Path targetPath, List<String> classpathElements) {\n this.compiler = new TestCompiler(testOutputPath, compileOutputPath, targetPath, classpathElements);\n }\n\n @Override\n public boolean syntacticValidate(String code) {\n try {\n StaticJavaParser.parse(code);\n return true;\n } catch (ParseProblemException e) {\n return false;\n }\n }\n\n @Override\n public boolean semanticValidate(String code, String className, Path outputPath, PromptInfo promptInfo) {\n compiler.setCode(code);\n return compiler.compileTest(className, outputPath, promptInfo);\n }\n\n @Override\n public boolean runtimeValidate(String fullTestName) {\n return compiler.executeTest(fullTestName).getTestsFailedCount() == 0;\n }\n\n @Override\n public boolean compile(String className, Path outputPath, PromptInfo promptInfo) {\n return compiler.compileTest(className, outputPath, promptInfo);\n }\n\n @Override\n public TestExecutionSummary execute(String fullTestName) {\n return compiler.executeTest(fullTestName);\n }\n}" } ]
import zju.cst.aces.api.Project; import com.github.javaparser.JavaParser; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Getter; import lombok.Setter; import okhttp3.OkHttpClient; import zju.cst.aces.api.Validator; import zju.cst.aces.api.impl.LoggerImpl; import zju.cst.aces.api.Logger; import zju.cst.aces.api.impl.ValidatorImpl; import java.io.File; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger;
1,828
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS; public boolean stopWhenSuccess; public boolean noExecution; public boolean enableMultithreading; public boolean enableRuleRepair; public boolean enableMerge; public boolean enableObfuscate; public String[] obfuscateGroupIds; public int maxThreads; public int classThreads; public int methodThreads; public int testNumber; public int maxRounds; public int maxPromptTokens; public int maxResponseTokens; public int minErrorTokens; public int sleepTime; public int dependencyDepth; public Model model; public Double temperature; public int topP; public int frequencyPenalty; public int presencePenalty; public Path testOutput; public Path tmpOutput; public Path compileOutputPath; public Path parseOutput; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy; public String hostname; public String port; public OkHttpClient client; public static AtomicInteger sharedInteger = new AtomicInteger(0); public static Map<String, Map<String, String>> classMapping; public Validator validator; public static class ConfigBuilder { public String date; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS = System.getProperty("os.name").toLowerCase(); public boolean stopWhenSuccess = true; public boolean noExecution = false; public boolean enableMultithreading = true; public boolean enableRuleRepair = true; public boolean enableMerge = true; public boolean enableObfuscate = false; public String[] obfuscateGroupIds; public int maxThreads = Runtime.getRuntime().availableProcessors() * 5; public int classThreads = (int) Math.ceil((double) this.maxThreads / 10); public int methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads); public int testNumber = 5; public int maxRounds = 5; public int maxPromptTokens = 2600; public int maxResponseTokens = 1024; public int minErrorTokens = 500; public int sleepTime = 0; public int dependencyDepth = 1; public Model model = Model.GPT_3_5_TURBO; public Double temperature = 0.5; public int topP = 1; public int frequencyPenalty = 0; public int presencePenalty = 0; public Path testOutput; public Path tmpOutput = Paths.get(System.getProperty("java.io.tmpdir"), "chatunitest-info"); public Path parseOutput; public Path compileOutputPath; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy = "null:-1"; public String hostname = "null"; public String port = "-1"; public OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .build(); public Validator validator; public ConfigBuilder(Project project) { this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss")).toString(); this.project = project;
package zju.cst.aces.api.config; @Getter @Setter public class Config { public String date; public Gson GSON; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS; public boolean stopWhenSuccess; public boolean noExecution; public boolean enableMultithreading; public boolean enableRuleRepair; public boolean enableMerge; public boolean enableObfuscate; public String[] obfuscateGroupIds; public int maxThreads; public int classThreads; public int methodThreads; public int testNumber; public int maxRounds; public int maxPromptTokens; public int maxResponseTokens; public int minErrorTokens; public int sleepTime; public int dependencyDepth; public Model model; public Double temperature; public int topP; public int frequencyPenalty; public int presencePenalty; public Path testOutput; public Path tmpOutput; public Path compileOutputPath; public Path parseOutput; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy; public String hostname; public String port; public OkHttpClient client; public static AtomicInteger sharedInteger = new AtomicInteger(0); public static Map<String, Map<String, String>> classMapping; public Validator validator; public static class ConfigBuilder { public String date; public Project project; public JavaParser parser; public JavaParserFacade parserFacade; public List<String> classPaths; public Path promptPath; public String url; public String[] apiKeys; public Logger log; public String OS = System.getProperty("os.name").toLowerCase(); public boolean stopWhenSuccess = true; public boolean noExecution = false; public boolean enableMultithreading = true; public boolean enableRuleRepair = true; public boolean enableMerge = true; public boolean enableObfuscate = false; public String[] obfuscateGroupIds; public int maxThreads = Runtime.getRuntime().availableProcessors() * 5; public int classThreads = (int) Math.ceil((double) this.maxThreads / 10); public int methodThreads = (int) Math.ceil((double) this.maxThreads / this.classThreads); public int testNumber = 5; public int maxRounds = 5; public int maxPromptTokens = 2600; public int maxResponseTokens = 1024; public int minErrorTokens = 500; public int sleepTime = 0; public int dependencyDepth = 1; public Model model = Model.GPT_3_5_TURBO; public Double temperature = 0.5; public int topP = 1; public int frequencyPenalty = 0; public int presencePenalty = 0; public Path testOutput; public Path tmpOutput = Paths.get(System.getProperty("java.io.tmpdir"), "chatunitest-info"); public Path parseOutput; public Path compileOutputPath; public Path errorOutput; public Path classNameMapPath; public Path historyPath; public Path examplePath; public Path symbolFramePath; public String proxy = "null:-1"; public String hostname = "null"; public String port = "-1"; public OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .build(); public Validator validator; public ConfigBuilder(Project project) { this.date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss")).toString(); this.project = project;
this.log = new LoggerImpl();
2
2023-10-14 07:15:10+00:00
4k
Nyayurn/Yutori-QQ
src/main/java/io/github/nyayurn/yutori/qq/listener/guild/role/DispatcherGuildRoleListener.java
[ { "identifier": "Bot", "path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Bot.java", "snippet": "@Data\npublic class Bot {\n /**\n * QQ 号\n */\n private String id;\n private ChannelApi channelApi;\n private GuildApi guildApi;\n private GuildMemberApi guildMemberApi;\n private GuildRoleApi guildRoleApi;\n private LoginApi loginApi;\n private MessageApi messageApi;\n private UserApi userApi;\n\n public Bot(String platform, String selfId, PropertiesEntity properties) {\n this.id = selfId;\n this.channelApi = new ChannelApi(platform, selfId, properties);\n this.guildApi = new GuildApi(platform, selfId, properties);\n this.guildMemberApi = new GuildMemberApi(platform, selfId, properties);\n this.guildRoleApi = new GuildRoleApi(platform, selfId, properties);\n this.loginApi = new LoginApi(properties);\n this.messageApi = new MessageApi(platform, selfId, properties);\n this.userApi = new UserApi(platform, selfId, properties);\n }\n}" }, { "identifier": "GuildRoleEvent", "path": "src/main/java/io/github/nyayurn/yutori/qq/event/guild/GuildRoleEvent.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\npublic class GuildRoleEvent extends Event {\n /**\n * 群组信息\n */\n protected Guild guild;\n\n /**\n * 角色信息\n */\n protected GuildRole role;\n\n public GuildRoleEvent(Integer id, Long timestamp, Guild guild, GuildRole role) {\n super(id, timestamp);\n this.guild = guild;\n this.role = role;\n }\n\n public static GuildRoleEvent parse(EventEntity event) {\n return new GuildRoleEvent(event.getId(), event.getTimestamp(), Guild.parse(event), GuildRole.parse(event));\n }\n}" }, { "identifier": "EventListenerContainer", "path": "src/main/java/io/github/nyayurn/yutori/qq/listener/EventListenerContainer.java", "snippet": "@Data\npublic class EventListenerContainer {\n public final List<GuildAddedListener> onGuildAddedListenerDelegate = new ArrayList<>();\n public final List<GuildUpdatedListener> onGuildUpdatedListenerDelegate = new ArrayList<>();\n public final List<GuildRemovedListener> onGuildRemovedListenerDelegate = new ArrayList<>();\n public final List<GuildRequestListener> onGuildRequestListenerDelegate = new ArrayList<>();\n\n public final List<GuildMemberAddedListener> onGuildMemberAddedListenerDelegate = new ArrayList<>();\n public final List<GuildMemberUpdatedListener> onGuildMemberUpdatedListenerDelegate = new ArrayList<>();\n public final List<GuildMemberRemovedListener> onGuildMemberRemovedListenerDelegate = new ArrayList<>();\n public final List<GuildMemberRequestListener> onGuildMemberRequestListenerDelegate = new ArrayList<>();\n\n public final List<GuildRoleCreatedListener> onGuildRoleCreatedListenerDelegate = new ArrayList<>();\n public final List<GuildRoleUpdatedListener> onGuildRoleUpdatedListenerDelegate = new ArrayList<>();\n public final List<GuildRoleDeletedListener> onGuildRoleDeletedListenerDelegate = new ArrayList<>();\n\n public final List<LoginAddedListener> onLoginAddedListenerDelegate = new ArrayList<>();\n public final List<LoginRemovedListener> onLoginRemovedListenerDelegate = new ArrayList<>();\n public final List<LoginUpdatedListener> onLoginUpdatedListenerDelegate = new ArrayList<>();\n\n public final List<MessageCreatedListener> onMessageCreatedListenerDelegate = new ArrayList<>();\n public final List<PrivateMessageCreatedListener> onPrivateMessageCreatedListenerDelegate = new ArrayList<>();\n public final List<GroupMessageCreatedListener> onGroupMessageCreatedListenerDelegate = new ArrayList<>();\n\n public final List<MessageDeletedListener> onMessageDeletedListenerDelegate = new ArrayList<>();\n public final List<PrivateMessageDeletedListener> onPrivateMessageDeletedListenerDelegate = new ArrayList<>();\n public final List<GroupMessageDeletedListener> onGroupMessageDeletedListenerDelegate = new ArrayList<>();\n\n public final List<FriendRequestListener> onFriendRequestListenerDelegate = new ArrayList<>();\n\n public void addOnGuildAddedListener(GuildAddedListener... listeners) {\n if (listeners != null) {\n onGuildAddedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildUpdatedListener(GuildUpdatedListener... listeners) {\n if (listeners != null) {\n onGuildUpdatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildRemovedListener(GuildRemovedListener... listeners) {\n if (listeners != null) {\n onGuildRemovedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildRequestListener(GuildRequestListener... listeners) {\n if (listeners != null) {\n onGuildRequestListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildMemberAddedListener(GuildMemberAddedListener... listeners) {\n if (listeners != null) {\n onGuildMemberAddedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildMemberUpdatedListener(GuildMemberUpdatedListener... listeners) {\n if (listeners != null) {\n onGuildMemberUpdatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildMemberRemovedListener(GuildMemberRemovedListener... listeners) {\n if (listeners != null) {\n onGuildMemberRemovedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildMemberRequestListener(GuildMemberRequestListener... listeners) {\n if (listeners != null) {\n onGuildMemberRequestListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildRoleCreatedListener(GuildRoleCreatedListener... listeners) {\n if (listeners != null) {\n onGuildRoleCreatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildRoleUpdatedListener(GuildRoleUpdatedListener... listeners) {\n if (listeners != null) {\n onGuildRoleUpdatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGuildRoleDeletedListener(GuildRoleDeletedListener... listeners) {\n if (listeners != null) {\n onGuildRoleDeletedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnLoginAddedListener(LoginAddedListener... listeners) {\n if (listeners != null) {\n onLoginAddedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnLoginRemovedListener(LoginRemovedListener... listeners) {\n if (listeners != null) {\n onLoginRemovedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnLoginUpdatedListener(LoginUpdatedListener... listeners) {\n if (listeners != null) {\n onLoginUpdatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnMessageCreatedListener(MessageCreatedListener... listeners) {\n if (listeners != null) {\n onMessageCreatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnPrivateMessageCreatedListener(PrivateMessageCreatedListener... listeners) {\n if (listeners != null) {\n onPrivateMessageCreatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGroupMessageCreatedListener(GroupMessageCreatedListener... listeners) {\n if (listeners != null) {\n onGroupMessageCreatedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnMessageDeletedListener(MessageDeletedListener... listeners) {\n if (listeners != null) {\n onMessageDeletedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnPrivateMessageDeletedListener(PrivateMessageDeletedListener... listeners) {\n if (listeners != null) {\n onPrivateMessageDeletedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnGroupMessageDeletedListener(GroupMessageDeletedListener... listeners) {\n if (listeners != null) {\n onGroupMessageDeletedListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void addOnFriendRequestListener(FriendRequestListener... listeners) {\n if (listeners != null) {\n onFriendRequestListenerDelegate.addAll(List.of(listeners));\n }\n }\n\n public void runOnGuildAddedListeners(Bot bot, GuildEvent event) {\n for (var listener : onGuildAddedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildUpdatedListeners(Bot bot, GuildEvent event) {\n for (var listener : onGuildUpdatedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildRemovedListeners(Bot bot, GuildEvent event) {\n for (var listener : onGuildRemovedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildRequestListeners(Bot bot, GuildEvent event) {\n for (var listener : onGuildRequestListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildMemberAddedListeners(Bot bot, GuildMemberEvent event) {\n for (var listener : onGuildMemberAddedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildMemberUpdatedListeners(Bot bot, GuildMemberEvent event) {\n for (var listener : onGuildMemberUpdatedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildMemberRemovedListeners(Bot bot, GuildMemberEvent event) {\n for (var listener : onGuildMemberRemovedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildMemberRequestListeners(Bot bot, GuildMemberEvent event) {\n for (var listener : onGuildMemberRequestListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildRoleCreatedListeners(Bot bot, GuildRoleEvent event) {\n for (var listener : onGuildRoleCreatedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildRoleUpdatedListeners(Bot bot, GuildRoleEvent event) {\n for (var listener : onGuildRoleUpdatedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnGuildRoleDeletedListeners(Bot bot, GuildRoleEvent event) {\n for (var listener : onGuildRoleDeletedListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n\n public void runOnLoginAddedListeners(Bot bot) {\n for (var listener : onLoginAddedListenerDelegate) {\n listener.onEvent(bot);\n }\n }\n\n public void runOnLoginRemovedListeners(Bot bot) {\n for (var listener : onLoginRemovedListenerDelegate) {\n listener.onEvent(bot);\n }\n }\n\n public void runOnLoginUpdatedListeners(Bot bot) {\n for (var listener : onLoginUpdatedListenerDelegate) {\n listener.onEvent(bot);\n }\n }\n\n public void runOnMessageCreatedListeners(Bot bot, MessageEvent event, String msg) {\n for (var listener : onMessageCreatedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnPrivateMessageCreatedListeners(Bot bot, PrivateMessageEvent event, String msg) {\n for (var listener : onPrivateMessageCreatedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnGroupMessageCreatedListeners(Bot bot, GroupMessageEvent event, String msg) {\n for (var listener : onGroupMessageCreatedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnMessageDeletedListeners(Bot bot, MessageEvent event, String msg) {\n for (var listener : onMessageDeletedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnPrivateMessageDeletedListeners(Bot bot, PrivateMessageEvent event, String msg) {\n for (var listener : onPrivateMessageDeletedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnGroupMessageDeletedListeners(Bot bot, GroupMessageEvent event, String msg) {\n for (var listener : onGroupMessageDeletedListenerDelegate) {\n listener.onEvent(bot, event, msg);\n }\n }\n\n public void runOnFriendRequestListeners(Bot bot, FriendRequestEvent event) {\n for (var listener : onFriendRequestListenerDelegate) {\n listener.onEvent(bot, event);\n }\n }\n}" } ]
import io.github.nyayurn.yutori.ListenerContainer; import io.github.nyayurn.yutori.entity.EventEntity; import io.github.nyayurn.yutori.entity.PropertiesEntity; import io.github.nyayurn.yutori.event.GuildRoleEvents; import io.github.nyayurn.yutori.qq.entity.event.Bot; import io.github.nyayurn.yutori.qq.event.guild.GuildRoleEvent; import io.github.nyayurn.yutori.qq.listener.EventListenerContainer; import lombok.extern.slf4j.Slf4j;
3,298
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.listener.guild.role; /** * @author Yurn */ @Slf4j public class DispatcherGuildRoleListener { private final PropertiesEntity properties;
/* Copyright (c) 2023 Yurn yutori-qq is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ package io.github.nyayurn.yutori.qq.listener.guild.role; /** * @author Yurn */ @Slf4j public class DispatcherGuildRoleListener { private final PropertiesEntity properties;
private final EventListenerContainer listenerContainer;
2
2023-10-12 09:58:07+00:00
4k
villainwtf/weave
src/main/java/wtf/villain/weave/builder/WeaveInstanceBuilder.java
[ { "identifier": "Weave", "path": "src/main/java/wtf/villain/weave/Weave.java", "snippet": "public sealed interface Weave permits Weave.Impl {\n\n @NotNull\n static WeaveInstanceBuilder builder() {\n return new WeaveInstanceBuilder();\n }\n\n /**\n * Gets the underlying Retrofit client.\n *\n * @return the client\n */\n @NotNull\n TolgeeClient client();\n\n /**\n * Gets the underlying storage instance.\n * This is where all the supported languages and translations are cached.\n *\n * @return the storage instance\n */\n @NotNull\n Storage storage();\n\n /**\n * Refreshes the cache in the background.\n *\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n default CompletableFuture<Void> refresh() {\n return storage().refresh(client());\n }\n\n /**\n * Refreshes the cache for the given project in the background.\n *\n * @param projectId the ID of the project to refresh\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n default CompletableFuture<Project> refreshProject(int projectId) {\n return storage().refreshProject(client(), projectId);\n }\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project\n * @return the project\n */\n @NotNull\n default Project project(int id) {\n return storage().ensureProject(id);\n }\n\n /**\n * Closes the underlying client.\n */\n void dispose();\n\n record Impl(@NotNull TolgeeClient client,\n @NotNull Runnable clientShutdown,\n @NotNull Storage storage) implements Weave {\n @Override\n public void dispose() {\n clientShutdown.run();\n }\n }\n\n\n}" }, { "identifier": "TolgeeClient", "path": "src/main/java/wtf/villain/weave/client/TolgeeClient.java", "snippet": "public interface TolgeeClient {\n\n @NotNull\n @GET(\"/v2/projects/{id}/languages?size=2000\")\n Call<LanguagesResponse> getLanguages(@Path(\"id\") int id);\n\n @NotNull\n @GET(\"/v2/projects/{id}/translations/{language}?structureDelimiter\")\n Call<Map<String, Map<String, String>>> getTranslations(@Path(\"id\") int id, @Path(\"language\") String language);\n\n /**\n * Queries the list of supported languages for the given project.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @return a future that completes with the list of supported languages\n */\n @NotNull\n default CompletableFuture<List<LanguagesResponse.Language>> querySupportedLanguages(@NotNull TolgeeClient client, int projectId) {\n CompletableFuture<List<LanguagesResponse.Language>> future = new CompletableFuture<>();\n\n client.getLanguages(projectId).enqueue(new Callback<>() {\n @Override\n public void onResponse(@NotNull Call<LanguagesResponse> call, @NotNull Response<LanguagesResponse> response) {\n if (!response.isSuccessful()) {\n future.completeExceptionally(new RuntimeException(\"Unsuccessful request, status code is \" + response.code()));\n return;\n }\n\n LanguagesResponse data = response.body();\n\n if (data == null) {\n future.completeExceptionally(new RuntimeException(\"Invalid response body received\"));\n return;\n }\n\n future.complete(data.embedded().languages());\n }\n\n @Override\n public void onFailure(@NotNull Call<LanguagesResponse> call, @NotNull Throwable throwable) {\n future.completeExceptionally(new RuntimeException(\"Request failed\", throwable));\n }\n });\n\n return future;\n }\n\n /**\n * Queries the translations for the given project and language.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @param language the language\n * @return a future that completes with the translations\n */\n @NotNull\n default CompletableFuture<Map<String, Map<String, String>>> queryTranslations(@NotNull TolgeeClient client, int projectId, @NotNull String language) {\n CompletableFuture<Map<String, Map<String, String>>> future = new CompletableFuture<>();\n\n client.getTranslations(projectId, language).enqueue(new Callback<>() {\n @Override\n public void onResponse(@NotNull Call<Map<String, Map<String, String>>> call, @NotNull Response<Map<String, Map<String, String>>> response) {\n if (!response.isSuccessful()) {\n future.completeExceptionally(new RuntimeException(\"Unsuccessful request, status code is \" + response.code()));\n return;\n }\n\n Map<String, Map<String, String>> data = response.body();\n\n if (data == null) {\n future.completeExceptionally(new RuntimeException(\"Invalid response body received\"));\n return;\n }\n\n future.complete(data);\n }\n\n @Override\n public void onFailure(@NotNull Call<Map<String, Map<String, String>>> call, @NotNull Throwable throwable) {\n future.completeExceptionally(new RuntimeException(\"Request failed\", throwable));\n }\n });\n\n return future;\n }\n\n}" }, { "identifier": "Storage", "path": "src/main/java/wtf/villain/weave/storage/Storage.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic final class Storage {\n\n private final List<Integer> projectIds;\n private final List<PostProcessor> postProcessors;\n private final Map<Integer, Project> projects = new HashMap<>();\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project to get\n * @return the project with the given ID\n * @throws IllegalArgumentException if no such project exists\n */\n @NotNull\n public Project ensureProject(int id) {\n Project project = project(id);\n\n if (project == null) {\n throw new IllegalArgumentException(\"No project with ID \" + id);\n }\n\n return project;\n }\n\n /**\n * Gets the project with the given ID.\n *\n * @param id the ID of the project to get\n * @return the project with the given ID, or {@code null} if no such project exists\n */\n @Nullable\n public Project project(int id) {\n return projects.get(id);\n }\n\n /**\n * Refreshes the cache in the background.\n *\n * @param client the Tolgee client\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n public CompletableFuture<Void> refresh(@NotNull TolgeeClient client) {\n List<CompletableFuture<Void>> futures = projectIds.stream()\n .map(projectId -> refreshProject(client, projectId)\n .thenAccept(project -> projects.put(projectId, project)))\n .toList();\n\n return CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new));\n }\n\n /**\n * Refreshes the cache of the given project in the background.\n *\n * @param client the Tolgee client\n * @param projectId the project ID\n * @return a future that completes when the cache is refreshed\n */\n @NotNull\n public CompletableFuture<Project> refreshProject(@NotNull TolgeeClient client, int projectId) {\n CompletableFuture<Project> future = new CompletableFuture<>();\n\n int oldProjectVersion = Optional.ofNullable(projects.get(projectId))\n .map(Project::version)\n .orElse(0);\n\n WeaveProcessor processor = WeaveProcessor.of(postProcessors.toArray(PostProcessor[]::new));\n\n CompletableFuture<List<LanguagesResponse.Language>> languagesFuture = client.querySupportedLanguages(client, projectId);\n languagesFuture.whenComplete((languages, throwable) -> {\n if (throwable != null) {\n future.completeExceptionally(throwable);\n return;\n }\n\n if (languages.isEmpty()) {\n // If there are no languages, there won't be any translations either.\n future.complete(new Project(projectId, Map.of(), Map.of(), oldProjectVersion + 1));\n return;\n }\n\n Map<String, Map<String, Translation>> translations = new HashMap<>();\n\n List<CompletableFuture<Void>> languageFutures = languages.stream()\n .map(language -> client.queryTranslations(client, projectId, language.tag())\n .thenAccept(map -> {\n Map<String, String> keyToValue = map.get(language.tag());\n\n if (keyToValue == null) {\n // This should never happen since we're querying the translations for the given language.\n throw new IllegalStateException(\"No translations for language \" + language.tag());\n }\n\n Map<String, Translation> translationMap = new HashMap<>();\n\n keyToValue.forEach((key, value) -> {\n if (value == null) {\n // The value can be null if this key is not translated in the given language.\n // Example: \"en\" has \"hello\" -> \"Hello World!\", but \"de\" doesn't have this key translated yet.\n return;\n }\n\n // We iterate through each (translation key -> text) pair and add it to the map.\n translationMap.put(key, new Translation(value, processor));\n });\n\n translations.put(language.tag(), translationMap);\n }))\n .toList();\n\n CompletableFuture.allOf(languageFutures.toArray(CompletableFuture[]::new))\n .whenComplete((unused, throwable1) -> {\n if (throwable1 != null) {\n future.completeExceptionally(throwable1);\n return;\n }\n\n future.complete(new Project(\n projectId,\n languages.stream().collect(HashMap::new, (map, language) -> map.put(language.tag(), Language.findOrCreate(language.tag(), language.name())), HashMap::putAll),\n translations,\n oldProjectVersion + 1));\n });\n });\n\n return future;\n }\n\n}" }, { "identifier": "PostProcessor", "path": "src/main/java/wtf/villain/weave/translation/process/PostProcessor.java", "snippet": "@FunctionalInterface\npublic interface PostProcessor extends Function<Text, String> {\n\n /**\n * Returns a post-processor that returns its input unchanged.\n *\n * @return a post-processor that returns its input unchanged\n */\n @NotNull\n static PostProcessor identity() {\n return Text::text;\n }\n\n}" }, { "identifier": "Ensure", "path": "src/main/java/wtf/villain/weave/util/Ensure.java", "snippet": "public interface Ensure {\n\n /**\n * Checks that the specified object reference is not {@code null}.\n *\n * @param object the object reference to check for nullity\n * @param key the key to use in the exception message\n * @throws IllegalArgumentException if {@code object} is {@code null}\n */\n @Contract(\"null, _ -> fail\")\n static void argumentIsSet(@Nullable Object object, @NotNull String key) {\n that(object != null, key + \" must be set\");\n }\n\n /**\n * Checks that the given condition is true.\n *\n * @param condition the condition to check\n * @param message the message to use in the exception\n * @throws IllegalArgumentException if {@code condition} is {@code false}\n */\n static void that(boolean condition, @NotNull String message) {\n if (!condition) {\n throw new IllegalArgumentException(message);\n }\n }\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import wtf.villain.weave.Weave; import wtf.villain.weave.client.TolgeeClient; import wtf.villain.weave.storage.Storage; import wtf.villain.weave.translation.process.PostProcessor; import wtf.villain.weave.util.Ensure; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture;
2,913
package wtf.villain.weave.builder; public final class WeaveInstanceBuilder { @Nullable private String apiKey; @Nullable private String endpoint; @NotNull private final List<Integer> projectIds = new ArrayList<>(); @NotNull private Duration connectTimeout = Duration.ofSeconds(30); @NotNull private Duration readTimeout = Duration.ofSeconds(30); @NotNull private Duration writeTimeout = Duration.ofSeconds(30); @NotNull
package wtf.villain.weave.builder; public final class WeaveInstanceBuilder { @Nullable private String apiKey; @Nullable private String endpoint; @NotNull private final List<Integer> projectIds = new ArrayList<>(); @NotNull private Duration connectTimeout = Duration.ofSeconds(30); @NotNull private Duration readTimeout = Duration.ofSeconds(30); @NotNull private Duration writeTimeout = Duration.ofSeconds(30); @NotNull
private final List<PostProcessor> processors = new ArrayList<>();
3
2023-10-09 13:46:52+00:00
4k
jmdevall/opencodeplan
src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/relfinders/OverridesRelFinder.java
[ { "identifier": "Util", "path": "src/main/java/jmdevall/opencodeplan/adapter/out/javaparser/Util.java", "snippet": "public class Util {\n\n\tpublic static LineColPos toDomainPosition( com.github.javaparser.Position position) {\n\t\treturn LineColPos.builder()\n\t\t.line(position.line)\n\t\t.column(position.column)\n\t\t.build();\n\t}\n\t\n\tpublic static NodeId toNodeId(com.github.javaparser.ast.Node node) {\n\t\t\n\t\tCompilationUnit compilationUnit = getCompilationUnit(node);\n\t\tString filename = getFileNameOfCompilationUnit(compilationUnit);\n\n\t\tOptional<Position> begin = node.getBegin();\n\t\tif(begin.isEmpty()) {\n\t\t\tSystem.out.println(\"foo\");\n\t\t}\n\t\tLineColRange absoluteNode=LineColRange.builder()\n\t\t\t\t.begin(toDomainPosition(begin.get()))\n\t\t\t\t.end(toDomainPosition(node.getEnd().get()))\n\t\t\t\t.build();\n\n\t\treturn NodeId.builder()\n\t\t\t.file(filename)\n\t\t\t.range(absoluteNode)\n\t\t\t.build();\n\t}\n\t\n\t//---------------------\n\t\n\t public static CompilationUnit getCompilationUnit(Node node) {\n\t\t\n Node currentNode = node;\n while (!(currentNode instanceof CompilationUnit)) {\n currentNode = currentNode.getParentNode().orElse(null);\n }\n return (CompilationUnit) currentNode;\n\t}\n\t\n\t\n\n\n\tpublic static String getPackageDeclarationOrEmptyString(CompilationUnit compilationUnit) {\n\t\tOptional<PackageDeclaration> packageDeclaration=compilationUnit.getPackageDeclaration();\n\t\t\n\t\tif (packageDeclaration.isPresent()) {\n\t\t return packageDeclaration.get().getNameAsString();\n\t\t}\n\t\telse {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\n\tpublic static void getTypeDeclaration(com.github.javaparser.ast.Node node) {\n\t\tSymbolResolver symbolResolver = node.getSymbolResolver();\n\t\n\t\ttry {\n\t\t\tResolvedReferenceTypeDeclaration foo;\n\t\t\tfoo = symbolResolver.toTypeDeclaration(node);\n\t\t\t\n//\t\t\tOptional<com.github.javaparser.ast.Node> otronode=foo.containerType().get().toAst();\n//\t\t\tif(otronode.isPresent()) {\n//\t\t\t\tSystem.out.println(\"foo \"+otronode.get());\n//\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\t// TODO Auto-generated catch block\n\t\t\t//e.printStackTrace();\n\t\t}\n\t\t\n\t}\n\n\tpublic static String getPublicTypeOfCompilationUnit(CompilationUnit cu) {\n\t\tList<TypeDeclaration<?>> types = cu.getTypes();\n\n\t\tfor (TypeDeclaration<?> type : types) {\n\t\t if (type.isPublic()) {\n\t\t return type.getNameAsString();\n\t\t }\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic static String getFileNameOfCompilationUnit(CompilationUnit compilationUnit) {\n\t\t\n\t\tString packageDeclaration = getPackageDeclarationOrEmptyString(compilationUnit);\n\t\tString publicType = getPublicTypeOfCompilationUnit(compilationUnit);\n\n\n\t\tif(packageDeclaration.isEmpty()) {\n\t\t\treturn String.format(\".%s\",publicType).replace(\".\", File.separator) + \".java\";\n\t\t}\n\t\treturn String.format(\".%s.%s\",packageDeclaration,publicType).replace(\".\", File.separator) + \".java\";\n\t\t\n\t}\n\n}" }, { "identifier": "DependencyLabel", "path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/DependencyLabel.java", "snippet": "public enum DependencyLabel{\n \n PARENT_OF,\n CHILD_OF,\n\n BASE_CLASS_OF,\n DERIVED_CLASS_OF,\n\n IMPORTS,\n IMPORTED_BY,\n\n USES,\n USED_BY,\n\n OVERRIDES,\n OVERRIDEN_BY,\n\n INSTANTIATES,\n INSTANTIATED_BY,\n\n CALLS,\n CALLED_BY,\n\n CONSTRUCTS,\n CONSTRUCTED_BY\n\n}" }, { "identifier": "DependencyRelation", "path": "src/main/java/jmdevall/opencodeplan/domain/dependencygraph/DependencyRelation.java", "snippet": "@Builder\n@Getter\npublic class DependencyRelation {\n\tNodeId origin;\n\tNodeId destiny;\n\tDependencyLabel label;\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Rel(origin=\" + origin + \", destiny=\" + destiny + \", label=\" + label + \")\";\n\t}\n}" } ]
import java.util.Arrays; import java.util.List; import java.util.Optional; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.body.CallableDeclaration.Signature; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.SimpleName; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import com.github.javaparser.resolution.SymbolResolver; import com.github.javaparser.resolution.UnsolvedSymbolException; import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration; import com.github.javaparser.resolution.types.ResolvedReferenceType; import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade; import jmdevall.opencodeplan.adapter.out.javaparser.Util; import jmdevall.opencodeplan.domain.dependencygraph.DependencyLabel; import jmdevall.opencodeplan.domain.dependencygraph.DependencyRelation; import lombok.extern.slf4j.Slf4j;
2,034
package jmdevall.opencodeplan.adapter.out.javaparser.relfinders; /** * Find field use relations (Uses and UsedBy) between a statement and the declaration of a field it uses. */ @Slf4j public class OverridesRelFinder extends VoidVisitorAdapter<List<DependencyRelation>>{ public OverridesRelFinder() { super(); } /* public SymbolResolver getSymbolResolver() { return findCompilationUnit().map(cu -> { if (cu.containsData(SYMBOL_RESOLVER_KEY)) { return cu.getData(SYMBOL_RESOLVER_KEY); } throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit")); } */ private Optional<ResolvedMethodDeclaration> findMethod(ResolvedReferenceType type, String methodName,String descriptor){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { try { System.out.println("qualified signature="+method.getQualifiedSignature()); System.out.println("signature="+method.getSignature()); System.out.println("methodName="+methodName); System.out.println("methodDescriptor="+descriptor); System.out.println("method.getName()"+method.getName()); System.out.println("method.toDescriptor()"+method.toDescriptor()); if(method.getName().equals(methodName) && method.toDescriptor().equals(descriptor)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); } } return Optional.empty(); } private Optional<ResolvedMethodDeclaration> findMethodByResolvedMethodDeclaration(ResolvedReferenceType type, ResolvedMethodDeclaration resolvedMethodImp){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { if(method.getSignature().equals(resolvedMethodImp.getSignature())){ return Optional.of(method); } /*try { String signature2 = method.getSignature(); if(method.getName().equals(methodName) && signature2.equals(signature)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); }*/ } return Optional.empty(); } private Optional<Node> tryResolveMethodDeclaration(MethodDeclaration m){ try { ResolvedMethodDeclaration resolved=m.resolve(); log.debug("descriptor="+resolved.toDescriptor()); List<ResolvedReferenceType> ancestors=resolved.declaringType().getAllAncestors(); //resolved.declaringType().getA getAllAncestors(); for(ResolvedReferenceType ancestor:ancestors) { log.debug("searching method "+m.toDescriptor()+" in ancestestor "+ ancestor.getQualifiedName()); //Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethod(ancestor,m.getName().toString(),m.toDescriptor()); Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethodByResolvedMethodDeclaration(ancestor,resolved); if(metodoEnPadre.isPresent()) { return metodoEnPadre.get().toAst(); } } } catch (UnsolvedSymbolException e) { return Optional.empty(); } return Optional.empty(); } @Override public void visit(MethodDeclaration n, List<DependencyRelation> rels) { super.visit(n, rels); Optional<Node> methodDeclaration=tryResolveMethodDeclaration(n); if(methodDeclaration.isPresent()) { DependencyRelation childToParent=DependencyRelation.builder() .label(DependencyLabel.OVERRIDES)
package jmdevall.opencodeplan.adapter.out.javaparser.relfinders; /** * Find field use relations (Uses and UsedBy) between a statement and the declaration of a field it uses. */ @Slf4j public class OverridesRelFinder extends VoidVisitorAdapter<List<DependencyRelation>>{ public OverridesRelFinder() { super(); } /* public SymbolResolver getSymbolResolver() { return findCompilationUnit().map(cu -> { if (cu.containsData(SYMBOL_RESOLVER_KEY)) { return cu.getData(SYMBOL_RESOLVER_KEY); } throw new IllegalStateException("Symbol resolution not configured: to configure consider setting a SymbolResolver in the ParserConfiguration"); }).orElseThrow(() -> new IllegalStateException("The node is not inserted in a CompilationUnit")); } */ private Optional<ResolvedMethodDeclaration> findMethod(ResolvedReferenceType type, String methodName,String descriptor){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { try { System.out.println("qualified signature="+method.getQualifiedSignature()); System.out.println("signature="+method.getSignature()); System.out.println("methodName="+methodName); System.out.println("methodDescriptor="+descriptor); System.out.println("method.getName()"+method.getName()); System.out.println("method.toDescriptor()"+method.toDescriptor()); if(method.getName().equals(methodName) && method.toDescriptor().equals(descriptor)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); } } return Optional.empty(); } private Optional<ResolvedMethodDeclaration> findMethodByResolvedMethodDeclaration(ResolvedReferenceType type, ResolvedMethodDeclaration resolvedMethodImp){ List<ResolvedMethodDeclaration> methods=type.getAllMethodsVisibleToInheritors(); for(ResolvedMethodDeclaration method:methods) { if(method.getSignature().equals(resolvedMethodImp.getSignature())){ return Optional.of(method); } /*try { String signature2 = method.getSignature(); if(method.getName().equals(methodName) && signature2.equals(signature)) { return Optional.of(method); } } catch (Exception e) { //TODO: en ciertos casos salta excepción no se por que return Optional.empty(); }*/ } return Optional.empty(); } private Optional<Node> tryResolveMethodDeclaration(MethodDeclaration m){ try { ResolvedMethodDeclaration resolved=m.resolve(); log.debug("descriptor="+resolved.toDescriptor()); List<ResolvedReferenceType> ancestors=resolved.declaringType().getAllAncestors(); //resolved.declaringType().getA getAllAncestors(); for(ResolvedReferenceType ancestor:ancestors) { log.debug("searching method "+m.toDescriptor()+" in ancestestor "+ ancestor.getQualifiedName()); //Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethod(ancestor,m.getName().toString(),m.toDescriptor()); Optional<ResolvedMethodDeclaration> metodoEnPadre=findMethodByResolvedMethodDeclaration(ancestor,resolved); if(metodoEnPadre.isPresent()) { return metodoEnPadre.get().toAst(); } } } catch (UnsolvedSymbolException e) { return Optional.empty(); } return Optional.empty(); } @Override public void visit(MethodDeclaration n, List<DependencyRelation> rels) { super.visit(n, rels); Optional<Node> methodDeclaration=tryResolveMethodDeclaration(n); if(methodDeclaration.isPresent()) { DependencyRelation childToParent=DependencyRelation.builder() .label(DependencyLabel.OVERRIDES)
.origin(Util.toNodeId(n))
0
2023-10-14 18:27:18+00:00
4k
eahau/douyin-openapi
generator/src/main/java/com/github/eahau/openapi/douyin/generator/Main.java
[ { "identifier": "DouYinOpenDocApi", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java", "snippet": "public interface DouYinOpenDocApi {\n\n @RequestLine(\"GET {path}?__loader=\" + Misc.DOC_LANGUAGE + \"/$\")\n DocResponse docs(@Param(\"path\") String path);\n\n @Getter\n @ToString\n @Setter\n class DocResponse {\n\n /**\n * content 类型,据观察 2=html.\n */\n private int type;\n\n private String title;\n\n private String keywords;\n\n private String description;\n\n private String content;\n\n private boolean isShowUpdateTime;\n\n private String updateTime;\n\n private String arcositeId;\n\n public String path;\n\n public boolean isJson() {\n return type == 1;\n }\n\n public boolean isMarkdownHeadHtmlBody() {\n return type == 2;\n }\n\n public GeneratorContent toGeneratorContext() {\n if (isJson()) {\n final ApiListResponse apiListResponse = ApiListResponse.fromJson(getContent());\n\n final String markdown = new JsonDocParser(apiListResponse.getOps()).toMarkdown();\n setContent(markdown);\n\n// return new MarkdownParser(this).parse();\n }\n\n // isMarkdownHeadHtmlBody\n return new HtmlParser(this).parse();\n }\n\n }\n\n @RequestLine(\"GET /docs_v2/directory\")\n DocsResponse allDocs();\n\n @Getter\n class DocsResponse {\n private int error;\n private List<Data> data;\n }\n\n @Getter\n class Data {\n\n private int PositionOrder;\n private String Title;\n private int Type;\n private String NodeId;\n private int Online;\n private String Path;\n private List<Children> Children;\n private String ParentNodeId;\n\n }\n\n @Getter\n class Children {\n\n private String Brief;\n private String Keywords;\n private int EditorType;\n private int isShowUpdateTime;\n private int PositionOrder;\n private String Title;\n private int Type;\n private String NodeId;\n private int Online;\n private String Path;\n private List<Children> Children;\n private String ParentNodeId;\n\n public String docPath() {\n return Misc.DOC_URI + getPath();\n }\n\n public String docUrl() {\n return Misc.DOC_BASE_URL + docPath();\n }\n\n public List<Children> flatChildren() {\n final List<Children> children = Children;\n\n if (CollectionUtils.isEmpty(children)) {\n return Collections.emptyList();\n }\n\n final List<Children> list = Lists.newLinkedList();\n\n for (final DouYinOpenDocApi.Children child : children) {\n if (CollectionUtils.isEmpty(child.getChildren())) {\n list.add(child);\n } else {\n list.addAll(child.flatChildren());\n }\n }\n\n return list;\n }\n }\n\n}" }, { "identifier": "Children", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java", "snippet": "@Getter\nclass Children {\n\n private String Brief;\n private String Keywords;\n private int EditorType;\n private int isShowUpdateTime;\n private int PositionOrder;\n private String Title;\n private int Type;\n private String NodeId;\n private int Online;\n private String Path;\n private List<Children> Children;\n private String ParentNodeId;\n\n public String docPath() {\n return Misc.DOC_URI + getPath();\n }\n\n public String docUrl() {\n return Misc.DOC_BASE_URL + docPath();\n }\n\n public List<Children> flatChildren() {\n final List<Children> children = Children;\n\n if (CollectionUtils.isEmpty(children)) {\n return Collections.emptyList();\n }\n\n final List<Children> list = Lists.newLinkedList();\n\n for (final DouYinOpenDocApi.Children child : children) {\n if (CollectionUtils.isEmpty(child.getChildren())) {\n list.add(child);\n } else {\n list.addAll(child.flatChildren());\n }\n }\n\n return list;\n }\n}" }, { "identifier": "Data", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java", "snippet": "@Getter\nclass Data {\n\n private int PositionOrder;\n private String Title;\n private int Type;\n private String NodeId;\n private int Online;\n private String Path;\n private List<Children> Children;\n private String ParentNodeId;\n\n}" }, { "identifier": "DocsResponse", "path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/api/DouYinOpenDocApi.java", "snippet": "@Getter\nclass DocsResponse {\n private int error;\n private List<Data> data;\n}" } ]
import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.Children; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.Data; import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.DocsResponse; import com.google.common.base.Stopwatch; import com.google.common.collect.Lists; import feign.Feign; import feign.Logger.Level; import feign.gson.GsonDecoder; import feign.slf4j.Slf4jLogger; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
1,847
/* * Copyright 2023 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator; @Slf4j public class Main { static final DouYinOpenDocApi douYinOpenDocApi = Feign.builder() .logLevel(Level.BASIC) .logger(new Slf4jLogger(DouYinOpenDocApi.class)) .decoder(new GsonDecoder(Misc.GSON)) .target(DouYinOpenDocApi.class, Misc.DOC_BASE_URL); static final ExecutorService executorService = new ThreadPoolExecutor( 30, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), new CallerRunsPolicy() ); @SneakyThrows public static void main(String[] args) { log.info("Hold on, generator started."); final Stopwatch stopwatch = Stopwatch.createStarted(); final DocsResponse docsResponse = douYinOpenDocApi.allDocs(); final List<Data> data = docsResponse.getData(); for (final Data datum : data) { final AtomicReference<GeneratorContents> contents = new AtomicReference<>(); final List<CompletableFuture<Void>> futures = Lists.newArrayList(); datum.getChildren() .stream() .filter(it -> it.getTitle().contains("开发"))
/* * Copyright 2023 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.eahau.openapi.douyin.generator; @Slf4j public class Main { static final DouYinOpenDocApi douYinOpenDocApi = Feign.builder() .logLevel(Level.BASIC) .logger(new Slf4jLogger(DouYinOpenDocApi.class)) .decoder(new GsonDecoder(Misc.GSON)) .target(DouYinOpenDocApi.class, Misc.DOC_BASE_URL); static final ExecutorService executorService = new ThreadPoolExecutor( 30, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), new CallerRunsPolicy() ); @SneakyThrows public static void main(String[] args) { log.info("Hold on, generator started."); final Stopwatch stopwatch = Stopwatch.createStarted(); final DocsResponse docsResponse = douYinOpenDocApi.allDocs(); final List<Data> data = docsResponse.getData(); for (final Data datum : data) { final AtomicReference<GeneratorContents> contents = new AtomicReference<>(); final List<CompletableFuture<Void>> futures = Lists.newArrayList(); datum.getChildren() .stream() .filter(it -> it.getTitle().contains("开发"))
.map(Children::getChildren)
1
2023-10-07 09:09:15+00:00
4k
Aywen1/wispy
src/fr/nicolas/wispy/Frames/MainFrame.java
[ { "identifier": "GamePanel", "path": "src/fr/nicolas/wispy/Panels/GamePanel.java", "snippet": "public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {\n\n\tpublic static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;\n\tprivate int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight;\n\tprivate Runner runner;\n\tprivate MapManager mapManager;\n\tprivate BufferedImage sky;\n\tprivate Player player;\n\tprivate Point mouseLocation;\n\n\tprivate boolean keyDPressed = false, keyQPressed = false, keySpacePressed = false, isEscapeMenuOpen = false;\n\n\tpublic GamePanel(Rectangle frameBounds, boolean isNewGame) {\n\t\tsuper(frameBounds);\n\t\tnewBlockWidth = BLOCK_SIZE;\n\t\tnewBlockHeight = BLOCK_SIZE;\n\n\t\tthis.addKeyListener(this);\n\t\tthis.addMouseListener(this);\n\t\tthis.addMouseMotionListener(this);\n\t\tthis.setFocusable(true);\n\n\t\t// Chargement des textures\n\t\tfor (int i = 0; i < BlockID.values().length; i++) {\n\t\t\tloadBlockImage(BlockID.values()[i]);\n\t\t}\n\n\t\ttry {\n\t\t\tsky = ImageIO.read(getClass().getResource(\"Components/Game/res/map/sky.png\"));\n\t\t\tplayer = new Player(ImageIO.read(getClass().getResource(\"Components/Game/res/player/p_stop.png\")),\n\t\t\t\t\tImageIO.read(getClass().getResource(\"Components/Game/res/player/p_walk1.png\")),\n\t\t\t\t\tImageIO.read(getClass().getResource(\"Components/Game/res/player/p_walk2.png\")), this);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// Création/Chargement nouveau monde\n\t\tmapManager = new MapManager(player);\n\t\tmapManager.loadWorld(\"TestWorld\");\n\n\t\t// Lancement des threads\n\t\trunner = new Runner(this); // Actualiser les blocs puis les textures\n\t\tmapManager.newLoadingMapThread(runner, this); // Charger et décharger les maps\n\n\t\tsetFrameBounds(new Rectangle(MainFrame.INIT_WIDTH, MainFrame.INIT_HEIGHT));\n\t}\n\n\t// Gestion blocs (textures)\n\tpublic enum BlockID {\n\t\tSTONE, DIRT, GRASS, SAND;\n\n\t\tprivate BufferedImage img = null;\n\n\t\tpublic void setImg(BufferedImage img) {\n\t\t\tthis.img = img;\n\t\t}\n\n\t\tpublic BufferedImage getImg() {\n\t\t\treturn img;\n\t\t}\n\t}\n\n\tprivate void loadBlockImage(BlockID blockID) {\n\t\ttry {\n\t\t\tblockID.setImg(ImageIO.read(\n\t\t\t\t\tgetClass().getResource(\"Components/Game/res/blocks/\" + blockID.toString().toLowerCase() + \".png\")));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t// Refresh / Paint methods\n\tpublic void refresh() {\n\t\tif (keyDPressed) {\n\t\t\tplayer.setWalking(true);\n\t\t\tplayer.setToRight(true);\n\t\t}\n\n\t\tif (keyQPressed) {\n\t\t\tplayer.setWalking(true);\n\t\t\tplayer.setToRight(false);\n\t\t}\n\n\t\tif (!keyQPressed && !keyDPressed) {\n\t\t\tplayer.setWalking(false);\n\t\t}\n\n\t\tif (keySpacePressed) {\n\t\t\tplayer.setJumping(true);\n\t\t\tkeySpacePressed = false;\n\t\t}\n\n\t\tplayer.refresh(playerX, playerY, playerWidth, playerHeight);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.drawImage(sky, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\t// Le paint des blocs intègre le test de collision avec le joueur\n\t\tmapManager.refreshPaintAllDisplayedBlocks(g, RefreshPaintMap.PAINT, this.getWidth(), this.getHeight(),\n\t\t\t\tnewBlockWidth, newBlockHeight, 0, 0, 0, 0, this, null);\n\t\tplayer.paint(g, playerX, playerY, playerWidth, playerHeight);\n\n\t\tif (isEscapeMenuOpen) {\n\t\t\tnew EscapeMenu().paint(g, this.getHeight());\n\t\t}\n\n\t\tmapManager.refreshPaintAllDisplayedBlocks(g, RefreshPaintMap.SELECTION, this.getWidth(), this.getHeight(),\n\t\t\t\tnewBlockWidth, newBlockHeight, 0, 0, 0, 0, this, mouseLocation);\n\t}\n\n\tpublic void setFrameBounds(Rectangle frameBounds) {\n\t\tnewBlockWidth = BLOCK_SIZE * (int) frameBounds.getWidth() / MainFrame.INIT_WIDTH;\n\t\tnewBlockHeight = BLOCK_SIZE * (int) frameBounds.getHeight() / MainFrame.INIT_HEIGHT;\n\t\tplayerX = INIT_PLAYER_X / GamePanel.BLOCK_SIZE * newBlockWidth;\n\t\tplayerY = INIT_PLAYER_Y / GamePanel.BLOCK_SIZE * newBlockHeight;\n\t\tplayerWidth = (int) player.getWidth() / GamePanel.BLOCK_SIZE * newBlockWidth;\n\t\tplayerHeight = (int) player.getHeight() / GamePanel.BLOCK_SIZE * newBlockHeight;\n\t}\n\n\t// Getters and Setters\n\tpublic int getNewBlockWidth() {\n\t\treturn newBlockWidth;\n\t}\n\n\tpublic int getNewBlockHeight() {\n\t\treturn newBlockHeight;\n\t}\n\n\tpublic Player getPlayer() {\n\t\treturn player;\n\t}\n\n\tpublic MapManager getMapManager() {\n\t\treturn mapManager;\n\t}\n\n\t// KeyListener\n\tpublic void keyPressed(KeyEvent e) {\n\t\tif (e.getKeyCode() == KeyEvent.VK_ESCAPE) {\n\t\t\tif (isEscapeMenuOpen) {\n\t\t\t\tisEscapeMenuOpen = false;\n\t\t\t} else {\n\t\t\t\tisEscapeMenuOpen = true;\n\t\t\t}\n\t\t}\n\t\tif (e.getKeyCode() == KeyEvent.VK_D) {\n\t\t\tkeyDPressed = true;\n\t\t} else if (e.getKeyCode() == KeyEvent.VK_Q) {\n\t\t\tkeyQPressed = true;\n\t\t}\n\t\tif (e.getKeyCode() == KeyEvent.VK_SPACE) {\n\t\t\tkeySpacePressed = true;\n\t\t}\n\t}\n\n\tpublic void keyReleased(KeyEvent e) {\n\t\tif (e.getKeyCode() == KeyEvent.VK_D) {\n\t\t\tkeyDPressed = false;\n\t\t} else if (e.getKeyCode() == KeyEvent.VK_Q) {\n\t\t\tkeyQPressed = false;\n\t\t}\n\t}\n\n\tpublic void keyTyped(KeyEvent e) {\n\n\t}\n\n\t// MouseListener\n\n\tpublic void mouseClicked(MouseEvent e) {\n\t}\n\n\tpublic void mouseEntered(MouseEvent e) {\n\t}\n\n\tpublic void mouseExited(MouseEvent e) {\n\t}\n\n\tpublic void mousePressed(MouseEvent e) {\n\t}\n\n\tpublic void mouseReleased(MouseEvent e) {\n\t}\n\n\t// MouseMotionListener\n\tpublic void mouseDragged(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\t}\n\n\tpublic void mouseMoved(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\t}\n\n}" }, { "identifier": "MenuPanel", "path": "src/fr/nicolas/wispy/Panels/MenuPanel.java", "snippet": "public class MenuPanel extends WPanel implements MouseListener, MouseMotionListener {\n\n\tprivate BufferedImage bg, title;\n\tprivate Point mouseLocation = new Point(0, 0);\n\tprivate WButton buttonStart, buttonSettings, buttonQuit;\n\tprivate MainFrame mainFrame;\n\n\tpublic MenuPanel(Rectangle frameBounds, MainFrame mainFrame) {\n\t\tsuper(frameBounds);\n\t\tthis.mainFrame = mainFrame;\n\n\t\t// Création dossier config\n\t\tif (!new File(\"Wispy\").exists()) {\n\t\t\tnew File(\"Wispy/worlds\").mkdirs();\n\t\t}\n\n\t\t// Chargement textures menu\n\t\ttry {\n\t\t\tbg = ImageIO.read(getClass().getResource(\"Components/Menu/res/img/bg.png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\ttitle = ImageIO.read(getClass().getResource(\"Components/Menu/res/img/title.png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tthis.addMouseListener(this);\n\t\tthis.addMouseMotionListener(this);\n\t\tthis.setFocusable(true);\n\n\t\tinit();\n\t}\n\n\tprivate void init() {\n\t\tthis.setLayout(null);\n\n\t\tbuttonStart = new WButton(\"Start\", new Rectangle((int) frameBounds.getWidth() / 2 - 450 / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - 93 - 110, 450, 93));\n\t\tbuttonSettings = new WButton(\"Settings\", new Rectangle((int) frameBounds.getWidth() / 2 - 450 / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - 93, 450, 93));\n\t\tbuttonQuit = new WButton(\"Quit\", new Rectangle((int) frameBounds.getWidth() / 2 - 450 / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - 93 - 110, 450, 93));\n\n\t\tadd(buttonStart);\n\t\tadd(buttonSettings);\n\t\tadd(buttonQuit);\n\n\t\tsetFrameBounds(frameBounds);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\tg.setColor(new Color(0, 0, 0, 220));\n\t\tg.fillRect(0, 0, this.getWidth(), this.getHeight());\n\n\t\tint newWidth = 393 * (int) frameBounds.getWidth() / MainFrame.INIT_WIDTH;\n\t\tint newHeight = 142 * (int) frameBounds.getHeight() / MainFrame.INIT_HEIGHT;\n\t\tg.drawImage(title, (int) frameBounds.getWidth() / 2 - newWidth / 2,\n\t\t\t\t(int) 55 * (int) frameBounds.getHeight() / MainFrame.INIT_HEIGHT, newWidth, newHeight, null);\n\t}\n\n\t// MouseListener\n\n\tpublic void mouseClicked(MouseEvent e) {\n\t}\n\n\tpublic void mouseEntered(MouseEvent e) {\n\t}\n\n\tpublic void mouseExited(MouseEvent e) {\n\t}\n\n\tpublic void mousePressed(MouseEvent e) {\n\t}\n\n\tpublic void mouseReleased(MouseEvent e) {\n\t\tif (e.getButton() == MouseEvent.BUTTON1) {\n\t\t\tif (buttonStart.mouseClick(mouseLocation)) {\n\t\t\t\tmainFrame.newGame();\n\t\t\t} else if (buttonSettings.mouseClick(mouseLocation)) {\n\t\t\t\tSystem.out.println(2);\n\t\t\t} else if (buttonQuit.mouseClick(mouseLocation)) {\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t}\n\n\t\trepaint();\n\t}\n\n\t// MouseMotionListener\n\n\tpublic void mouseDragged(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tbuttonStart.mouseMove(mouseLocation);\n\t\tbuttonSettings.mouseMove(mouseLocation);\n\t\tbuttonQuit.mouseMove(mouseLocation);\n\n\t\trepaint();\n\t}\n\n\tpublic void mouseMoved(MouseEvent e) {\n\t\tthis.mouseLocation = e.getPoint();\n\n\t\tbuttonStart.mouseMove(mouseLocation);\n\t\tbuttonSettings.mouseMove(mouseLocation);\n\t\tbuttonQuit.mouseMove(mouseLocation);\n\n\t\trepaint();\n\t}\n\n\tpublic void setFrameBounds(Rectangle frameBounds) {\n\t\tthis.frameBounds = frameBounds;\n\n\t\tint newWidth = 450 * (int) frameBounds.getWidth() / MainFrame.INIT_WIDTH;\n\t\tint newHeight = 93 * (int) frameBounds.getHeight() / MainFrame.INIT_HEIGHT;\n\t\tbuttonStart.changeBounds(new Rectangle((int) frameBounds.getWidth() / 2 - newWidth / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - newHeight - 50 * (int) frameBounds.getHeight() / 700, newWidth,\n\t\t\t\tnewHeight));\n\n\t\tbuttonSettings.changeBounds(new Rectangle((int) frameBounds.getWidth() / 2 - newWidth / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - newHeight + 70 * (int) frameBounds.getHeight() / 700, newWidth,\n\t\t\t\tnewHeight));\n\n\t\tbuttonQuit.changeBounds(new Rectangle((int) frameBounds.getWidth() / 2 - newWidth / 2,\n\t\t\t\t(int) frameBounds.getHeight() / 2 - newHeight + 190 * (int) frameBounds.getHeight() / 700, newWidth,\n\t\t\t\tnewHeight));\n\n\t\tbuttonStart.reSize(40 * ((int) frameBounds.getWidth() * (int) frameBounds.getHeight()) / 1200000);\n\t\tbuttonSettings.reSize(40 * ((int) frameBounds.getWidth() * (int) frameBounds.getHeight()) / 1200000);\n\t\tbuttonQuit.reSize(40 * ((int) frameBounds.getWidth() * (int) frameBounds.getHeight()) / 1200000);\n\t}\n\n}" }, { "identifier": "WPanel", "path": "src/fr/nicolas/wispy/Panels/Components/Menu/WPanel.java", "snippet": "public abstract class WPanel extends JPanel {\n\n\tprotected Rectangle frameBounds;\n\n\tpublic WPanel(Rectangle frameBounds) {\n\t\tthis.frameBounds = frameBounds;\n\t}\n\n\tpublic void setFrameBounds(Rectangle frameBounds) {\n\n\t}\n\n}" } ]
import java.awt.Dimension; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import fr.nicolas.wispy.Panels.GamePanel; import fr.nicolas.wispy.Panels.MenuPanel; import fr.nicolas.wispy.Panels.Components.Menu.WPanel;
3,378
package fr.nicolas.wispy.Frames; public class MainFrame extends JFrame { private WPanel panel; public static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720; public MainFrame() { this.setTitle("Wispy"); this.setSize(INIT_WIDTH, INIT_HEIGHT); this.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT)); this.setLocationRelativeTo(null); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new MenuPanel(this.getBounds(), this); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { panel.setFrameBounds(getBounds()); } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } }); this.setContentPane(panel); this.setVisible(true); } public void newGame() {
package fr.nicolas.wispy.Frames; public class MainFrame extends JFrame { private WPanel panel; public static final int INIT_WIDTH = 1250, INIT_HEIGHT = 720; public MainFrame() { this.setTitle("Wispy"); this.setSize(INIT_WIDTH, INIT_HEIGHT); this.setMinimumSize(new Dimension(INIT_WIDTH, INIT_HEIGHT)); this.setLocationRelativeTo(null); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new MenuPanel(this.getBounds(), this); this.addComponentListener(new ComponentListener() { public void componentResized(ComponentEvent e) { panel.setFrameBounds(getBounds()); } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } }); this.setContentPane(panel); this.setVisible(true); } public void newGame() {
panel = new GamePanel(this.getBounds(), true);
0
2023-10-13 13:10:56+00:00
4k
PfauMC/CyanWorld
cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/commands/CmdSethome.java
[ { "identifier": "Cyan1dex", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/Cyan1dex.java", "snippet": "public class Cyan1dex extends JavaPlugin {\n public static Server server;\n public static Cyan1dex instance;\n public static File dataFolder;\n public static Random random;\n public static YandexTranslator translator;\n public static LanguageUtils lang;\n public static EffectManager effectManager;\n public static ChatUtils chatUtils;\n public static FileConfiguration configuration;\n public static YamlConfiguration cfgplayers;\n public static YamlConfiguration cfguuid;\n public static YamlConfiguration goodbyedear;\n public static Map<String, QueryResponse> queryResponseMap;\n public static Map<Player, Integer> ecoMap;\n public static World world;\n public static List<ArmorStand> tempHolo;\n\n static {\n random = new Random();\n queryResponseMap = new HashMap<String, QueryResponse>();\n tempHolo = new ArrayList<ArmorStand>();\n }\n\n public static void saveCfg(FileConfiguration cfg, String name) {\n try {\n cfg.save(new File(dataFolder, name));\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void mainRcon(String cmd) {\n System.out.println(\"[MainRCON] /\" + cmd);\n Cyan1dex.rcon(35001, cmd, \"4HJU9VPONRUFKE8A1PH4\");\n }\n\n public static void rcon(String servername, String cmd) {\n switch (servername) {\n case \"auth\": {\n Cyan1dex.rcon(35000, cmd, \"3CyanPetuh3\");\n break;\n }\n case \"survival\": {\n Cyan1dex.rcon(35002, cmd, \"3CyanPetuh3\");\n break;\n }\n case \"mw\": {\n Cyan1dex.rcon(35003, cmd, \"3CyanPetuh3\");\n break;\n }\n case \"bw1\": {\n Cyan1dex.rcon(35101, cmd, \"3CyanPetuh3\");\n break;\n }\n case \"bw2\": {\n Cyan1dex.rcon(35102, cmd, \"3CyanPetuh3\");\n break;\n }\n default: {\n Cyan1dex.rcon(35001, cmd, \"3CyanPetuh3\");\n }\n }\n }\n\n public static void rcon(int port, String cmd, String pass) {\n try {\n RconManager rcon = new RconManager(\"localhost\", port, pass.getBytes());\n rcon.command(cmd);\n rcon.disconnect();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n public void onEnable() {\n server = this.getServer();\n instance = this;\n dataFolder = this.getDataFolder();\n try {\n configuration = this.getConfig();\n configuration.save(new File(dataFolder, \"config.yml\"));\n cfgplayers = YamlConfiguration.loadConfiguration(new File(dataFolder, \"players.yml\"));\n cfguuid = YamlConfiguration.loadConfiguration(new File(dataFolder, \"uuid.yml\"));\n new Config();\n new Msg();\n chatUtils = new ChatUtils();\n new RebootManager();\n ecoMap = new HashMap<Player, Integer>();\n world = server.getWorld(\"world\");\n new BungeeBridge();\n new EventListener();\n translator = new YandexTranslator(Arrays.asList(\"trnsl.1.1.20170422T093752Z.2a56bcc7b9a144df.80639eb6042f852255fab658bc107a0f6995554d\", \"trnsl.1.1.20170422T093801Z.6c7589690cd72e17.17c8b7df162fcb00389d50d025aead63ab97f20c\", \"trnsl.1.1.20170422T093823Z.09bb4567c9157c9c.4c4f9c6b07defe91494a26b4720b3f9532274cba\"));\n lang = new LanguageUtils();\n this.initCommands();\n System.out.println(\"[Cyan1dex] Запуск для сервера \" + Config.servername);\n server.getScheduler().scheduleSyncDelayedTask(instance, () -> {\n server.getOnlinePlayers().forEach(players -> {\n players.sendMessage(\"§aПлагины перезапущены!\");\n }\n );\n }\n );\n } catch (Exception ex) {\n ex.printStackTrace();\n server.shutdown();\n }\n }\n\n public void onDisable() {\n Cyan1dex.saveCfg(cfgplayers, \"players.yml\");\n Cyan1dex.saveCfg(cfguuid, \"uuid.yml\");\n Cyan1dex.saveCfg(CmdTrack.trackcfg, \"track.yml\");\n server.getWorlds().forEach(World2 -> {\n World2.getEntities().forEach(Entity2 -> {\n if (!(Entity2 instanceof ArmorStand)) {\n return;\n }\n ArmorStand as = (ArmorStand) Entity2;\n if (as.getScoreboardTags().contains(\"tempholo\")) {\n as.remove();\n }\n }\n );\n }\n );\n }\n\n private void initCommands() {\n new CmdCyan1dex();\n new CmdBroadcast();\n new CmdPlayerInfo();\n new CmdTell();\n new CmdKick();\n new CmdLang();\n new CmdMe();\n new CmdBan();\n new CmdTrack();\n new CmdG();\n }\n\n private void initOnlineUpdate() {\n if (!Config.isMainServer) {\n return;\n }\n MCQuery hub = new MCQuery(\"localhost\", 25001);\n MCQuery survival = new MCQuery(\"localhost\", 25002);\n MCQuery mw = new MCQuery(\"localhost\", 25003);\n MCQuery bw1 = new MCQuery(\"localhost\", 25101);\n MCQuery bw2 = new MCQuery(\"localhost\", 25102);\n server.getScheduler().scheduleSyncRepeatingTask(this, () -> {\n queryResponseMap.put(\"hub\", hub.basicStat());\n queryResponseMap.put(\"survival\", survival.basicStat());\n queryResponseMap.put(\"mw\", mw.basicStat());\n queryResponseMap.put(\"bw1\", bw1.basicStat());\n queryResponseMap.put(\"bw2\", bw2.basicStat());\n }\n , 0, 20);\n }\n\n private void initFakeButItsRealOnline() {\n if (!Config.fakebutitsrealonline_enable) {\n return;\n }\n if (!server.getPluginManager().isPluginEnabled(\"ProtocolLib\")) {\n return;\n }\n new FakeButItsRealOnline(this);\n }\n}" }, { "identifier": "Msg", "path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/messages/Msg.java", "snippet": "public class Msg {\n public static String consoledeny = Msg.a(\"consoledeny\");\n public static String permdeny = Msg.a(\"permdeny\");\n public static String teleportdeny_otherworld = Msg.a(\"teleportdeny-otherworld\");\n public static String teleporting = Msg.a(\"teleporting\");\n public static String sethome_needsleep = Msg.a(\"sethome-needsleep\");\n public static String sethome_success = Msg.a(\"sethome-success\");\n\n public static String a(String a) {\n return Cyan1dex.configuration.getString(\"messages.\" + a);\n }\n}" } ]
import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import ru.cyanworld.cyan1dex.Cyan1dex; import ru.cyanworld.cyan1dex.messages.Msg; import java.util.ArrayList;
1,957
package ru.cyanworld.cyan1dex.commands; public class CmdSethome extends Command { public CmdSethome() { super("sethome", "Телепортация на точку дома", "/sethome", new ArrayList()); Cyan1dex.server.getCommandMap().register(this.getName(), this); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (sender instanceof Player) { Player player = (Player) sender;
package ru.cyanworld.cyan1dex.commands; public class CmdSethome extends Command { public CmdSethome() { super("sethome", "Телепортация на точку дома", "/sethome", new ArrayList()); Cyan1dex.server.getCommandMap().register(this.getName(), this); } public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (sender instanceof Player) { Player player = (Player) sender;
player.sendMessage(Msg.sethome_needsleep);
1
2023-10-08 17:50:55+00:00
4k
vaaako/Vakraft
src/main/java/com/magenta/main/Engine.java
[ { "identifier": "IGameLogic", "path": "src/main/java/com/magenta/engine/IGameLogic.java", "snippet": "public interface IGameLogic {\n\tvoid init(Window window, MouseInput mouseInput) throws Exception;\n\tvoid input(Window window, KeyboardInput keyboardInput, MouseInput mouseInput);\n\tvoid update(double delta, MouseInput mouseInput, Window window);\n\tvoid render(Window window);\n\tvoid cleanup(Window window);\n}" }, { "identifier": "KeyboardInput", "path": "src/main/java/com/magenta/engine/KeyboardInput.java", "snippet": "public class KeyboardInput {\n\tprivate Window window;\n\tprivate int keyDown = -1;\n\t\n\tpublic KeyboardInput(Window window) {\n\t\tthis.window = window;\n\t}\n\n\tpublic void init() {\n\t\tGLFW.glfwSetKeyCallback(window.getWindowHandle(), (window, key, scancode, action, mods) -> {\n\t\t\t// Just change if is action is pressed\n\t\t \tif(action == GLFW.GLFW_PRESS) this.keyDown = key;\n\t\t\t// System.out.println(\"Key: \" + key + \"\\nAction: \" + action + \"\\nMods: \" + mods);\n\t\t});\n\t}\n\n\tpublic boolean isPressingKey(int key) {\n\t\treturn GLFW.glfwGetKey(window.getWindowHandle(), key) == GLFW.GLFW_PRESS;\n\t}\n\t\n\tpublic boolean isKeyDown(int key) {\n\t\tint currentKeyDown = keyDown;\n\t\tif(currentKeyDown != key) return false;\n\n\t\t// Reset keyDown after checking\n\t\tkeyDown = -1; \n\t\treturn true;\n\t\t\n\t}\n\n\tpublic int getKeyDown() {\n\t\treturn keyDown; // Return the stored value\n\t}\n}" }, { "identifier": "Timer", "path": "src/main/java/com/magenta/engine/Timer.java", "snippet": "public class Timer {\n\tprivate double last;\n\t\n\tpublic Timer() {\n\t\tlast = getTime();\n\t}\n\n\tpublic double getCurrentTime() {\n\t\treturn System.nanoTime();\n\t}\n\n\tpublic double getTime() {\n\t\treturn System.nanoTime() / 1e9;\n\t}\n\n\tpublic double getElapsedTime() {\n\t\tdouble now = getTime();\n\t\tdouble deltaTime = now - last; // Calc elapsed time\n\t\tlast = now; // Lat time now is \"now\" time\n\t\treturn deltaTime;\n\t}\n\n\n\tpublic void setLast(double last) {\n\t\tthis.last = last;\n\t}\n\n\tpublic double getLast() {\n\t\treturn last;\n\t}\n}" }, { "identifier": "Window", "path": "src/main/java/com/magenta/engine/Window.java", "snippet": "public class Window {\n\tprivate String title;\n\tprivate int width, height;\n\tprivate long windowHandle;\n\tprivate boolean vSync;\n\n\n\tpublic Window(String title, int width, int height, boolean vSync) {\n\t\tthis.title = title;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.vSync = vSync;\n\t}\n\n\tpublic void initGLFW() {\n\t\tGLFWErrorCallback.createPrint(System.err).set(); // Errors to System.err\n\t\t\n\t\tif(!GLFW.glfwInit()) throw new IllegalStateException(\"Unable to initialize GLFW\");\n\t\t\t\t\n\t\tGLFW.glfwDefaultWindowHints();\n\t\tGLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GLFW.GLFW_FALSE);\n\t\tGLFW.glfwWindowHint(GLFW.GLFW_RESIZABLE, GLFW.GLFW_TRUE);\n\t\t\n\t\twindowHandle = GLFW.glfwCreateWindow(width, height, title, NULL, NULL);\n\t\tif(windowHandle == NULL) throw new IllegalStateException(\"Unable to create GLFW Window\");\n\n\t\t// Calback\n\t\t// On resizing window, adjust viewport\n\t\tGLFW.glfwSetFramebufferSizeCallback(windowHandle, (window, width, height) -> {\n\t\t\t// Tells OpenGL size of rendering window\n\t\t\tSystem.out.println(\"Resizing to: \" + width + \"x\" + height);\n\n\t\t\t// int aspect = width/height;\n\t\t\t// GL11.glViewport(0, 0, width * aspect, height * aspect); // Rendering startX, startX, width and height\n\t\t\tGL11.glViewport(0, 0, width, height); // Rendering startX, startX, width and height\n\n\t\t\tthis.width = width;\n\t\t\tthis.height = height;\n\t\t});\n\n\n\t\t// Get the thread stack and push a new frame\n\t\t// This is just to center the window\n\t\ttry (MemoryStack stack = MemoryStack.stackPush()) {\n\t\t\tIntBuffer pWidth = stack.mallocInt(1); // int*\n\t\t\tIntBuffer pHeight = stack.mallocInt(1); // int*\n\t\t\t\n\t\t\tGLFW.glfwGetWindowSize(windowHandle, pWidth, pHeight);\n\n\t\t\t// Get the resolution of the primary monitor\n\t\t\tGLFWVidMode vidmode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());\n\t\t\t\n\t\t\t// Set window position to center of screen\n\t\t\tGLFW.glfwSetWindowPos(windowHandle,\n\t\t\t\t(vidmode.width() - pWidth.get(0)) / 2,\n\t\t\t\t(vidmode.height() - pHeight.get(0)) / 2\n\t\t\t);\n\t\t\t\n\t\t} // The stack frame is popped automatically\n\n\t\tGLFW.glfwMakeContextCurrent(windowHandle); // Make the OpenGL context current\n\t\t\n\t\tif(vSync) GLFW.glfwSwapInterval(1); // Enable V-Sync\n\t\tGLFW.glfwShowWindow(windowHandle); // Make window visible\n\n\t\t// Begining of the start\n\t\tGL.createCapabilities(); // Finishes the initializing process\t\n\t\tGL11.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set the clear color\n\t\t\n\t\tGL11.glEnable(GL11.GL_DEPTH_TEST); // Enable 3D depth\n\t\tGL11.glEnable(GL11.GL_CULL_FACE); // Don't show inside faces\n\t\t\n\t\t// Translucent\n\t\tGL11.glEnable(GL11.GL_BLEND);\n\t}\n\n\n\t// This //\n\tpublic long getWindowHandle() {\n\t\treturn windowHandle;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn width;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn height;\n\t}\n\n\tpublic boolean isvSync() {\n\t\treturn vSync;\n\t}\n\n\tpublic void setClearColor(float r, float g, float b, float alpha) {\n\t\tGL11.glClearColor(r, g, b, alpha);\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t\tGLFW.glfwSetWindowTitle(windowHandle, title);\n\t}\n\n\tpublic void setvSync(boolean vSync) {\n\t\tthis.vSync = vSync;\n\t}\n\n\n\n\n\t// GLFW //\n\tpublic boolean windowShouldClose() {\n\t\treturn GLFW.glfwWindowShouldClose(windowHandle);\n\t}\n\n\tpublic void update() {\n\t\tGLFW.glfwSwapBuffers(windowHandle); // Swap front buffers to back buffers (clean screen basically)\n\t\tGLFW.glfwPollEvents(); // Window events (close, resize etc)\n\t}\n\n\tpublic void destroy() {\n\t\t// Free the window callbacks and destroy the window\n\t\tCallbacks.glfwFreeCallbacks(windowHandle);\n\t\tGLFW.glfwDestroyWindow(windowHandle);\n\n\t\t// Terminate GLFW and free the error callback\n\t\tGLFW.glfwTerminate();\n\t\tGLFW.glfwSetErrorCallback(null).free();\n\t}\n}" }, { "identifier": "MouseInput", "path": "src/main/java/com/magenta/engine/MouseInput.java", "snippet": "public class MouseInput {\n\tprivate Vector2d previousPos, currentPos;\n\tprivate Vector2f movement;\n\tprivate boolean inWindow = false,\n\t\t\t\t\tpressedLMB = false,\n\t\t\t\t\tpressedRMB = false,\n\t\t\t\t\tpressedMMB = false;\n\n\tpublic MouseInput() {\n\t\tthis.previousPos = new Vector2d(0, 0);\n\t\tthis.currentPos = new Vector2d(0, 0);\n\t\tthis.movement = new Vector2f();\n\t}\n\n\tpublic void init(Window window) {\n\t\tGLFW.glfwSetCursorPosCallback(window.getWindowHandle(), (windowHandle, xpos, ypos) -> {\n\t\t\tcurrentPos.x = xpos;\n\t\t\tcurrentPos.y = ypos;\n\t\t});\n\n\t\tGLFW.glfwSetCursorEnterCallback(window.getWindowHandle(), (windowHandle, entered) -> {\n\t\t\tinWindow = entered;\n\t\t});\n\t\t\n\t\tGLFW.glfwSetMouseButtonCallback(window.getWindowHandle(), (windowHandle, button, action, mode) -> {\n\t\t\tpressedLMB = button == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_PRESS;\n\t\t\tpressedMMB = button == GLFW.GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW.GLFW_PRESS;\n\t\t\tpressedRMB = button == GLFW.GLFW_MOUSE_BUTTON_RIGHT && action == GLFW.GLFW_PRESS;\n\t\t});\n\t}\n\n\t// Get previous position //\n\tpublic void input() {\n\t\tmovement.x = 0;\n\t\tmovement.y = 0;\n\n\t\tif(previousPos.x > 0 && previousPos.y > 0 && inWindow) {\n\t\t\t// Ellapsed position\n\t\t\tdouble deltaX = currentPos.x - previousPos.x,\n\t\t\t\t deltaY = currentPos.y - previousPos.y;\n\n\t\t\t// double centerX = window.getWidth() / 2;\n\t\t\t// double centerY = window.getHeight() / 2;\n\t\t\t// double deltaX = currentPos.x - centerX,\n\t\t\t// \t deltaY = currentPos.y - centerY;\n\n\t\t\tboolean rotX = deltaX != 0,\n\t\t\t\t\trotY = deltaY != 0;\n\n\t\t\t// The movement the cursor made (e.g. X +2.0 x Y +1.0)\n\t\t\tif(rotX)\n\t\t\t\tmovement.x = (float) deltaX;\n\t\t\tif(rotY)\n\t\t\t\tmovement.y = (float) -deltaY;\n\n\t\t\t// System.out.println(movement.x + \"x\" + movement.y);\n\t\t}\n\n\t\tpreviousPos.x = currentPos.x;\n\t\tpreviousPos.y = currentPos.y;\n\t}\n\n\t// Get pressed //\n\tpublic boolean isLMBPressed() {\n\t\treturn pressedLMB;\n\t}\n\n\tpublic boolean isRMBPressed() {\n\t\treturn pressedRMB;\n\t}\n\n\tpublic boolean isMMBPressed() {\n\t\treturn pressedMMB;\n\t}\n\n\t// Release //\n\tpublic void releaseLMB() {\n\t\tpressedLMB = false;\n\t}\n\n\tpublic void releaseRMB() {\n\t\tpressedRMB = false;\n\t}\n\n\tpublic void releaseMMB() {\n\t\tpressedMMB = false;\n\t}\n\n\t// This//\n\tpublic Vector2f getMovement() {\n\t\treturn movement;\n\t}\n\n\tpublic Vector2d getPreviousPos() {\n\t\treturn previousPos;\n\t}\n}" } ]
import com.magenta.engine.IGameLogic; import com.magenta.engine.KeyboardInput; import com.magenta.engine.Timer; import com.magenta.engine.Window; import com.magenta.engine.MouseInput;
2,663
package com.magenta.main; public class Engine implements Runnable { private final Window window; private final IGameLogic gameLogic; private final Timer timer; private final MouseInput mouseInput;
package com.magenta.main; public class Engine implements Runnable { private final Window window; private final IGameLogic gameLogic; private final Timer timer; private final MouseInput mouseInput;
private final KeyboardInput keyboardInput;
1
2023-10-08 04:08:22+00:00
4k
Aywen1/improvident
src/fr/nicolas/main/frames/EditFrame.java
[ { "identifier": "NBackground", "path": "src/fr/nicolas/main/components/NBackground.java", "snippet": "public class NBackground extends JPanel {\n\n\tprivate BufferedImage bg, bg2;\n\tprivate int type;\n\n\tpublic NBackground(int type) {\n\t\tthis.type = type;\n\t\tsetLayout(null);\n\n\t\tif (type == 0 || type == 1) {\n\n\t\t\ttry {\n\t\t\t\tbg = ImageIO.read(new File(\"res/components/bg.png\"));\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t} else if (type == 2) {\n\n\t\t\tthis.setBounds(0, 0, 800, 500);\n\t\t\ttry {\n\t\t\t\tbg2 = ImageIO.read(new File(\"res/components/bg2.png\"));\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tif (type == 0) {\n\t\t\tg.drawImage(bg, 0, 0, getWidth(), getHeight(), null);\n\t\t} else if (type == 1) {\n\t\t\tg.drawImage(bg, 0, 0, getWidth(), getHeight(), null);\n\n\t\t\tg.setColor(new Color(0, 0, 0, 120));\n\t\t\tg.fillRect(10, 20, 65, 30);\n\t\t\tg.fillRect(10, 70, 120, 30);\n\n\t\t\tg.setColor(new Color(0, 0, 0));\n\t\t\tg.drawRect(9, 19, 66, 31);\n\t\t\tg.drawRect(9, 69, 121, 31);\n\t\t} else if (type == 2) {\n\t\t\tg.drawImage(bg2, 0, 0, getWidth(), getHeight(), null);\n\t\t}\n\t}\n\n}" }, { "identifier": "NButtonImg", "path": "src/fr/nicolas/main/components/NButtonImg.java", "snippet": "public class NButtonImg extends JPanel {\n\n\tprivate String name = \"\";\n\tprivate BufferedImage img, imgHovered, imgMore;\n\tprivate Rectangle button;\n\tprivate boolean isHovered = false, isSelected = false;\n\tprivate int typeButton = 0;\n\n\tpublic NButtonImg(String name, Rectangle bounds) {\n\t\tinit1(name, bounds);\n\t}\n\n\tpublic NButtonImg(String path, Rectangle bounds, int typeButton) {\n\t\tthis.typeButton = typeButton;\n\n\t\tif (typeButton == 1) {\n\t\t\tthis.button = bounds;\n\t\t\ttry {\n\t\t\t\timg = ImageIO.read(new File(path + \"icon.png\"));\n\t\t\t} catch (IOException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\timgHovered = img;\n\t\t} else {\n\t\t\tinit1(path, bounds);\n\t\t}\n\t}\n\n\tprivate void init1(String name, Rectangle bounds) {\n\t\tthis.button = bounds;\n\t\ttry {\n\t\t\timg = ImageIO.read(new File(\"res/components/buttons/\" + name.toLowerCase() + \".png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\timgHovered = ImageIO.read(new File(\"res/components/buttons/\" + name.toLowerCase() + \"Hovered.png\"));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tif (button.contains(mouseLocation)) {\n\t\t\tisHovered = true;\n\t\t\tsetCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));\n\t\t} else {\n\t\t\tisHovered = false;\n\t\t\tsetCursor(Cursor.getDefaultCursor());\n\t\t}\n\t}\n\n\tpublic boolean mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tif (button.contains(mouseLocation) && !middleClick) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic boolean middleClick(Point mouseLocation, boolean middleClick) {\n\t\tif (button.contains(mouseLocation) && middleClick) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t\trepaint();\n\t}\n\n\tpublic boolean isHovered() {\n\t\treturn isHovered;\n\t}\n\n\tpublic void setSelected(boolean isSelected) {\n\t\tthis.isSelected = isSelected;\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tif (typeButton == 1) {\n\t\t\tif (isHovered) {\n\t\t\t\tg.setColor(new Color(255, 255, 255, 30));\n\t\t\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t\t\t\tg.setColor(new Color(255, 255, 255, 100));\n\t\t\t\tg.drawRect(0, 0, getWidth() - 1, getHeight() - 1);\n\t\t\t\tg.drawImage(img, 4, 4, getWidth() - 8, getHeight() - 8, null);\n\t\t\t} else {\n\t\t\t\tg.drawImage(img, 4, 4, getWidth() - 8, getHeight() - 8, null);\n\t\t\t}\n\t\t} else {\n\t\t\tif (isHovered || isSelected) {\n\t\t\t\tg.drawImage(imgHovered, 0, 0, getWidth(), getHeight(), null);\n\t\t\t} else {\n\t\t\t\tg.drawImage(img, 0, 0, getWidth(), getHeight(), null);\n\t\t\t}\n\t\t\tif (typeButton == 2 || typeButton == 3 || typeButton == 4 || typeButton == 5) {\n\t\t\t\tg.drawImage(imgMore, 7, 3, 30, 30, null);\n\t\t\t\tg.setColor(new Color(255, 255, 255));\n\t\t\t\tg.setFont(new Font(\"Calibri Light\", Font.PLAIN, 20));\n\t\t\t\tif (typeButton == 2) {\n\t\t\t\t\tg.setFont(new Font(\"Calibri Light\", Font.PLAIN, 22));\n\t\t\t\t\tg.drawString(name, 15, 25);\n\t\t\t\t} else if (typeButton == 3) {\n\t\t\t\t\tg.drawString(name, 23, 21);\n\t\t\t\t\tif (isSelected) {\n\t\t\t\t\t\tg.setColor(new Color(255, 255, 255, 30));\n\t\t\t\t\t\tg.drawLine(0, 26, 180, 26);\n\t\t\t\t\t\tg.setColor(new Color(255, 255, 255, 60));\n\t\t\t\t\t\tg.drawLine(0, 27, 180, 27);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeButton == 4) {\n\t\t\t\t\tg.drawString(name, 40, 21);\n\t\t\t\t\tif (isSelected) {\n\t\t\t\t\t\tg.setColor(new Color(255, 255, 255, 20));\n\t\t\t\t\t\tg.drawLine(0, 26, 150, 26);\n\t\t\t\t\t\tg.setColor(new Color(255, 255, 255, 30));\n\t\t\t\t\t\tg.drawLine(0, 27, 150, 27);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeButton == 5) {\n\t\t\t\t\tg.setFont(new Font(\"Calibri Light\", Font.PLAIN, 18));\n\t\t\t\t\tg.drawString(name, 10, 18);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "NLabel", "path": "src/fr/nicolas/main/components/NLabel.java", "snippet": "public class NLabel extends JLabel {\n\n\tpublic NLabel(String text, int size) {\n\t\tsetText(text);\n\t\tsetForeground(new Color(255,255,255));\n\t\tsetFont(new Font(\"Calibri Light\", Font.PLAIN, size));\n\t}\n\t\n}" }, { "identifier": "NDefault", "path": "src/fr/nicolas/main/panels/categories/NDefault.java", "snippet": "public class NDefault extends NCategoryPanel {\n\n\tprivate ArrayList<NButtonImg> buttonList;\n\tprivate ArrayList<NButtonImg> buttonCategoryList;\n\tprivate ArrayList<Integer> categoryList;\n\tprivate ArrayList<String> urlList;\n\tprivate CardLayout cardLayout = new CardLayout();\n\tprivate JPanel items = new JPanel(), aFaire = new JPanel(), aRevoir = new JPanel(), archives = new JPanel();\n\n\tprivate String[] categories = { \"À faire\", \"À revoir\", \"Archivés\" };\n\tprivate int openCategory = 0;\n\tprivate NButtonImg buttonAdd;\n\tprivate String name;\n\n\tpublic NDefault(String name) {\n\t\tthis.name = name;\n\n\t\tload();\n\t}\n\n\tpublic void load() {\n\t\tif (new File(\"Improvident/Categories/Cours écrits/À faire\").exists()) {\n\n\t\t\tbuttonList = new ArrayList<NButtonImg>();\n\t\t\tbuttonCategoryList = new ArrayList<NButtonImg>();\n\t\t\tcategoryList = new ArrayList<Integer>();\n\t\t\turlList = new ArrayList<String>();\n\t\t\tthis.removeAll();\n\t\t\taFaire.removeAll();\n\t\t\taRevoir.removeAll();\n\t\t\tarchives.removeAll();\n\n\t\t\tint x2 = 76;\n\t\t\tfor (int i = 0; i < categories.length; i++) {\n\t\t\t\tint y = 42, xNum = 1;\n\n\t\t\t\ttry {\n\t\t\t\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\t\t\t\tnew FileReader(\"Improvident/Categories/\" + name + \"/\" + categories[i]));\n\n\t\t\t\t\tString buttonName = \"\";\n\n\t\t\t\t\twhile (buttonName != null) {\n\t\t\t\t\t\tbuttonName = bufferedReader.readLine();\n\t\t\t\t\t\tif (buttonName != null) {\n\n\t\t\t\t\t\t\tNButtonImg button;\n\t\t\t\t\t\t\tif (xNum == 1) {\n\t\t\t\t\t\t\t\tbutton = new NButtonImg(\"category3\", new Rectangle(15 + 45, y + 86, 354, 25), 5);\n\t\t\t\t\t\t\t\tbutton.setBounds(15, y, 354, 25);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbutton = new NButtonImg(\"category3Inverted\", new Rectangle(383 + 45, y + 86, 354, 25),\n\t\t\t\t\t\t\t\t\t\t5);\n\t\t\t\t\t\t\t\tbutton.setBounds(383, y, 354, 25);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbutton.setName(buttonName);\n\n\t\t\t\t\t\t\tif (categories[i] == \"À faire\") {\n\t\t\t\t\t\t\t\taFaire.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(0);\n\t\t\t\t\t\t\t} else if (categories[i] == \"À revoir\") {\n\t\t\t\t\t\t\t\taRevoir.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(1);\n\t\t\t\t\t\t\t} else if (categories[i] == \"Archivés\") {\n\t\t\t\t\t\t\t\tarchives.add(button);\n\t\t\t\t\t\t\t\tcategoryList.add(2);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tbuttonList.add(button);\n\t\t\t\t\t\t\turlList.add(bufferedReader.readLine());\n\n\t\t\t\t\t\t\tif (xNum == 1) {\n\t\t\t\t\t\t\t\txNum = 2;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\txNum = 1;\n\t\t\t\t\t\t\t\ty += 32;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferedReader.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\n\t\t\t\tNButtonImg category = new NButtonImg(\"category\", new Rectangle(x2 + 45, 4 + 86, 150, 28), 4);\n\t\t\t\tcategory.setName(categories[i]);\n\t\t\t\tcategory.setBounds(x2, 4, 150, 28);\n\n\t\t\t\tbuttonCategoryList.add(category);\n\t\t\t\tthis.add(category);\n\n\t\t\t\tx2 += 225;\n\t\t\t}\n\t\t}\n\n\t\taFaire.setLayout(null);\n\t\taRevoir.setLayout(null);\n\t\tarchives.setLayout(null);\n\n\t\taFaire.add(new NBackground(2));\n\t\taRevoir.add(new NBackground(2));\n\t\tarchives.add(new NBackground(2));\n\n\t\tbuttonAdd = new NButtonImg(\"add\", new Rectangle(15 + 45, 5 + 86, 26, 26), 5);\n\t\tbuttonAdd.setBounds(15, 5, 26, 26);\n\t\tthis.add(buttonAdd);\n\n\t\tthis.setLayout(new BorderLayout());\n\t\titems.setLayout(cardLayout);\n\n\t\titems.add(aFaire, \"À faire\");\n\t\titems.add(aRevoir, \"À revoir\");\n\t\titems.add(archives, \"Archivés\");\n\n\t\tthis.add(items, BorderLayout.CENTER);\n\n\t\tselect(openCategory);\n\t}\n\n\tpublic void mouseMove(Point mouseLocation) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tbuttonList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tbuttonCategoryList.get(i).mouseMove(mouseLocation);\n\t\t}\n\t\tbuttonAdd.mouseMove(mouseLocation);\n\t}\n\n\tpublic void mouseClick(Point mouseLocation, boolean middleClick) {\n\t\tfor (int i = 0; i < buttonList.size(); i++) {\n\t\t\tif (buttonList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tif (categoryList.get(i) == openCategory) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tDesktop.getDesktop().browse(URI.create(urlList.get(i)));\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (buttonList.get(i).middleClick(mouseLocation, middleClick)) {\n\t\t\t\tif (categoryList.get(i) == openCategory) {\n\t\t\t\t\tnew EditFrame(this.getLocationOnScreen(),\n\t\t\t\t\t\t\t\"Improvident/Categories/\" + name + \"/\",\n\t\t\t\t\t\t\tcategories[openCategory],urlList.get(i), this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < buttonCategoryList.size(); i++) {\n\t\t\tif (buttonCategoryList.get(i).mouseClick(mouseLocation, middleClick)) {\n\t\t\t\tselect(i);\n\t\t\t}\n\t\t}\n\t\tif (buttonAdd.mouseClick(mouseLocation, middleClick)) {\n\t\t\tnew NewFrame(this.getLocationOnScreen(), \"Improvident/Categories/\" + name + \"/\" + categories[openCategory],\n\t\t\t\t\tthis);\n\t\t}\n\t}\n\n\tprivate void select(int i) {\n\t\tcardLayout.show(items, categories[i]);\n\t\topenCategory = i;\n\t\tfor (int i2 = 0; i2 < buttonCategoryList.size(); i2++) {\n\t\t\tbuttonCategoryList.get(i2).setSelected(false);\n\t\t}\n\t\tbuttonCategoryList.get(i).setSelected(true);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(0, 0, 0, 50));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\t}\n\n}" } ]
import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.ImageIcon; import javax.swing.JFrame; import fr.nicolas.main.components.NBackground; import fr.nicolas.main.components.NButtonImg; import fr.nicolas.main.components.NLabel; import fr.nicolas.main.panels.categories.NDefault;
3,509
package fr.nicolas.main.frames; public class EditFrame extends JFrame implements MouseListener, MouseMotionListener { private NBackground bg; private NButtonImg buttonAFaire, buttonARevoir, buttonArchives, buttonSupprimer; private NLabel labelText; private String path, category, url, name = "";
package fr.nicolas.main.frames; public class EditFrame extends JFrame implements MouseListener, MouseMotionListener { private NBackground bg; private NButtonImg buttonAFaire, buttonARevoir, buttonArchives, buttonSupprimer; private NLabel labelText; private String path, category, url, name = "";
private NDefault panel;
3
2023-10-13 10:30:31+00:00
4k
Mon-L/virtual-waiting-room
virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/repository/gateway/AccessTokenGatewayImpl.java
[ { "identifier": "AccessTokenGateway", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/gateway/repository/AccessTokenGateway.java", "snippet": "public interface AccessTokenGateway {\n AccessToken add(AccessToken token);\n\n AccessToken getByQueueIdAndRequestId(String queueId, String requestId);\n\n boolean changeStatus(String queueId, String requestId, AccessTokenStatus oldStatus, AccessTokenStatus newStatus);\n}" }, { "identifier": "AccessToken", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/model/entity/AccessToken.java", "snippet": "public class AccessToken {\n\n public static final String BEARER_TOKEN_TYPE = \"Bearer\";\n\n private Integer id;\n private String queueId;\n private String requestId;\n private long position;\n private String tokenValue;\n private String tokenType;\n private Date createTime;\n private Date expiredTime;\n private AccessTokenStatus status;\n\n public static AccessToken create(\n String queueId, String requestId, long requestPosition, Integer tokenValiditySecond) {\n Instant now = Instant.now();\n AccessToken accessToken = new AccessToken();\n accessToken.setQueueId(queueId);\n accessToken.setRequestId(requestId);\n accessToken.setPosition(requestPosition);\n accessToken.setCreateTime(Date.from(now));\n accessToken.setTokenType(AccessToken.BEARER_TOKEN_TYPE);\n accessToken.setTokenValue(generateBearerTokenValue());\n accessToken.setStatus(AccessTokenStatus.ACTIVE);\n if (tokenValiditySecond != null) {\n Instant expiredTime = now.plus(tokenValiditySecond, ChronoUnit.SECONDS);\n accessToken.setExpiredTime(Date.from(expiredTime));\n }\n return accessToken;\n }\n\n private static String generateBearerTokenValue() {\n return UUID.randomUUID().toString().replace(\"-\", \"\");\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getQueueId() {\n return queueId;\n }\n\n public void setQueueId(String queueId) {\n this.queueId = queueId;\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n\n public long getPosition() {\n return position;\n }\n\n public void setPosition(long position) {\n this.position = position;\n }\n\n public String getTokenValue() {\n return tokenValue;\n }\n\n public void setTokenValue(String tokenValue) {\n this.tokenValue = tokenValue;\n }\n\n public String getTokenType() {\n return tokenType;\n }\n\n public void setTokenType(String tokenType) {\n this.tokenType = tokenType;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getExpiredTime() {\n return expiredTime;\n }\n\n public void setExpiredTime(Date expiredTime) {\n this.expiredTime = expiredTime;\n }\n\n public AccessTokenStatus getStatus() {\n return status;\n }\n\n public void setStatus(AccessTokenStatus status) {\n this.status = status;\n }\n}" }, { "identifier": "AccessTokenStatus", "path": "virtual-waiting-room-domain/src/main/java/cn/zcn/virtual/waiting/room/domain/model/entity/AccessTokenStatus.java", "snippet": "public enum AccessTokenStatus implements EnumValue<Integer> {\n COMPLETED(1),\n ABANDONED(2),\n ACTIVE(3);\n\n private final int value;\n\n AccessTokenStatus(int value) {\n this.value = value;\n }\n\n @Override\n public Integer getValue() {\n return value;\n }\n\n public static AccessTokenStatus getByValue(int value) {\n for (AccessTokenStatus t : AccessTokenStatus.class.getEnumConstants()) {\n if (t.getValue() == value) {\n return t;\n }\n }\n throw new IllegalArgumentException(\"AccessTokenStatus can not be found by value: \" + value);\n }\n}" }, { "identifier": "AccessTokenMapper", "path": "virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/repository/AccessTokenMapper.java", "snippet": "public interface AccessTokenMapper {\n void add(AccessTokenPO token);\n\n AccessTokenPO getByQueueIdAndRequestId(@Param(\"queueId\") String queueId, @Param(\"requestId\") String requestId);\n\n int changeStatus(\n @Param(\"queueId\") String queueId,\n @Param(\"requestId\") String requestId,\n @Param(\"oldStatus\") AccessTokenStatus oldStatus,\n @Param(\"newStatus\") AccessTokenStatus newStatus);\n}" }, { "identifier": "AccessTokenConverter", "path": "virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/repository/converter/AccessTokenConverter.java", "snippet": "@Mapper\npublic interface AccessTokenConverter {\n\n AccessTokenConverter INSTANCE = Mappers.getMapper(AccessTokenConverter.class);\n\n AccessToken poToEntity(AccessTokenPO po);\n\n AccessTokenPO entityToPO(AccessToken entity);\n}" }, { "identifier": "AccessTokenPO", "path": "virtual-waiting-room-infrastructure/src/main/java/cn/zcn/virtual/waiting/room/infrastructure/repository/po/AccessTokenPO.java", "snippet": "public class AccessTokenPO {\n\n private Integer id;\n private String queueId;\n private String requestId;\n private long position;\n private String tokenValue;\n private String tokenType;\n private Date createTime;\n private Date expiredTime;\n private AccessTokenStatus status;\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 getQueueId() {\n return queueId;\n }\n\n public void setQueueId(String queueId) {\n this.queueId = queueId;\n }\n\n public String getRequestId() {\n return requestId;\n }\n\n public void setRequestId(String requestId) {\n this.requestId = requestId;\n }\n\n public long getPosition() {\n return position;\n }\n\n public void setPosition(long position) {\n this.position = position;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getExpiredTime() {\n return expiredTime;\n }\n\n public void setExpiredTime(Date expiredTime) {\n this.expiredTime = expiredTime;\n }\n\n public String getTokenValue() {\n return tokenValue;\n }\n\n public void setTokenValue(String tokenValue) {\n this.tokenValue = tokenValue;\n }\n\n public String getTokenType() {\n return tokenType;\n }\n\n public void setTokenType(String tokenType) {\n this.tokenType = tokenType;\n }\n\n public AccessTokenStatus getStatus() {\n return status;\n }\n\n public void setStatus(AccessTokenStatus status) {\n this.status = status;\n }\n}" } ]
import cn.zcn.virtual.waiting.room.domain.gateway.repository.AccessTokenGateway; import cn.zcn.virtual.waiting.room.domain.model.entity.AccessToken; import cn.zcn.virtual.waiting.room.domain.model.entity.AccessTokenStatus; import cn.zcn.virtual.waiting.room.infrastructure.repository.AccessTokenMapper; import cn.zcn.virtual.waiting.room.infrastructure.repository.converter.AccessTokenConverter; import cn.zcn.virtual.waiting.room.infrastructure.repository.po.AccessTokenPO; import javax.annotation.Resource; import org.springframework.stereotype.Component;
2,033
/* * 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 cn.zcn.virtual.waiting.room.infrastructure.repository.gateway; /** * @author zicung */ @Component public class AccessTokenGatewayImpl implements AccessTokenGateway { @Resource private AccessTokenMapper accessTokenMapper; @Override
/* * 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 cn.zcn.virtual.waiting.room.infrastructure.repository.gateway; /** * @author zicung */ @Component public class AccessTokenGatewayImpl implements AccessTokenGateway { @Resource private AccessTokenMapper accessTokenMapper; @Override
public AccessToken add(AccessToken token) {
1
2023-10-07 10:31:42+00:00
4k
ferderplays/ElypsaClient
src/main/java/net/elypsaclient/client/Main.java
[ { "identifier": "ClientRefers", "path": "src/main/java/net/ferderplays/elypsa/refers/ClientRefers.java", "snippet": "public class ClientRefers {\n public static final String MODID = \"elypsaclient\",\n NAME =\"Elypsa Client\",\n VERSION = \"0.0.1\";\n}" }, { "identifier": "Module", "path": "src/main/java/net/elypsaclient/modules/Module.java", "snippet": "public class Module {\n public String name, description;\n public int keyChar;\n public ModuleCateg category;\n public boolean toggled;\n\n protected Minecraft mc = Minecraft.getMinecraft();\n public Module(String name, String description, ModuleCateg category) {\n super();\n this.name = name;\n this.description = description;\n this.category = category;\n this.toggled = false;\n }\n\n public String getName() {\n return name;\n }\n\n public ModuleCateg getCategory() {\n return category;\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 int getKeyChar() {\n return keyChar;\n }\n\n public void setKeyChar(int keyChar) {\n this.keyChar = keyChar;\n }\n\n public boolean isToggled() {\n return toggled;\n }\n\n public void setToggled(boolean toggled) {\n this.toggled = toggled;\n }\n\n public void enable() {\n this.toggled = !this.toggled;\n if (this.toggled) onEnable();\n else onDisable();\n }\n\n public void onEnable() {\n MinecraftForge.EVENT_BUS.register(this);\n modAction();\n }\n\n public void modAction() {\n }\n\n public void onDisable() {\n MinecraftForge.EVENT_BUS.unregister(this);\n modActionEnd();\n }\n\n public void modActionEnd() {\n\n }\n}" }, { "identifier": "ModuleManager", "path": "src/main/java/net/elypsaclient/manager/ModuleManager.java", "snippet": "public class ModuleManager {\n public ArrayList<Module> modules;\n\n public ModuleManager() {\n (modules = new ArrayList<Module>()).clear();\n // combat\n this.modules.add(new KillAura());\n this.modules.add(new CrystalAura());\n this.modules.add(new AutoTotem());\n // movement\n this.modules.add(new Sprint());\n this.modules.add(new Fly());\n // player\n\n // render\n this.modules.add(new NoHurtCam());\n this.modules.add(new ClickGui());\n this.modules.add(new FullBright());\n // client\n }\n\n public Module getModule(String name) {\n for (Module module : modules) {\n if (module.getName().equals(name)) return module;\n }\n return null;\n }\n\n public ArrayList<Module> getModules() {\n return modules;\n }\n\n public static List<Module> getModulesByCateg(ModuleCateg category) {\n List<Module> modulesByCateg = new ArrayList<Module>();\n for (Module module : Main.moduleManager.modules) {\n if (module.getCategory().equals(category))\n modulesByCateg.add(module);\n }\n return modulesByCateg;\n }\n}" }, { "identifier": "HUD", "path": "src/main/java/net/elypsaclient/ui/HUD.java", "snippet": "public class HUD extends Gui {\n\n public Minecraft mc = Minecraft.getMinecraft();\n\n public static class ModuleComperator implements Comparator<Module> {\n\n @Override\n public int compare(Module m1, Module m2) {\n if (Minecraft.getMinecraft().fontRenderer.getStringWidth(m1.getName()) > Minecraft.getMinecraft().fontRenderer.getStringWidth(m2.getName())) {\n return -1;\n }\n if (Minecraft.getMinecraft().fontRenderer.getStringWidth(m1.getName()) > Minecraft.getMinecraft().fontRenderer.getStringWidth(m2.getName())) {\n return 1;\n }\n return 0;\n }\n }\n\n //private final ResourceLocation watermark = new ResourceLocation(ClientRefers.MODID,\"textures/watermark.png\");\n @SubscribeEvent\n public void renderOverlay(RenderGameOverlayEvent event) {\n Collections.sort(Main.moduleManager.modules, new ModuleComperator());\n ScaledResolution scaledres = new ScaledResolution(mc);\n FontRenderer fontRenderer = mc.fontRenderer;\n\n /* client logo\n if (event.getType() == RenderGameOverlayEvent.ElementType.TEXT) {\n mc.renderEngine.bindTexture(watermark);\n drawScaledCustomSizeModalRect(0, 0, 0, 50, 50, 50, 50, 50, 50, 50);\n } */\n\n // client info\n if (event.getType() == RenderGameOverlayEvent.ElementType.TEXT) {\n GlStateManager.pushMatrix();\n GlStateManager.translate(4, 4, 1);\n GlStateManager.scale(2, 2, 1);\n GlStateManager.translate(-4, -4, 1);\n fontRenderer.drawStringWithShadow(ClientRefers.NAME, 4, 4, ColorManager.getPrefferedColor());\n GlStateManager.popMatrix();\n }\n\n // module list\n if (event.getType() == RenderGameOverlayEvent.ElementType.TEXT) {\n int y = 2;\n final int[] counter = {1};\n for (Module module : Main.moduleManager.modules) {\n if (!module.getName().equalsIgnoreCase(\"\") && module.isToggled()) {\n drawRect(scaledres.getScaledWidth() - fontRenderer.getStringWidth(module.getName()) - 4, 4 + y, scaledres.getScaledWidth() - fontRenderer.getStringWidth(module.getName()) - 8, 8 + y + fontRenderer.FONT_HEIGHT, ColorManager.rainbow(counter[0] * 300));\n drawRect(scaledres.getScaledWidth() - fontRenderer.getStringWidth(module.getName()) - 4, 4 + y, scaledres.getScaledWidth(), 8 + y + fontRenderer.FONT_HEIGHT, ColorManager.getBgColor());\n fontRenderer.drawStringWithShadow(module.getName(), scaledres.getScaledWidth() - fontRenderer.getStringWidth(module.getName()) - 2, y + 6, ColorManager.rainbow(counter[0] * 300));\n\n y += fontRenderer.FONT_HEIGHT + 4;\n counter[0]++;\n }\n }\n }\n }\n}" }, { "identifier": "MainMenu", "path": "src/main/java/net/elypsaclient/ui/MainMenu.java", "snippet": "public class MainMenu extends GuiScreen {\n @Override\n public void initGui() {\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n mc.renderEngine.bindTexture(new ResourceLocation(\"elypsaclient/rsz_background.JPG\"));\n drawModalRectWithCustomSizedTexture(0, 0, 0, 0, width, height, width, height);\n ScaledResolution scaledres = new ScaledResolution(mc);\n\n drawRect(width / 2 - fontRenderer.getStringWidth(\"Singleplayer\") / 2 - 8, height / 2 - fontRenderer.FONT_HEIGHT - 4, width / 2 + fontRenderer.getStringWidth(\"Singleplayer\") / 2 + 8, (height / 2 + fontRenderer.FONT_HEIGHT + 8) + 3 * (fontRenderer.FONT_HEIGHT + 8), ColorManager.getColor(0, 0, 0, 155));\n\n String[] buttons = new String[] { \"Singleplayer\", \"Multiplayer\", \"Options\", \"Quit\"};\n\n int count = 0;\n for (String button : buttons) {\n drawCenteredString(fontRenderer, button, width / 2, height / 2 + (count * (fontRenderer.FONT_HEIGHT+ 8)) , ColorManager.getColor(255, 255, 255, 255));\n count++;\n }\n\n GlStateManager.pushMatrix();\n GlStateManager.translate(CoordsManager.centerStringX(ClientRefers.NAME, this.width), 50, 1);\n GlStateManager.scale(2, 2, 1);\n GlStateManager.translate(-(CoordsManager.centerStringX(ClientRefers.NAME, this.width)), -50, 1);\n fontRenderer.drawString(ClientRefers.NAME, CoordsManager.centerStringX(ClientRefers.NAME, this.width), 50, ColorManager.getColor(255, 255, 255, 255));\n GlStateManager.popMatrix();\n }\n\n @Override\n protected void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n String[] buttons = new String[] { \"Singleplayer\", \"Multiplayer\", \"Options\", \"Quit\"};\n\n int count = 0;\n for (String name : buttons) {\n float x = width / 2 - fontRenderer.getStringWidth(name) / 2;\n float y = height / 2 + (count * (fontRenderer.FONT_HEIGHT + 8)) ;\n if (mouseX >= x && mouseY >= y && mouseX < x + fontRenderer.getStringWidth(name) && mouseY < y + mc.fontRenderer.FONT_HEIGHT) {\n switch (name) {\n case \"Singleplayer\":\n mc.displayGuiScreen(new GuiWorldSelection(this));\n break;\n\n case \"Multiplayer\":\n mc.displayGuiScreen(new GuiMultiplayer(this));\n break;\n\n case \"Options\":\n mc.displayGuiScreen(new GuiOptions(this, mc.gameSettings));\n break;\n\n case \"Quit\":\n mc.shutdown();\n break;\n }\n }\n count++;\n }\n }\n}" }, { "identifier": "ClientDirectoryUtil", "path": "src/main/java/net/ferderplays/elypsa/utils/ClientDirectoryUtil.java", "snippet": "public class ClientDirectoryUtil {\n public static void init() {\n makeDir(FileUtil.getClientDir());\n makeDir(FileUtil.getClientConfigDir());\n }\n\n private static void makeDir(String dir) {\n FileUtil.createDir(dir);\n }\n}" } ]
import net.ferderplays.elypsa.refers.ClientRefers; import net.elypsaclient.modules.Module; import net.elypsaclient.manager.ModuleManager; import net.elypsaclient.ui.HUD; import net.elypsaclient.ui.MainMenu; import net.ferderplays.elypsa.utils.ClientDirectoryUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import org.apache.logging.log4j.Logger; import org.lwjgl.input.Keyboard;
2,546
package net.elypsaclient.client; @Mod(modid = ClientRefers.MODID, name = ClientRefers.NAME, version = ClientRefers.VERSION) public class Main { @Mod.Instance public Main instance;
package net.elypsaclient.client; @Mod(modid = ClientRefers.MODID, name = ClientRefers.NAME, version = ClientRefers.VERSION) public class Main { @Mod.Instance public Main instance;
public static ModuleManager moduleManager;
2
2023-10-10 18:11:26+00:00
4k
Kelwinkxps13/Projeto_POO_Swing
UrnaEletronica/src/br/edu/view/Login.java
[ { "identifier": "User", "path": "UrnaEletronica/src/br/edu/bancodedados/User.java", "snippet": "public class User {\r\n \r\n protected String nome;\r\n protected String senha;\r\n protected String email;\r\n\r\n public String getNome() {\r\n return nome;\r\n }\r\n\r\n public void setNome(String nome) {\r\n this.nome = nome;\r\n }\r\n\r\n public String getSenha() {\r\n return senha;\r\n }\r\n\r\n public void setSenha(String senha) {\r\n this.senha = senha;\r\n }\r\n\r\n public String getEmail() {\r\n return email;\r\n }\r\n\r\n public void setEmail(String email) {\r\n this.email = email;\r\n }\r\n\r\n /*\r\n String nome = campoNome.getText();\r\n String senha = campoSenha.getText();\r\n \r\n PreparedStatement pstm;\r\n \r\n Connection conn;\r\n String sql = \"insert into login (nome_usuario, senha_usuario) values(?, ?)\";\r\n \r\n conn = new ConexaoDAO().conexaodao();\r\n \r\n \r\n try {\r\n pstm = conn.prepareStatement(sql);\r\n \r\n \r\n \r\n } catch (SQLException erro) {\r\n JOptionPane.showMessageDialog(null, erro);\r\n }\r\n */\r\n\r\n \r\n}\r" }, { "identifier": "UsuarioDAO", "path": "UrnaEletronica/src/br/edu/bancodedados/UsuarioDAO.java", "snippet": "public class UsuarioDAO {\r\n Connection conn;\r\n \r\n\r\n public ResultSet autenticacaoUsuario(User objusuariodto) {\r\n conn = new ConexaoDAO().conexaodao();\r\n\r\n try {\r\n String sql = (\"SELECT * FROM usuarios WHERE email = ? AND senha = ?\");\r\n\r\n PreparedStatement pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getEmail());\r\n pstm.setString(2, objusuariodto.getSenha());\r\n\r\n ResultSet rs = pstm.executeQuery();\r\n return rs;\r\n\r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (autenticação): \" + error);\r\n return null;\r\n }\r\n\r\n }\r\n \r\n \r\n public void cadastrarUsuario(UsuarioDTO objusuariodto) {\r\n PreparedStatement pstm;\r\n String sql = \"insert into usuarios (nome, email, senha, votosA, votosB, votosC, votosBranco, votosNulo, votosEx) values (?,?,?,0,0,0,0,0,0)\";\r\n\r\n conn = new ConexaoDAO().conexaodao();\r\n\r\n try {\r\n \r\n pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getCriar_nome_usuario());\r\n pstm.setString(2, objusuariodto.getCriar_email_usuario());\r\n pstm.setString(3, objusuariodto.getCriar_senha_usuario());\r\n\r\n pstm.execute();\r\n pstm.close();\r\n\r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (cadastrar)\" + error);\r\n }\r\n }\r\n \r\n \r\n \r\n \r\n \r\n public ResultSet checarUsuarioExistente(UsuarioDTO objusuariodto) {\r\n conn = new ConexaoDAO().conexaodao();\r\n \r\n try {\r\n String sql = \"select * from usuarios where email = ?\";\r\n \r\n PreparedStatement pstm = conn.prepareStatement(sql);\r\n pstm.setString(1, objusuariodto.getCriar_email_usuario());\r\n \r\n ResultSet rs = pstm.executeQuery();\r\n return rs;\r\n \r\n } catch (SQLException error) {\r\n JOptionPane.showMessageDialog(null, \"UsuarioDAO (checagem): \" + error);\r\n return null;\r\n }\r\n }\r\n \r\n}\r" } ]
import br.edu.bancodedados.User; import br.edu.bancodedados.UsuarioDAO; import javax.swing.JOptionPane; import java.sql.ResultSet; import java.sql.SQLException;
3,078
jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botaoEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoForgotPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(101, 101, 101) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(196, 196, 196) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jButton1))) .addGap(1, 1, 1) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoEntrar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoForgotPassword) .addContainerGap(14, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 490, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents String emailUser = null; private void campoSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campoSenhaActionPerformed private void botaoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarActionPerformed Cadastro cadastro = new Cadastro(); cadastro.setVisible(true); dispose(); }//GEN-LAST:event_botaoCadastrarActionPerformed private void botaoEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEntrarActionPerformed /* 1- Coleta os dados de email e senha, por exemplo: email: [email protected] pass: 12345678 2- verificar no banco de dados se a combinaçao de email e senha existem na tabela da base de dados 3- se verdadeiro, deixe o usuario entrar na urna se falso, mostre: email ou senha incorretos */ String emailx, senhax; emailx = campoNome.getText(); senhax = campoSenha.getText(); if(emailx.equals("") || senhax.equals("")){ JOptionPane.showMessageDialog(null, "Preencha todos os campos!!"); }else{ try { String email = campoNome.getText(); String senha = campoSenha.getText(); Urna user = new Urna();
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package br.edu.view; /** * * @author Alunos */ public class Login extends javax.swing.JFrame { /** * Creates new form Login */ public Login() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); campoNome = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); campoSenha = new javax.swing.JPasswordField(); jLabel4 = new javax.swing.JLabel(); botaoCadastrar = new javax.swing.JButton(); botaoEntrar = new javax.swing.JButton(); botaoForgotPassword = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Login"); setResizable(false); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setMaximumSize(new java.awt.Dimension(513, 645)); jPanel1.setMinimumSize(new java.awt.Dimension(513, 645)); jLabel1.setBackground(new java.awt.Color(0, 0, 0)); jLabel1.setFont(new java.awt.Font("Gill Sans MT", 1, 36)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 0, 0)); jLabel1.setText("Login"); campoNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campoNomeActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N jLabel2.setForeground(new java.awt.Color(153, 153, 153)); jLabel2.setText("Email"); campoSenha.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { campoSenhaActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(153, 153, 153)); jLabel4.setText("Senha"); botaoCadastrar.setBackground(new java.awt.Color(0, 0, 0)); botaoCadastrar.setFont(new java.awt.Font("Leelawadee UI", 1, 18)); // NOI18N botaoCadastrar.setForeground(new java.awt.Color(255, 255, 255)); botaoCadastrar.setText("Cadastre-se "); botaoCadastrar.setBorder(new javax.swing.border.MatteBorder(null)); botaoCadastrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoCadastrarActionPerformed(evt); } }); botaoEntrar.setBackground(new java.awt.Color(0, 0, 0)); botaoEntrar.setFont(new java.awt.Font("Leelawadee UI", 1, 24)); // NOI18N botaoEntrar.setForeground(new java.awt.Color(255, 255, 255)); botaoEntrar.setText("Entrar"); botaoEntrar.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); botaoEntrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoEntrarActionPerformed(evt); } }); botaoForgotPassword.setBackground(new java.awt.Color(255, 255, 255)); botaoForgotPassword.setForeground(new java.awt.Color(102, 102, 102)); botaoForgotPassword.setText("Esqueceu sua Senha? Clique aqui"); botaoForgotPassword.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoForgotPasswordActionPerformed(evt); } }); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/resourses/topo login.png"))); // NOI18N jLabel5.setText("jLabel5"); jButton1.setBackground(new java.awt.Color(255, 255, 255)); jButton1.setForeground(new java.awt.Color(0, 0, 0)); jButton1.setText("Ajuda?"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(83, 83, 83) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botaoEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoForgotPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(101, 101, 101) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 282, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(196, 196, 196) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel1)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addComponent(jButton1))) .addGap(1, 1, 1) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoEntrar, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(botaoForgotPassword) .addContainerGap(14, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 490, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents String emailUser = null; private void campoSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoSenhaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_campoSenhaActionPerformed private void botaoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarActionPerformed Cadastro cadastro = new Cadastro(); cadastro.setVisible(true); dispose(); }//GEN-LAST:event_botaoCadastrarActionPerformed private void botaoEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEntrarActionPerformed /* 1- Coleta os dados de email e senha, por exemplo: email: [email protected] pass: 12345678 2- verificar no banco de dados se a combinaçao de email e senha existem na tabela da base de dados 3- se verdadeiro, deixe o usuario entrar na urna se falso, mostre: email ou senha incorretos */ String emailx, senhax; emailx = campoNome.getText(); senhax = campoSenha.getText(); if(emailx.equals("") || senhax.equals("")){ JOptionPane.showMessageDialog(null, "Preencha todos os campos!!"); }else{ try { String email = campoNome.getText(); String senha = campoSenha.getText(); Urna user = new Urna();
User objusuariodto = new User();
0
2023-10-10 18:25:35+00:00
4k
zlhy7/ldDecrypt
src/main/java/top/zlhy7/listener/FileListener.java
[ { "identifier": "MonitoredFileService", "path": "src/main/java/top/zlhy7/service/MonitoredFileService.java", "snippet": "@Slf4j\n@Service\npublic class MonitoredFileService {\n /**\n * 被监控的文件目录\n * 放置到此目录的所有文件会解密并放置到同级的 \"${monitoredFilePath}_解密\"目录中\n */\n @Value(\"${monitoredPath}\")\n private String monitoredFilePath;\n /**\n * 解密后目录\n */\n @Value(\"${monitoredDecryptPath}\")\n private String monitoredDecryptPath;\n /**\n * 被监控的文件目录 file对象\n */\n public static File monitoredFilePathObj;\n /**\n * 解密文件目录 file对象\n */\n public static File monitoredDecryptPathObj;\n\n @PostConstruct\n public void init(){\n log.info(\"绿盾文件解密监控目录:{}\",monitoredFilePath);\n log.info(\"初始化相关目录对象\");\n monitoredFilePathObj = new File(monitoredFilePath);\n monitoredDecryptPathObj = new File(monitoredDecryptPath);\n if (!monitoredFilePathObj.exists()){\n monitoredFilePathObj.mkdirs();\n }\n if (!monitoredDecryptPathObj.exists()){\n monitoredDecryptPathObj.mkdirs();\n }\n //开启监听指定目录\n startFileWatch();\n }\n /**\n * 开启监听指定目录\n * @return\n * @author 任勇 on 2020/8/26 10:07\n */\n public void startFileWatch(){\n log.info(\"***************开启监听指定目录 {}***************\",monitoredFilePath);\n // 监控目录\n String rootDir = monitoredFilePath;\n // 轮询间隔 5 秒\n long interval = TimeUnit.SECONDS.toMillis(1);\n // 创建过滤器·文件夹\n IOFileFilter directories = FileFilterUtils.and(\n FileFilterUtils.directoryFileFilter(),\n HiddenFileFilter.VISIBLE);\n // 创建过滤器·文件\n IOFileFilter filter = FileFilterUtils.or(directories, FileFilterUtils.fileFileFilter());\n // 使用过滤器\n FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);\n //添加监听器\n observer.addListener(new FileListener());\n //创建文件变化监听器\n FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);\n // 开始监控\n try{\n monitor.start();\n log.info(\"***************监控中***************\");\n }catch (Exception e){\n log.error(\"异常处理 {}\",e.getMessage());\n }\n }\n\n /**\n * 解密\n * @param file\n *\n */\n public void decrypt(File file) throws Exception {\n System.out.printf(\"开始解密:%s,原文件大小:%d\\n\",file.getAbsolutePath(),file.length());\n //region 解密目标地址\n String path2 = file.getAbsolutePath().replace(\"\\\\\",\"/\")\n .replace(\"//\",\"/\")\n .replace(monitoredFilePath,\"\");\n File decryptFile = new File(monitoredDecryptPath + path2);\n if (!decryptFile.getParentFile().exists()) {\n decryptFile.getParentFile().mkdirs();\n }\n //endregion\n try (InputStream fis = new FileInputStream(file)){\n Files.copy(fis,Paths.get(decryptFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);\n System.out.printf(\"解密完毕:%s\\n\",decryptFile.getAbsolutePath());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n decrypt(file,monitoredFilePath,monitoredDecryptPath);\n }\n /**\n * 手动指定解密目录\n * @param monitoredFilePath 监控目录\n * @param monitoredDecryptPath 解密文件生成目录\n * @return\n * @author renyong on 2023/9/22 12:10\n */\n public void decrypt(String monitoredFilePath,String monitoredDecryptPath) throws Exception {\n // 手动解密\n MonitoredFileService monitoredFileService = new MonitoredFileService();\n monitoredFileService.monitoredFilePath = \"E:/download/\";\n monitoredFileService.monitoredDecryptPath = \"E:/fileWatch_解密/\";\n Files.walk(Paths.get(monitoredFilePath))\n .map(Path::toFile)\n .filter(file -> !file.isDirectory())\n .forEach(file -> {\n try {\n monitoredFileService.decrypt(file,monitoredFilePath,monitoredDecryptPath);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n });\n }\n /**\n * 手动指定解密目录\n * @param file 文件目录\n * @param monitoredFilePath 监控目录\n * @param monitoredDecryptPath 解密文件生成目录\n * @return\n * @author renyong on 2023/9/22 12:10\n */\n public void decrypt(File file,String monitoredFilePath,String monitoredDecryptPath){\n System.out.printf(\"开始解密:%s,原文件大小:%d\\n\",file.getAbsolutePath(),file.length());\n //region 解密目标地址\n String path2 = file.getAbsolutePath().replace(\"\\\\\",\"/\")\n .replace(\"//\",\"/\")\n .replace(monitoredFilePath,\"\");\n File decryptFile = new File(monitoredDecryptPath + path2);\n if (!decryptFile.getParentFile().exists()) {\n decryptFile.getParentFile().mkdirs();\n }\n //endregion\n try (InputStream fis = new FileInputStream(file)){\n Files.copy(fis,Paths.get(decryptFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);\n System.out.printf(\"解密完毕:%s\\n\",decryptFile.getAbsolutePath());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n public static void main(String[] args) throws Exception {\n // 手动解密\n MonitoredFileService monitoredFileService = new MonitoredFileService();\n // 注意文件夹末尾必须带“/”\n monitoredFileService.decrypt(\"E:/deskTop/日常工作添加/需求文档/\",\"E:/fileWatch_解密/\");\n }\n}" }, { "identifier": "SpringUtils", "path": "src/main/java/top/zlhy7/util/SpringUtils.java", "snippet": "@Component\npublic final class SpringUtils implements BeanFactoryPostProcessor\n{\n /** Spring应用上下文环境 */\n private static ConfigurableListableBeanFactory beanFactory;\n\n @Override\n public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException\n {\n SpringUtils.beanFactory = beanFactory;\n }\n\n /**\n * 获取对象\n *\n * @param name\n * @return Object 一个以所给名字注册的bean的实例\n * @throws BeansException\n *\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getBean(String name) throws BeansException\n {\n return (T) beanFactory.getBean(name);\n }\n\n /**\n * 获取类型为requiredType的对象\n *\n * @param clz\n * @return\n * @throws BeansException\n *\n */\n public static <T> T getBean(Class<T> clz) throws BeansException\n {\n T result = (T) beanFactory.getBean(clz);\n return result;\n }\n\n /**\n * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true\n *\n * @param name\n * @return boolean\n */\n public static boolean containsBean(String name)\n {\n return beanFactory.containsBean(name);\n }\n\n /**\n * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)\n *\n * @param name\n * @return boolean\n * @throws NoSuchBeanDefinitionException\n *\n */\n public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException\n {\n return beanFactory.isSingleton(name);\n }\n\n /**\n * @param name\n * @return Class 注册对象的类型\n * @throws NoSuchBeanDefinitionException\n *\n */\n public static Class<?> getType(String name) throws NoSuchBeanDefinitionException\n {\n return beanFactory.getType(name);\n }\n\n /**\n * 如果给定的bean名字在bean定义中有别名,则返回这些别名\n *\n * @param name\n * @return\n * @throws NoSuchBeanDefinitionException\n *\n */\n public static String[] getAliases(String name) throws NoSuchBeanDefinitionException\n {\n return beanFactory.getAliases(name);\n }\n\n /**\n * 获取aop代理对象\n * \n * @param invoker\n * @return\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getAopProxy(T invoker)\n {\n return (T) AopContext.currentProxy();\n }\n}" } ]
import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.springframework.stereotype.Component; import top.zlhy7.service.MonitoredFileService; import top.zlhy7.util.SpringUtils; import java.io.File;
2,387
package top.zlhy7.listener; /** * @author 任勇 * @date 2020/8/26 9:43 * @description 文件变化监听器 */ @Component @Slf4j public class FileListener extends FileAlterationListenerAdaptor { /** * 监控文件 */
package top.zlhy7.listener; /** * @author 任勇 * @date 2020/8/26 9:43 * @description 文件变化监听器 */ @Component @Slf4j public class FileListener extends FileAlterationListenerAdaptor { /** * 监控文件 */
private MonitoredFileService monitoredFileService = SpringUtils.getBean(MonitoredFileService.class);
1
2023-10-12 10:23:05+00:00
4k
openGemini/opengemini-client-java
opengemini-client-jdk/src/main/java/io/opengemini/client/jdk/OpenGeminiJdkClient.java
[ { "identifier": "Address", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/Address.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Address {\n /**\n * Host service ip or domain.\n */\n private String host;\n /**\n * Port exposed service port.\n */\n private int port;\n}" }, { "identifier": "OpenGeminiException", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/OpenGeminiException.java", "snippet": "public class OpenGeminiException extends Exception {\n private static final int DEFAULT_STATUS_CODE = 500;\n\n private final int statusCode;\n\n public OpenGeminiException(Throwable t) {\n super(t);\n statusCode = DEFAULT_STATUS_CODE;\n }\n\n public OpenGeminiException(String message) {\n this(message, DEFAULT_STATUS_CODE);\n }\n\n public OpenGeminiException(String message, int statusCode) {\n super(message);\n this.statusCode = statusCode;\n }\n}" }, { "identifier": "Query", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/Query.java", "snippet": "@AllArgsConstructor\n@Getter\n@Setter\npublic class Query {\n /*\n * the query command\n */\n private String command;\n\n /*\n * the database name of the query command using\n */\n private String database;\n\n /*\n * the rp name of the query command using\n */\n private String retentionPolicy;\n\n public Query(String command){\n this.command = command;\n };\n}" }, { "identifier": "QueryResult", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/QueryResult.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class QueryResult {\n private List<SeriesResult> results;\n\n private String error;\n}" }, { "identifier": "SslContextUtil", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/SslContextUtil.java", "snippet": "public class SslContextUtil {\n\n public static SSLContext buildSSLContextFromJks(String keyStorePath,\n String keyStorePassword,\n String trustStorePath,\n String trustStorePassword,\n boolean disableSslVerify) {\n try {\n // Load the key store\n KeyStore keyStore = KeyStore.getInstance(\"JKS\");\n try (FileInputStream keyStoreFile = new FileInputStream(keyStorePath)) {\n keyStore.load(keyStoreFile, keyStorePassword.toCharArray());\n }\n\n // Set up key manager factory to use our key store\n String defaultKeyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();\n KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultKeyAlgorithm);\n keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());\n\n // Load the trust store, if specified\n TrustManagerFactory trustManagerFactory = null;\n if (trustStorePath != null) {\n KeyStore trustStore = KeyStore.getInstance(\"JKS\");\n try (FileInputStream trustStoreFile = new FileInputStream(trustStorePath)) {\n trustStore.load(trustStoreFile, trustStorePassword.toCharArray());\n }\n\n // Set up trust manager factory to use our trust store\n trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n trustManagerFactory.init(trustStore);\n }\n\n // Set up SSL context\n SSLContext sslContext = SSLContext.getInstance(\"TLSv1.3\");\n\n TrustManager[] trustManagers;\n if (disableSslVerify) {\n trustManagers = new TrustManager[] { new InsecureTrustManager() };\n } else if (trustManagerFactory != null) {\n trustManagers = trustManagerFactory.getTrustManagers();\n } else {\n trustManagers = null;\n }\n\n // Set up SSL parameters\n sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());\n\n if (disableSslVerify) {\n sslContext.getDefaultSSLParameters().setEndpointIdentificationAlgorithm(null);\n }\n\n return sslContext;\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }\n}" }, { "identifier": "TlsConfig", "path": "opengemini-client-api/src/main/java/io/opengemini/client/api/TlsConfig.java", "snippet": "@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TlsConfig {\n public String keyStorePath;\n\n @ToString.Exclude\n public String keyStorePassword;\n\n public String trustStorePath;\n\n @ToString.Exclude\n public String trustStorePassword;\n\n public boolean tlsVerificationDisabled;\n}" }, { "identifier": "OpenGeminiCommon", "path": "opengemini-client-jdk/src/main/java/io/opengemini/client/jdk/common/OpenGeminiCommon.java", "snippet": "public class OpenGeminiCommon {\n private static final ObjectMapper objectMapper = new ObjectMapper();\n public static <T> T converJson2Bean(String json, Class<T> cls) throws JsonProcessingException {\n return objectMapper.readValue(json, cls);\n }\n}" } ]
import com.fasterxml.jackson.core.JsonProcessingException; import io.opengemini.client.api.Address; import io.opengemini.client.api.OpenGeminiException; import io.opengemini.client.api.Query; import io.opengemini.client.api.QueryResult; import io.opengemini.client.api.SslContextUtil; import io.opengemini.client.api.TlsConfig; import io.opengemini.client.jdk.common.OpenGeminiCommon; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger;
1,727
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig(); builder = builder.sslContext(SslContextUtil.buildSSLContextFromJks( tlsConfig.getKeyStorePath(), tlsConfig.getKeyStorePassword(), tlsConfig.getTrustStorePath(), tlsConfig.getTrustStorePassword(), tlsConfig.isTlsVerificationDisabled())); httpPrefix = "https://"; } else { httpPrefix = "http://"; } for (Address address : conf.getAddresses()) { this.serverUrls.add(httpPrefix + address.getHost() + ":" + address.getPort()); } this.client = builder.build(); } public String encodeUtf8(String str) { return URLEncoder.encode(str, StandardCharsets.UTF_8); } private URI buildUri(String url, String command) throws URISyntaxException { // avoid multi-thread conflict, realize simple round-robin int idx = prevIndex.addAndGet(1); idx = idx % this.conf.getAddresses().size(); return buildUri(idx, url, command); } private URI buildUri(int index, String url, String command) throws URISyntaxException { StringBuilder sb = new StringBuilder(this.serverUrls.get(index)) .append(url) .append("?q=") .append(encodeUtf8(command)); return new URI(sb.toString()); }
package io.opengemini.client.jdk; public class OpenGeminiJdkClient { private final Configuration conf; private final List<String> serverUrls = new ArrayList<>(); private final HttpClient client; private final AtomicInteger prevIndex = new AtomicInteger(0); public OpenGeminiJdkClient(Configuration conf) { this.conf = conf; HttpClient.Builder builder = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1); String httpPrefix; if (conf.isTlsEnabled()) { TlsConfig tlsConfig = conf.getTlsConfig(); builder = builder.sslContext(SslContextUtil.buildSSLContextFromJks( tlsConfig.getKeyStorePath(), tlsConfig.getKeyStorePassword(), tlsConfig.getTrustStorePath(), tlsConfig.getTrustStorePassword(), tlsConfig.isTlsVerificationDisabled())); httpPrefix = "https://"; } else { httpPrefix = "http://"; } for (Address address : conf.getAddresses()) { this.serverUrls.add(httpPrefix + address.getHost() + ":" + address.getPort()); } this.client = builder.build(); } public String encodeUtf8(String str) { return URLEncoder.encode(str, StandardCharsets.UTF_8); } private URI buildUri(String url, String command) throws URISyntaxException { // avoid multi-thread conflict, realize simple round-robin int idx = prevIndex.addAndGet(1); idx = idx % this.conf.getAddresses().size(); return buildUri(idx, url, command); } private URI buildUri(int index, String url, String command) throws URISyntaxException { StringBuilder sb = new StringBuilder(this.serverUrls.get(index)) .append(url) .append("?q=") .append(encodeUtf8(command)); return new URI(sb.toString()); }
public CompletableFuture<QueryResult> query(Query query) throws URISyntaxException {
2
2023-10-12 09:08:55+00:00
4k
lilmayu/java-discord-oauth2-api
src/test/java/dev/mayuna/discord/oauth/DiscordOAuthTest.java
[ { "identifier": "DiscordAccessToken", "path": "src/main/java/dev/mayuna/discord/oauth/entities/DiscordAccessToken.java", "snippet": "@Getter\npublic class DiscordAccessToken extends DiscordApiResponse {\n\n /**\n * Gets the time when the access token was fetched, e.g., when the {@link DiscordAccessToken} instance was created.\n *\n * @return The time in milliseconds.\n */\n private final @Getter long fetchedAt = System.currentTimeMillis();\n\n private @SerializedName(\"access_token\") String accessToken;\n private @SerializedName(\"token_type\") String tokenType;\n private @SerializedName(\"expires_in\") long expiresInSeconds;\n private @SerializedName(\"refresh_token\") String refreshToken;\n private String scope;\n\n /**\n * Determines if access token are expired\n *\n * @return boolean\n */\n public boolean isAccessTokenExpired() {\n return System.currentTimeMillis() - fetchedAt > expiresInSeconds * 1000;\n }\n\n /**\n * Gets the scopes returned by the Discord API.<br> If the scope is null or empty, then an empty array will be returned.\n *\n * @return The scopes.\n */\n public String[] getScopes() {\n if (scope == null || scope.isEmpty()) {\n return new String[]{};\n }\n\n return scope.split(\" \");\n }\n}" }, { "identifier": "DiscordOAuthServerMock", "path": "src/test/java/dev/mayuna/discord/oauth/server/DiscordOAuthServerMock.java", "snippet": "@Getter\npublic class DiscordOAuthServerMock {\n\n private final int port;\n private final Javalin javalin;\n\n private String clientId;\n private String clientSecret;\n private String code;\n private String redirectUrl;\n private String scope;\n\n private String lastAccessToken;\n private String lastRefreshToken;\n\n /**\n * Creates a new DiscordOAuthServerMock instance.\n *\n * @param clientId The client ID.\n * @param clientSecret The client secret.\n * @param code The code.\n * @param redirectUrl The redirect URL.\n */\n public DiscordOAuthServerMock(String clientId, String clientSecret, String code, String redirectUrl, String scope) {\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n this.code = code;\n this.redirectUrl = redirectUrl;\n this.scope = scope;\n\n this.port = new Random().nextInt(65535 - 1024) + 1024;\n this.javalin = Javalin.create();\n }\n\n /**\n * Gets the URL of the server.\n *\n * @return The URL of the server.\n */\n public String getUrl() {\n return \"http://localhost:\" + port;\n }\n\n /**\n * Starts the server.\n */\n public void start() {\n prepareEndpoints();\n\n javalin.start(\"localhost\", port);\n }\n\n /**\n * Stops the server.\n */\n public void stop() {\n javalin.stop();\n }\n\n private void prepareEndpoints() {\n javalin.post(\"/oauth2/token\", ctx -> {\n String contentType = ctx.header(\"Content-Type\");\n\n if (contentType == null || !contentType.equals(\"application/x-www-form-urlencoded\")) {\n processCtxAsError(ctx, \"invalid_request (contentType is null or is not application/x-www-form-urlencoded)\", null);\n return;\n }\n\n String body = ctx.body();\n\n String[] bodyParts = body.split(\"&\");\n\n String requestClientId = null;\n String requestClientSecret = null;\n String requestCode = null;\n String requestRedirectUrl = null;\n String grantType = null;\n String refreshToken = null;\n\n for (String bodyPart : bodyParts) {\n String[] bodyPartParts = bodyPart.split(\"=\");\n\n String key = bodyPartParts[0];\n String value = bodyPartParts[1];\n\n switch (key) {\n case \"client_id\":\n requestClientId = value;\n break;\n case \"client_secret\":\n requestClientSecret = value;\n break;\n case \"code\":\n requestCode = value;\n break;\n case \"redirect_uri\":\n requestRedirectUrl = value;\n break;\n case \"grant_type\":\n grantType = value;\n break;\n case \"refresh_token\":\n refreshToken = value;\n break;\n }\n }\n\n if (requestClientId == null || !requestClientId.equals(clientId)) {\n processCtxAsError(ctx, \"invalid_client (client_id is missing or unknown)\", \"Invalid client ID.\");\n return;\n }\n\n if (requestClientSecret == null || !requestClientSecret.equals(clientSecret)) {\n processCtxAsError(ctx, \"invalid_client (client_secret is missing or unknown\", \"Invalid client secret.\");\n return;\n }\n\n if (grantType == null) {\n processCtxAsError(ctx, \"unsupported_grant_type (grant_type is missing)\", null);\n return;\n }\n\n switch (grantType) {\n case \"authorization_code\":\n if (requestRedirectUrl == null || !requestRedirectUrl.equals(redirectUrl)) {\n processCtxAsError(ctx, \"invalid_request (redirect_url is missing or unknown)\", \"Invalid redirect URL.\");\n return;\n }\n\n if (requestCode == null || !requestCode.equals(code)) {\n processCtxAsError(ctx, \"invalid_request (code is missing or unknown)\", \"Invalid code.\");\n return;\n }\n\n lastAccessToken = UUID.randomUUID().toString().replace(\"-\", \"\").substring(0, 32);\n lastRefreshToken = UUID.randomUUID().toString().replace(\"-\", \"\").substring(0, 32);\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"access_token\", lastAccessToken);\n jsonObject.addProperty(\"token_type\", \"Bearer\");\n jsonObject.addProperty(\"expires_in\", 604800);\n jsonObject.addProperty(\"refresh_token\", lastRefreshToken);\n jsonObject.addProperty(\"scope\", scope);\n\n ctx.status(200);\n ctx.contentType(\"application/json\");\n ctx.result(jsonObject.toString());\n break;\n case \"refresh_token\":\n if (lastRefreshToken == null) {\n processCtxAsError(ctx, \"invalid_request (lastRefreshToken is null (you must fetch tokens before refreshing them!))\", \"Invalid refresh token.\");\n return;\n }\n\n if (refreshToken == null || !refreshToken.equals(lastRefreshToken)) {\n processCtxAsError(ctx, \"invalid_request (refresh_token is missing or unknown)\", \"Invalid refresh token.\");\n return;\n }\n\n lastAccessToken = UUID.randomUUID().toString().replace(\"-\", \"\").substring(0, 32);\n lastRefreshToken = UUID.randomUUID().toString().replace(\"-\", \"\").substring(0, 32);\n\n JsonObject jsonObjectRefresh = new JsonObject();\n jsonObjectRefresh.addProperty(\"access_token\", lastAccessToken);\n jsonObjectRefresh.addProperty(\"token_type\", \"Bearer\");\n jsonObjectRefresh.addProperty(\"expires_in\", 604800);\n jsonObjectRefresh.addProperty(\"refresh_token\", lastRefreshToken);\n jsonObjectRefresh.addProperty(\"scope\", scope);\n\n ctx.status(200);\n ctx.contentType(\"application/json\");\n ctx.result(jsonObjectRefresh.toString());\n break;\n default:\n processCtxAsError(ctx, \"unsupported_grant_type (grant_type is not authorization_code or refresh_token)\", null);\n break;\n }\n });\n\n javalin.post(\"/oauth2/token/revoke\", ctx -> {\n String contentType = ctx.header(\"Content-Type\");\n\n if (contentType == null || !contentType.equals(\"application/x-www-form-urlencoded\")) {\n processCtxAsError(ctx, \"invalid_request (contentType is null or is not application/x-www-form-urlencoded)\", null);\n return;\n }\n\n String body = ctx.body();\n\n String[] bodyParts = body.split(\"&\");\n String requestClientId = null;\n String requestClientSecret = null;\n String requestToken = null;\n\n for (String bodyPart : bodyParts) {\n String[] bodyPartParts = bodyPart.split(\"=\");\n\n String key = bodyPartParts[0];\n String value = bodyPartParts[1];\n\n switch (key) {\n case \"client_id\":\n requestClientId = value;\n break;\n case \"client_secret\":\n requestClientSecret = value;\n break;\n case \"token\":\n requestToken = value;\n break;\n }\n }\n\n if (requestClientId == null || !requestClientId.equals(clientId)) {\n processCtxAsError(ctx, \"invalid_client (client_id is missing or unknown)\", \"Invalid client ID.\");\n return;\n }\n\n if (requestClientSecret == null || !requestClientSecret.equals(clientSecret)) {\n processCtxAsError(ctx, \"invalid_client (client_secret is missing or unknown\", \"Invalid client secret.\");\n return;\n }\n\n if (requestToken == null || !requestToken.equals(lastAccessToken)) {\n processCtxAsError(ctx, \"unsupported_grant_type (requestToken is missing or unknown (check if access_token is passed))\", null);\n return;\n }\n\n lastAccessToken = null;\n lastRefreshToken = null;\n\n ctx.status(200);\n ctx.contentType(\"application/json\");\n ctx.result(\"{}\");\n });\n }\n\n private void processCtxAsError(Context ctx, String error, String errorDescription) {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"error\", error);\n jsonObject.addProperty(\"error_description\", errorDescription);\n\n ctx.status(400);\n ctx.contentType(\"application/json\");\n ctx.result(jsonObject.toString());\n }\n}" }, { "identifier": "AssertStringArraysEquals", "path": "src/test/java/dev/mayuna/discord/Utils.java", "snippet": "public static void AssertStringArraysEquals(String[] a, String[] b) {\n if (a.length != b.length) {\n Assertions.fail(\"Arrays are not the same length (a.length != b.length: \" + a.length + \" != \" + b.length + \")\");\n }\n\n for (int i = 0; i < a.length; i++) {\n if (!a[i].equals(b[i])) {\n Assertions.fail(\"Arrays are not the same (a[i] != b[i]: \" + a[i] + \" != \" + b[i] + \")\");\n }\n }\n}" } ]
import dev.mayuna.discord.oauth.entities.DiscordAccessToken; import dev.mayuna.discord.oauth.server.DiscordOAuthServerMock; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Random; import java.util.UUID; import static dev.mayuna.discord.Utils.AssertStringArraysEquals;
2,891
package dev.mayuna.discord.oauth; public class DiscordOAuthTest { private static final String clientId = new Random().nextLong() + ""; private static final String clientSecret = UUID.randomUUID().toString().replace("-", ""); private static final String redirectUrl = "https://localhost:8080"; private static final String code = UUID.randomUUID().toString().replace("-", ""); private static final String state = UUID.randomUUID().toString(); private static final String[] scopes = new String[]{"identify", "guilds"}; private static DiscordOAuthServerMock serverMock; private static DiscordOAuth discordOAuth; @BeforeAll public static void prepare() { serverMock = new DiscordOAuthServerMock(clientId, clientSecret, code, redirectUrl, String.join(" ", Arrays.asList(scopes))); serverMock.start(); DiscordApplication application = new DiscordApplication.Builder() .withApiUrl(serverMock.getUrl()) .withClientId(clientId) .withClientSecret(clientSecret) .withRedirectUrl(redirectUrl) .withScopes(scopes) .build(); discordOAuth = new DiscordOAuth(application); } @AfterAll public static void stop() { serverMock.stop(); } @Test public void testNullInConstructor() { Assertions.assertThrows(NullPointerException.class, () -> new DiscordOAuth(null)); } @Test public void testFetchingWithNulls() { Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.fetchAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.refreshAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.revokeTokens(null).sendAsync().join()); } @Test public void fetchTokens() {
package dev.mayuna.discord.oauth; public class DiscordOAuthTest { private static final String clientId = new Random().nextLong() + ""; private static final String clientSecret = UUID.randomUUID().toString().replace("-", ""); private static final String redirectUrl = "https://localhost:8080"; private static final String code = UUID.randomUUID().toString().replace("-", ""); private static final String state = UUID.randomUUID().toString(); private static final String[] scopes = new String[]{"identify", "guilds"}; private static DiscordOAuthServerMock serverMock; private static DiscordOAuth discordOAuth; @BeforeAll public static void prepare() { serverMock = new DiscordOAuthServerMock(clientId, clientSecret, code, redirectUrl, String.join(" ", Arrays.asList(scopes))); serverMock.start(); DiscordApplication application = new DiscordApplication.Builder() .withApiUrl(serverMock.getUrl()) .withClientId(clientId) .withClientSecret(clientSecret) .withRedirectUrl(redirectUrl) .withScopes(scopes) .build(); discordOAuth = new DiscordOAuth(application); } @AfterAll public static void stop() { serverMock.stop(); } @Test public void testNullInConstructor() { Assertions.assertThrows(NullPointerException.class, () -> new DiscordOAuth(null)); } @Test public void testFetchingWithNulls() { Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.fetchAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.refreshAccessToken(null).sendAsync().join()); Assertions.assertThrows(NullPointerException.class, () -> discordOAuth.revokeTokens(null).sendAsync().join()); } @Test public void fetchTokens() {
DiscordAccessToken token = discordOAuth.fetchAccessToken(code).sendAsync().join();
0
2023-10-10 15:10:53+00:00
4k
ljjy1/discord-mj-java
src/main/java/com/github/dmj/bot/DiscordBot.java
[ { "identifier": "DiscordAccountProperties", "path": "src/main/java/com/github/dmj/autoconfigure/DiscordAccountProperties.java", "snippet": "@Data\npublic class DiscordAccountProperties {\n\n /**\n * 用户key 自己定义不重复即可(用于切换用户调用接口)\n */\n private String userKey;\n /**\n * 用户token\n */\n private String userToken;\n\n /**\n * discord账号\n */\n private String user;\n\n /**\n * discord密码\n */\n private String password;\n\n /**\n * 当前用户下应用机器人token\n */\n private String botToken;\n /**\n * 服务器ID\n */\n private String guildId;\n /**\n * 频道ID\n */\n private String channelId;\n /**\n * 并发执行任务大小\n */\n private int concurSize = 3;\n /**\n * 等待队列大小\n */\n private int waitSize = 10;\n}" }, { "identifier": "DiscordProxyProperties", "path": "src/main/java/com/github/dmj/autoconfigure/DiscordProxyProperties.java", "snippet": "@Data\npublic class DiscordProxyProperties {\n\n /**\n * 是否开启代理\n */\n private Boolean enable = Boolean.FALSE;\n /**\n * 代理IP\n */\n private String address;\n /**\n * 代理端口\n */\n private Integer port;\n\n\n public Boolean isEnable() {\n return enable;\n }\n}" }, { "identifier": "MjMsgStatus", "path": "src/main/java/com/github/dmj/enums/MjMsgStatus.java", "snippet": "@Getter\npublic enum MjMsgStatus {\n\n START(\"START\",\"首次触发\"),\n UPDATE(\"UPDATE\",\"更新\"),\n ERR(\"ERR\",\"错误停止\"),\n END(\"END\",\"生成结束\"),\n\n ;\n /**\n * 状态\n */\n private String status;\n\n private String msg;\n\n\n MjMsgStatus(String type, String msg) {\n this.status = type;\n this.msg = msg;\n }\n}" }, { "identifier": "MjMsg", "path": "src/main/java/com/github/dmj/model/MjMsg.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class MjMsg implements Serializable {\n\n\n /**\n * 账号key\n */\n private String userKey;\n\n /**\n * 消息ID\n */\n private String msgId;\n\n /**\n * 业务唯一ID\n */\n private Integer triggerId;\n\n /**\n * 服务器ID\n */\n private String guildId;\n\n /**\n * 服务器名称\n */\n private String guildName;\n\n /**\n * 频道ID\n */\n private String channelId;\n\n /**\n * 频道名称\n */\n private String channelName;\n\n\n /**\n * 附件\n */\n private Attachment attachment;\n\n\n /**\n * 消息内容\n */\n private String content;\n\n\n /**\n * 引用的消息ID 通过哪个消息参考生成的新的内容\n */\n private String referenceMsgId;\n\n\n /**\n * 消息状态\n */\n private MjMsgStatus status;\n\n\n /**\n * 指令列表 用户确认图片可以有哪些执行\n */\n private List<List<ComponentDetail>> components;\n\n\n @Data\n @Accessors(chain = true)\n public static class Attachment{\n\n /**\n * 附件id\n */\n private String id;\n /**\n * 附件url\n */\n private String url;\n /**\n * 附件代理Url\n */\n private String proxyUrl;\n\n /**\n * 附件名称\n */\n private String fileName;\n\n /**\n * 附件类型\n */\n private String contentType;\n\n /**\n * 附件描述\n */\n private String description;\n\n /**\n * 附件大小\n */\n private Integer size;\n\n /**\n * 附件高度\n */\n private Integer height;\n\n /**\n * 附件宽度\n */\n private Integer width;\n }\n\n\n @Data\n public static class ComponentDetail{\n private String id;\n private String label;\n }\n}" }, { "identifier": "MessageQueue", "path": "src/main/java/com/github/dmj/queue/MessageQueue.java", "snippet": "@Slf4j\npublic class MessageQueue {\n\n private static final LinkedBlockingQueue<MjMsg> msgQueue = new LinkedBlockingQueue<>(300);\n\n private MessageQueue() {\n }\n\n private static class MessageEmbedQueueHolder{\n private static final MessageQueue INSTANCE = new MessageQueue();\n }\n\n\n public static MessageQueue getInstance(){\n return MessageEmbedQueueHolder.INSTANCE;\n }\n\n /**\n * 获取并移除队首元素 如果队列为空则会阻塞\n */\n public MjMsg takeMsg(){\n try {\n return msgQueue.take();\n } catch (InterruptedException e) {\n log.error(e.getMessage(),e);\n }\n return null;\n }\n\n /**\n * 往队列添加元素 如果队列满了 会阻塞等待\n * @param msg\n */\n public void putMsg(MjMsg msg){\n msgQueue.offer(msg);\n }\n\n}" } ]
import cn.hutool.core.collection.CollUtil; import cn.hutool.json.JSONUtil; import com.github.dmj.autoconfigure.DiscordAccountProperties; import com.github.dmj.autoconfigure.DiscordProxyProperties; import com.github.dmj.enums.MjMsgStatus; import com.github.dmj.model.MjMsg; import com.github.dmj.queue.MessageQueue; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.neovisionaries.ws.client.WebSocketFactory; import lombok.extern.slf4j.Slf4j; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.buttons.Button; import okhttp3.OkHttpClient; import org.jetbrains.annotations.NotNull; import org.springframework.util.DigestUtils; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,819
package com.github.dmj.bot; /** * @author ljjy1 * @classname DiscordBot * @description discord机器人 * @date 2023/10/11 13:38 */ @Slf4j public class DiscordBot extends ListenerAdapter { private final DiscordAccountProperties discordAccountProperties; private final Cache<String, String> cache; /** * 初始化机器人 */
package com.github.dmj.bot; /** * @author ljjy1 * @classname DiscordBot * @description discord机器人 * @date 2023/10/11 13:38 */ @Slf4j public class DiscordBot extends ListenerAdapter { private final DiscordAccountProperties discordAccountProperties; private final Cache<String, String> cache; /** * 初始化机器人 */
public DiscordBot(DiscordAccountProperties discordAccountProperties, DiscordProxyProperties discordProxyProperties) throws Exception {
1
2023-10-11 01:12:39+00:00
4k
weizen-w/Educational-Management-System-BE
src/test/java/de/ait/ems/services/ModulesServiceTest.java
[ { "identifier": "CoursesDtoTest", "path": "src/test/java/de/ait/ems/dto/CoursesDtoTest.java", "snippet": "@DisplayName(\"Courses DTO is works:\")\n@DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class)\npublic class CoursesDtoTest {\n\n public static final Long ID = 1L;\n public static final String NAME = \"Fullstack developer\";\n public static final Boolean IS_ARCHIVED = false;\n\n @Nested\n @DisplayName(\"CourseDto:\")\n public class TestsCourseDto {\n\n @Test\n public void get_course_dto() {\n CourseDto courseDtoNoArg = new CourseDto();\n Course course = new Course(ID, NAME, IS_ARCHIVED);\n CourseDto courseDto = CourseDto.from(course);\n\n Assertions.assertNotNull(courseDtoNoArg);\n Assertions.assertEquals(ID, courseDto.getId());\n Assertions.assertEquals(NAME, courseDto.getName());\n Assertions.assertEquals(IS_ARCHIVED, courseDto.getArchived());\n }\n\n @Test\n public void get_courses_dto() {\n Course course1 = new Course(ID, NAME, IS_ARCHIVED);\n Course course2 = new Course(ID, NAME, IS_ARCHIVED);\n List<Course> courses = new ArrayList<>();\n courses.add(course1);\n courses.add(course2);\n List<CourseDto> courseDtoList = CourseDto.from(courses);\n\n Assertions.assertEquals(2, courseDtoList.size());\n }\n }\n\n @Nested\n @DisplayName(\"NewCourseDto:\")\n public class TestsNewCourseDto {\n\n @Test\n public void get_new_course_dto() {\n NewCourseDto newCourseDto = new NewCourseDto();\n newCourseDto.setName(NAME);\n\n Assertions.assertEquals(NAME, newCourseDto.getName());\n }\n }\n\n @Nested\n @DisplayName(\"UpdateCourseDto:\")\n public class TestsUpdateCourseDto {\n\n @Test\n public void get_update_course_dto() {\n UpdateCourseDto updateCourseDtoNoArg = new UpdateCourseDto();\n UpdateCourseDto updateCourseDto = new UpdateCourseDto(NAME, IS_ARCHIVED);\n\n Assertions.assertNotNull(updateCourseDtoNoArg);\n Assertions.assertEquals(NAME, updateCourseDto.getName());\n Assertions.assertEquals(IS_ARCHIVED, updateCourseDto.getArchived());\n }\n }\n}" }, { "identifier": "ModuleDto", "path": "src/main/java/de/ait/ems/dto/ModuleDto.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Schema(name = \"Module\", description = \"Lesson module\")\npublic class ModuleDto {\n\n @Schema(description = \"Module ID\", example = \"1\")\n private Long id;\n @Schema(description = \"Module name\", example = \"Backend\")\n private String name;\n @Schema(description = \"Module is archived\", example = \"false\")\n private Boolean archived;\n\n public static ModuleDto from(Module module) {\n return ModuleDto.builder()\n .id(module.getId())\n .name(module.getName())\n .archived(module.getArchived())\n .build();\n }\n\n public static List<ModuleDto> from(List<Module> modules) {\n return modules\n .stream()\n .map(ModuleDto::from)\n .collect(Collectors.toList());\n }\n}" }, { "identifier": "ModulesDtoTest", "path": "src/test/java/de/ait/ems/dto/ModulesDtoTest.java", "snippet": "@DisplayName(\"Modules DTO is works:\")\n@DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class)\npublic class ModulesDtoTest {\n\n public static final Long ID = 1L;\n public static final String NAME = \"Backend\";\n public static final Boolean IS_ARCHIVED = false;\n\n @Nested\n @DisplayName(\"ModuleDto:\")\n public class TestsModuleDto {\n\n @Test\n public void get_module_dto() {\n ModuleDto moduleDtoNoArg = new ModuleDto();\n Module module = new Module(ID, NAME, IS_ARCHIVED);\n ModuleDto moduleDto = ModuleDto.from(module);\n\n Assertions.assertNotNull(moduleDtoNoArg);\n Assertions.assertEquals(ID, moduleDto.getId());\n Assertions.assertEquals(NAME, moduleDto.getName());\n Assertions.assertEquals(IS_ARCHIVED, moduleDto.getArchived());\n }\n\n @Test\n public void get_modules_dto() {\n Module module1 = new Module(ID, NAME, IS_ARCHIVED);\n Module module2 = new Module(ID, NAME, IS_ARCHIVED);\n List<Module> modules = new ArrayList<>();\n modules.add(module1);\n modules.add(module2);\n List<ModuleDto> moduleDtoList = ModuleDto.from(modules);\n\n Assertions.assertEquals(2, moduleDtoList.size());\n }\n }\n\n @Nested\n @DisplayName(\"NewModuleDto:\")\n public class TestsNewModuleDto {\n\n @Test\n public void get_new_module_dto() {\n NewModuleDto newModuleDto = new NewModuleDto();\n newModuleDto.setName(NAME);\n\n Assertions.assertEquals(NAME, newModuleDto.getName());\n }\n }\n\n @Nested\n @DisplayName(\"UpdateModuleDto:\")\n public class TestsUpdateModuleDto {\n\n @Test\n public void get_update_module_dto() {\n UpdateModuleDto updateModuleDtoNoArg = new UpdateModuleDto();\n UpdateModuleDto updateModuleDto = new UpdateModuleDto(NAME, IS_ARCHIVED);\n\n Assertions.assertNotNull(updateModuleDtoNoArg);\n Assertions.assertEquals(NAME, updateModuleDto.getName());\n Assertions.assertEquals(IS_ARCHIVED, updateModuleDto.getArchived());\n }\n }\n}" }, { "identifier": "NewModuleDto", "path": "src/main/java/de/ait/ems/dto/NewModuleDto.java", "snippet": "@Data\n@Schema(name = \"New module\")\npublic class NewModuleDto {\n\n @Schema(description = \"Module name\", example = \"Backend\")\n @NotNull(message = \"Must not be null\")\n @NotBlank(message = \"Must not be blank\")\n @NotEmpty(message = \"Must not be empty\")\n @Size(max = 50, message = \"Size must be in the range from 0 to 50\")\n private String name;\n}" }, { "identifier": "UpdateModuleDto", "path": "src/main/java/de/ait/ems/dto/UpdateModuleDto.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Schema(name = \"Update module\", description = \"Data for updating the module\")\npublic class UpdateModuleDto {\n\n @Pattern(regexp = \"^$|^(?!\\\\s+$).+\", message = \"Must not be blank or contain only spaces\")\n @Size(min = 1, max = 50, message = \"Size must be in the range from 1 to 50\")\n @Schema(description = \"Module name\", example = \"Backend\")\n private String name;\n @Schema(description = \"Module is archived\", example = \"true\")\n private Boolean archived;\n}" } ]
import de.ait.ems.dto.CoursesDtoTest; import de.ait.ems.dto.ModuleDto; import de.ait.ems.dto.ModulesDtoTest; import de.ait.ems.dto.NewModuleDto; import de.ait.ems.dto.UpdateModuleDto; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayNameGeneration; import org.junit.jupiter.api.DisplayNameGenerator; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.jdbc.Sql;
2,025
package de.ait.ems.services; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @SpringBootTest @Nested @DisplayName("Module service is works:") @DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ActiveProfiles("test") public class ModulesServiceTest { @Autowired private ModulesService modulesService; @Test @Sql(scripts = "/sql/data.sql") public void add_module() { NewModuleDto newModuleDto = new NewModuleDto(); newModuleDto.setName(ModulesDtoTest.NAME); ModuleDto moduleDto = modulesService.addModule(newModuleDto); Assertions.assertNotNull(moduleDto); Assertions.assertEquals(5, moduleDto.getId()); Assertions.assertEquals(newModuleDto.getName(), moduleDto.getName()); Assertions.assertEquals(false, moduleDto.getArchived()); } @Test @Sql(scripts = "/sql/data.sql") public void get_modules() { List<ModuleDto> modules = modulesService.getModules(); Assertions.assertNotNull(modules); Assertions.assertEquals(4, modules.size()); } @Test @Sql(scripts = "/sql/data.sql") public void update_module() {
package de.ait.ems.services; /** * 01/11/2023 EducationalManagementSystemBE * * @author Wladimir Weizen */ @SpringBootTest @Nested @DisplayName("Module service is works:") @DisplayNameGeneration(value = DisplayNameGenerator.ReplaceUnderscores.class) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) @ActiveProfiles("test") public class ModulesServiceTest { @Autowired private ModulesService modulesService; @Test @Sql(scripts = "/sql/data.sql") public void add_module() { NewModuleDto newModuleDto = new NewModuleDto(); newModuleDto.setName(ModulesDtoTest.NAME); ModuleDto moduleDto = modulesService.addModule(newModuleDto); Assertions.assertNotNull(moduleDto); Assertions.assertEquals(5, moduleDto.getId()); Assertions.assertEquals(newModuleDto.getName(), moduleDto.getName()); Assertions.assertEquals(false, moduleDto.getArchived()); } @Test @Sql(scripts = "/sql/data.sql") public void get_modules() { List<ModuleDto> modules = modulesService.getModules(); Assertions.assertNotNull(modules); Assertions.assertEquals(4, modules.size()); } @Test @Sql(scripts = "/sql/data.sql") public void update_module() {
UpdateModuleDto updateModuleDto = new UpdateModuleDto(ModulesDtoTest.NAME,
4
2023-10-07 16:00:02+00:00
4k
wukong121/eights-reservation
src/main/java/com/bupt/eights/controller/LoginController.java
[ { "identifier": "LoginRequest", "path": "src/main/java/com/bupt/eights/dto/request/LoginRequest.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Data\npublic class LoginRequest {\n \n @NotBlank String userName;\n \n @NotBlank String password;\n \n @NotBlank boolean remember;\n}" }, { "identifier": "RegisterRequest", "path": "src/main/java/com/bupt/eights/dto/request/RegisterRequest.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Data\npublic class RegisterRequest {\n \n @NotBlank String email;\n \n @NotBlank String gender;\n \n String nickName;\n \n @NotBlank String password;\n \n @NotBlank String phone;\n \n @NotBlank String prefix;\n \n @NotBlank String userName;\n \n}" }, { "identifier": "LoginResponse", "path": "src/main/java/com/bupt/eights/dto/response/LoginResponse.java", "snippet": "@Data\npublic class LoginResponse implements Serializable {\n \n @Data\n @AllArgsConstructor\n public static class User {\n \n String userName;\n \n String password;\n \n }\n \n private User user;\n \n private String token;\n}" }, { "identifier": "AuthorityRole", "path": "src/main/java/com/bupt/eights/model/AuthorityRole.java", "snippet": "public enum AuthorityRole {\n ROLE_STUDENT,\n ROLE_ADMIN;\n}" }, { "identifier": "User", "path": "src/main/java/com/bupt/eights/model/User.java", "snippet": "@Data\n@JsonInclude(JsonInclude.Include.NON_NULL)\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class User {\n\n private String userId;\n \n private String userName;\n \n private String email;\n \n private String phoneNumber;\n \n private String gender;\n \n private String nickName;\n \n private String password;\n\n private String createTime;\n \n private AuthorityRole authority;\n}" }, { "identifier": "HttpResponse", "path": "src/main/java/com/bupt/eights/dto/response/HttpResponse.java", "snippet": "@Data\npublic class HttpResponse<T> implements Serializable {\n \n private String status; // success,failed\n \n private int code; // 0 success;-1 failed\n \n private String message;\n \n public T data;\n \n}" }, { "identifier": "AuthenticateService", "path": "src/main/java/com/bupt/eights/service/AuthenticateService.java", "snippet": "public interface AuthenticateService {\n \n User createUser(RegisterRequest registerRequest);\n \n HttpResponse<LoginResponse> authenticate(LoginRequest loginRequest);\n \n}" }, { "identifier": "JwtTokenUtils", "path": "src/main/java/com/bupt/eights/utils/JwtTokenUtils.java", "snippet": "public class JwtTokenUtils {\n \n // expiration time set to 3600s (1 hour)\n private static final long EXPIRATION = 3600L;\n \n // expiration time set to 7 days after select remember me\n private static final long EXPIRATION_REMEMBER = 604800L;\n \n private static final String SECRET = \"eightsjwtsecret\";\n \n private static final String ISSUER = \"com.bupt.eights\";\n \n private static final String ROLE_CLAIMS = \"role\";\n \n public static String createToken(String userName, AuthorityRole role, Boolean isRememberMe) {\n long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;\n Map<String, Object> claimMap = new HashMap<>();\n claimMap.put(ROLE_CLAIMS, role);\n return Jwts.builder().signWith(SignatureAlgorithm.HS256, SECRET).setClaims(claimMap).setIssuer(ISSUER)\n .setSubject(userName).setIssuedAt(new Date())\n .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000)).compact();\n }\n \n public static String getUserName(String token) {\n return getTokenBody(token).getSubject();\n }\n \n public static AuthorityRole getUserRole(String token) {\n return (AuthorityRole) getTokenBody(token).get(ROLE_CLAIMS);\n }\n \n public static boolean isExpired(String token) {\n try {\n return getTokenBody(token).getExpiration().before(new Date());\n } catch (ExpiredJwtException e) {\n return true;\n }\n }\n \n private static Claims getTokenBody(String token) {\n return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();\n }\n}" }, { "identifier": "URLConstant", "path": "src/main/java/com/bupt/eights/utils/URLConstant.java", "snippet": "public class URLConstant {\n \n public static final String LOGIN_URL = \"/api/v1\";\n \n}" } ]
import com.bupt.eights.dto.request.LoginRequest; import com.bupt.eights.dto.request.RegisterRequest; import com.bupt.eights.dto.response.LoginResponse; import com.bupt.eights.model.AuthorityRole; import com.bupt.eights.model.User; import com.bupt.eights.dto.response.HttpResponse; import com.bupt.eights.service.AuthenticateService; import com.bupt.eights.utils.JwtTokenUtils; import com.bupt.eights.utils.URLConstant; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
1,685
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST) public HttpResponse<String> createUser(@RequestBody @Valid RegisterRequest request) { User user = loginService.createUser(request); HttpResponse<String> response = new HttpResponse<>(); response.setStatus("success"); response.setCode(HttpStatus.OK.value()); response.setMessage("注册成功"); response.setData(user.getUserId()); log.info("用户" + user.getUserName() + "注册成功"); return response; } @CrossOrigin @ResponseBody @RequestMapping(value = "/oauth/token", method = RequestMethod.POST) public HttpResponse<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest) { HttpResponse<LoginResponse> response = loginService.authenticate(loginRequest); if (response.getCode() != 200) { return response; }
package com.bupt.eights.controller; @Slf4j @Controller @RequestMapping(URLConstant.LOGIN_URL) public class LoginController { @Autowired AuthenticateService loginService; private String redirectByRole(HttpServletRequest request) { if (request.isUserInRole(AuthorityRole.ROLE_ADMIN.toString())) { return "redirect:/admin"; } if (request.isUserInRole(AuthorityRole.ROLE_STUDENT.toString())) { return "redirect:/students/home"; } return ""; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String showLogin(@ModelAttribute(value = "user") User user, HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "login"; } return path; } @RequestMapping(value = "/login-success", method = RequestMethod.GET) public String loginSuccess(HttpServletRequest request) { String path = redirectByRole(request); if (path.isEmpty()) { return "redirect:/home"; } return path; } @RequestMapping(value = "/login-failed", method = RequestMethod.GET) public String loginFailed(@ModelAttribute(value = "user") User user, Model model) { model.addAttribute("fail", true); return "login"; } @CrossOrigin @ResponseBody @RequestMapping(value = "/register", method = RequestMethod.POST) public HttpResponse<String> createUser(@RequestBody @Valid RegisterRequest request) { User user = loginService.createUser(request); HttpResponse<String> response = new HttpResponse<>(); response.setStatus("success"); response.setCode(HttpStatus.OK.value()); response.setMessage("注册成功"); response.setData(user.getUserId()); log.info("用户" + user.getUserName() + "注册成功"); return response; } @CrossOrigin @ResponseBody @RequestMapping(value = "/oauth/token", method = RequestMethod.POST) public HttpResponse<LoginResponse> login(@RequestBody @Valid LoginRequest loginRequest) { HttpResponse<LoginResponse> response = loginService.authenticate(loginRequest); if (response.getCode() != 200) { return response; }
String jwtToken = JwtTokenUtils.createToken(loginRequest.getUserName(), AuthorityRole.ROLE_STUDENT,
7
2023-10-11 09:34:23+00:00
4k
aws-samples/amazon-vpc-lattice-secure-apis
lambda/src/main/java/cloud/heeki/DemoController.java
[ { "identifier": "Customer", "path": "lambda/src/main/java/cloud/heeki/lib/Customer.java", "snippet": "public class Customer {\n public UUID uuid;\n public String given_name;\n public String family_name;\n public String birthdate;\n public String email;\n public String phone_number;\n public boolean phone_number_verified;\n\n public Customer(String given_name, String family_name, String birthdate, String email, String phone_number, boolean phone_number_verified) {\n this.uuid = UUID.randomUUID();\n this.given_name = given_name;\n this.family_name = family_name;\n this.birthdate = birthdate;\n this.email = email;\n this.phone_number = phone_number;\n this.phone_number_verified = phone_number_verified;\n }\n\n public Customer(String json) {\n System.out.format(\"Customer(String): %s\\n\", json);\n Gson g = new Gson();\n Customer c = g.fromJson(json, Customer.class);\n this.uuid = c.uuid != null ? c.uuid : UUID.randomUUID();\n this.given_name = c.given_name;\n this.family_name = c.family_name;\n this.birthdate = c.birthdate;\n this.email = c.email;\n this.phone_number = c.phone_number;\n this.phone_number_verified = c.phone_number_verified;\n }\n\n public Customer(Map<String, AttributeValue> item) {\n System.out.format(\"Customer(Map): %s\\n\", item.get(\"uuid\"));\n Gson g = new Gson();\n Map<String, String> map = new HashMap<>();\n for (Map.Entry<String, AttributeValue> entry : item.entrySet()) {\n map.put(entry.getKey(), entry.getValue().s());\n }\n Customer c = new Customer(g.toJson(map));\n this.uuid = c.uuid;\n this.given_name = c.given_name;\n this.family_name = c.family_name;\n this.birthdate = c.birthdate;\n this.email = c.email;\n this.phone_number = c.phone_number;\n this.phone_number_verified = c.phone_number_verified;\n }\n\n public String toString() {\n Gson g = new Gson();\n return g.toJson(this);\n }\n\n public Map<String, Object> toHashMap() {\n Map<String, Object> map = new HashMap<>();\n for (Field field : this.getClass().getDeclaredFields()) {\n try {\n map.put(field.getName(), field.get(this));\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n return map;\n }\n\n public Map<String, AttributeValue> toDynamoMap() {\n Map<String, AttributeValue> map = new HashMap<>();\n for (Field field : this.getClass().getDeclaredFields()) {\n try {\n String value = field.get(this).toString();\n AttributeValue attribute = AttributeValue.builder().s(value).build();\n map.put(field.getName(), attribute);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n return map;\n }\n}" }, { "identifier": "DynamoAdapter", "path": "lambda/src/main/java/cloud/heeki/lib/DynamoAdapter.java", "snippet": "public class DynamoAdapter {\n private AwsCredentialsProvider credentials;\n private Region region;\n private DynamoDbClient client;\n private String table;\n private Gson g;\n\n public DynamoAdapter(String table) {\n // WebIdentityTokenFileCredentialsProvider doesn't expose a method to set the HTTP client, so need to set this at the system level\n System.setProperty(\"software.amazon.awssdk.http.service.impl\", \"software.amazon.awssdk.http.urlconnection.UrlConnectionSdkHttpService\");\n\n String awsProfile = System.getenv(\"AWS_PROFILE\");\n String awsRegion = System.getenv(\"AWS_REGION\");\n String awsAccessKey = System.getenv(\"AWS_ACCESS_KEY_ID\");\n String awsSecretKey = System.getenv(\"AWS_SECRET_ACCESS_KEY\");\n String awsRoleArn = System.getenv(\"AWS_ROLE_ARN\");\n String awsWebIdentityToken = System.getenv(\"AWS_WEB_IDENTITY_TOKEN_FILE\");\n String awsContainerCredentialsFull = System.getenv(\"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI\");\n String awsContainerCredentialsRelative = System.getenv(\"AWS_CONTAINER_CREDENTIALS_FULL_URI\");\n String awsContainerAuthToken = System.getenv(\"AWS_CONTAINER_AUTHORIZATION_TOKEN\");\n\n this.g = new Gson();\n // when credentials are available via environment variables\n if (awsAccessKey != null && awsSecretKey != null) {\n this.credentials = EnvironmentVariableCredentialsProvider.create();\n // when operating in EKS\n } else if (awsRoleArn != null && awsWebIdentityToken != null) {\n this.credentials = WebIdentityTokenFileCredentialsProvider.create();\n // when operating in ECS\n } else if (awsContainerCredentialsFull != null) {\n this.credentials = ContainerCredentialsProvider.builder().build();\n // when using SnapStart since EnvironmentVariableCredentialsProvider is not supported\n } else if (awsContainerCredentialsRelative != null && awsContainerAuthToken != null) {\n this.credentials = ContainerCredentialsProvider.builder().build();\n // when operating locally with a cli profile\n } else {\n this.credentials = ProfileCredentialsProvider.create();\n }\n this.table = table;\n this.region = (awsRegion != null) ? Region.of(awsRegion) : Region.US_EAST_1;\n this.client = DynamoDbClient.builder()\n .credentialsProvider(credentials)\n .region(region)\n .httpClient(UrlConnectionHttpClient.builder().build())\n .build();\n }\n\n public ScanIterable scan() {\n ScanRequest request = ScanRequest.builder()\n .tableName(this.table)\n .build();\n ScanIterable response = client.scanPaginator(request);\n return response;\n }\n\n public String put(Customer c) {\n PutItemRequest request = PutItemRequest.builder()\n .tableName(this.table)\n .item(c.toDynamoMap())\n .build();\n Map<String, String> payload = new HashMap<>();\n payload.put(\"table\", this.table);\n try {\n PutItemResponse response = client.putItem(request);\n payload.put(\"request_id\", response.responseMetadata().requestId());\n System.out.println(this.g.toJson(payload));\n } catch (ResourceNotFoundException e) {\n payload.put(\"error\", \"table not found\");\n System.err.println(this.g.toJson(payload));\n System.exit(1);\n } catch (DynamoDbException e) {\n payload.put(\"error\", e.getMessage());\n System.err.println(this.g.toJson(payload));\n System.exit(1);\n }\n return this.g.toJson(payload);\n }\n\n public String delete(String uuid) {\n Map<String, AttributeValue> keymap = new HashMap<>();\n keymap.put(\"uuid\", AttributeValue.builder().s(uuid).build());\n DeleteItemRequest request = DeleteItemRequest.builder()\n .tableName(this.table)\n .key(keymap)\n .build();\n Map<String, String> payload = new HashMap<>();\n payload.put(\"table\", this.table);\n payload.put(\"uuid\", uuid);\n try {\n client.deleteItem(request);\n payload.put(\"status\", \"deleted\");\n } catch (ResourceNotFoundException e) {\n payload.put(\"error\", \"table not found\");\n System.err.println(this.g.toJson(payload));\n System.exit(1);\n } catch (DynamoDbException e) {\n payload.put(\"error\", e.getMessage());\n System.err.println(this.g.toJson(payload));\n System.exit(1);\n }\n return this.g.toJson(payload);\n }\n}" }, { "identifier": "PropertiesLoader", "path": "lambda/src/main/java/cloud/heeki/lib/PropertiesLoader.java", "snippet": "public class PropertiesLoader {\n public static Properties loadProperties(String file) {\n Properties props = new Properties();\n try {\n InputStream input = PropertiesLoader.class\n .getClassLoader()\n .getResourceAsStream(file);\n props.load(input);\n input.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return props;\n }\n}" } ]
import cloud.heeki.lib.Customer; import cloud.heeki.lib.DynamoAdapter; import cloud.heeki.lib.PropertiesLoader; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Properties; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;
1,995
package cloud.heeki; @RestController public class DemoController { private Properties props = PropertiesLoader.loadProperties("application.properties");
package cloud.heeki; @RestController public class DemoController { private Properties props = PropertiesLoader.loadProperties("application.properties");
private ArrayList<Customer> customers = new ArrayList<Customer>();
0
2023-10-13 17:38:23+00:00
4k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/entities/Big_Bloated.java
[ { "identifier": "RIGHT", "path": "src/utilz/Constants.java", "snippet": "public static final int RIGHT = 2;" }, { "identifier": "EnemyConstants", "path": "src/utilz/Constants.java", "snippet": "public static class EnemyConstants {\n\tpublic static final int CARNIVOROUS = 0;\n\tpublic static final int TURTLE = 1;\n\tpublic static final int BIG_BLOATED = 2;\n\n\t\t\n\tpublic static final int IDLE = 0;\n\tpublic static final int RUNNING = 1;\n\tpublic static final int ATTACK = 2;\n\tpublic static final int HIT = 3;\n\tpublic static final int DEAD = 4;\n\n\t\t\n\tpublic static final int CARNIVOROUS_WIDTH_DEFAULT = 96;\n\tpublic static final int CARNIVOROUS_HEIGHT_DEFAULT = 98;\n\tpublic static final int CARNIVOROUS_WIDTH = (int)(CARNIVOROUS_WIDTH_DEFAULT * Game.SCALE);\n\tpublic static final int CARNIVOROUS_HEIGHT = (int)(CARNIVOROUS_HEIGHT_DEFAULT * Game.SCALE);\n\tpublic static final int CARNIVOROUS_DRAWOFFSET_X = (int)(68 * Game.SCALE);\n\tpublic static final int CARNIVOROUS_DRAWOFFSET_Y = (int)(65 * Game.SCALE);\n\t\t\n\tpublic static final int TURTLE_WIDTH_DEFAULT = 72;\n\tpublic static final int TURTLE_HEIGHT_DEFAULT = 74;\n\tpublic static final int TURTLE_WIDTH = (int)(TURTLE_WIDTH_DEFAULT * Game.SCALE);\n\tpublic static final int TURTLE_HEIGHT = (int)(TURTLE_HEIGHT_DEFAULT * Game.SCALE);\n\tpublic static final int TURTLE_DRAWOFFSET_X = (int)(68 * Game.SCALE);\n\tpublic static final int TURTLE_DRAWOFFSET_Y = (int)(15 * Game.SCALE);\n\t\t\n\t\t\n\tpublic static final int BIG_BLOATED_WIDTH_DEFAULT = 72;\n\tpublic static final int BIG_BLOATED_HEIGHT_DEFAULT = 74;\n\tpublic static final int BIG_BLOATED_WIDTH = (int)(BIG_BLOATED_WIDTH_DEFAULT * Game.SCALE);\n\tpublic static final int BIG_BLOATED_HEIGHT = (int)(BIG_BLOATED_HEIGHT_DEFAULT * Game.SCALE);\n\tpublic static final int BIG_BLOATED_DRAWOFFSET_X = (int)(68 * Game.SCALE);\n\tpublic static final int BIG_BLOATED_DRAWOFFSET_Y = (int)(15 * Game.SCALE);\n\t\t\n\n\t\t\n\tpublic static int GetSpriteAmount(int enemy_type, int enemy_state) {\n\t\t\t\n\t\tswitch(enemy_type) {\n\t\tcase CARNIVOROUS:\n\t\t\tswitch(enemy_state) {\n\t\t\tcase IDLE:\n\t\t\t\treturn 6;\n\t\t\tcase RUNNING:\n\t\t\t\treturn 6;\n\t\t\tcase ATTACK:\n\t\t\t\treturn 6;\n\t\t\tcase HIT:\n\t\t\t\treturn 4;\n\t\t\tcase DEAD:\n\t\t\t\treturn 6;\n\t\t\t}\n\t\tcase TURTLE:\n\t\t\tswitch(enemy_state) {\n\t\t\tcase IDLE:\n\t\t\t\treturn 4;\n\t\t\tcase RUNNING:\n\t\t\t\treturn 4;\n\t\t\tcase ATTACK:\n\t\t\t\treturn 4;\n\t\t\tcase HIT:\n\t\t\t\treturn 2;\n\t\t\tcase DEAD:\n\t\t\t\treturn 4;\n\t\t\t}\n\t\tcase BIG_BLOATED:\n\t\t\tswitch(enemy_state) {\n\t\t\tcase IDLE:\n\t\t\t\treturn 4;\n\t\t\tcase RUNNING:\n\t\t\t\treturn 6;\n\t\t\tcase ATTACK:\n\t\t\t\treturn 6;\n\t\t\tcase HIT:\n\t\t\t\treturn 2;\n\t\t\tcase DEAD:\n\t\t\t\treturn 4;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t\t\n\t\treturn 0;\n\t}\n\tpublic static int GetMaxHealth(int enemy_type) {\n\t\tswitch (enemy_type) {\n\t\tcase CARNIVOROUS:\n\t\t\treturn 20;\n\t\tcase TURTLE:\n\t\t\treturn 15;\n\t\tcase BIG_BLOATED:\n\t\t\treturn 45;\n\t\tdefault:\n\t\t\treturn 1;\n\t\t}\n\t}\n\t\t\n\tpublic static int GetEnemyDmg(int enemy_type) {\n\t\tswitch (enemy_type) {\n\t\tcase CARNIVOROUS:\n\t\t\treturn 10;\n\t\tcase TURTLE:\n\t\t\treturn 5;\n\t\tcase BIG_BLOATED:\n\t\t\treturn 15;\n\t\tdefault:\n\t\t\treturn 0;\n\t\t}\n\t}\n\t\t\n}" }, { "identifier": "Game", "path": "src/main/Game.java", "snippet": "public class Game implements Runnable {\n\n\tprivate GameWindow gameWindow;\n\tprivate GamePanel gamePanel;\n\tprivate Thread gameThread;\n\tprivate final int FPS_SET = 120;\n\tprivate final int UPS_SET = 200;\n\n\tprivate Playing playing;\n\tprivate Menu menu;\n\tprivate GameOptions gameOptions;\n\tprivate AudioOptions audioOptions;\n\tprivate AudioPlayer audioPlayer;\n\t\n\tpublic final static int TILES_DEFAULT_SIZE = 32;\n\tpublic final static float SCALE = 1f;\n\tpublic final static int TILES_IN_WIDTH = 26;\n\tpublic final static int TILES_IN_HEIGHT = 14;\n\tpublic final static int TILES_SIZE = (int) (TILES_DEFAULT_SIZE * SCALE);\n\tpublic final static int GAME_WIDTH = TILES_SIZE * TILES_IN_WIDTH;\n\tpublic final static int GAME_HEIGHT = TILES_SIZE * TILES_IN_HEIGHT;\n\n\tpublic Game() {\n\t\t\n\t\tLoadSave.GetAllLevels();\n\t\tinitClasses();\n\n\t\tgamePanel = new GamePanel(this);\n\t\tgameWindow = new GameWindow(gamePanel);\n\t\tgamePanel.setFocusable(true);\n\t\tgamePanel.requestFocus();\n\n\t\tstartGameLoop();\n\t}\n\n\tprivate void initClasses() {\n\t\taudioOptions = new AudioOptions(this);\n\t\taudioPlayer = new AudioPlayer();\n\t\tmenu = new Menu(this);\n\t\tplaying = new Playing(this);\n\t\tgameOptions = new GameOptions(this);\n\t}\n\n\tprivate void startGameLoop() {\n\t\tgameThread = new Thread(this);\n\t\tgameThread.start();\n\t}\n\n\tpublic void update() {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tmenu.update();\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tplaying.update();\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgameOptions.update();\n\t\t\t\tbreak;\n\t\t\tcase QUIT:\n\t\t\tdefault:\n\t\t\t\tSystem.exit(0);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tpublic void render(Graphics g) {\n\t\tswitch (Gamestate.state) {\n\t\t\tcase MENU:\n\t\t\t\tmenu.draw(g);\n\t\t\t\tbreak;\n\t\t\tcase PLAYING:\n\t\t\t\tplaying.draw(g);\n\t\t\t\tbreak;\n\t\t\tcase OPTIONS:\n\t\t\t\tgameOptions.draw(g);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void run() {\n\n\t\tdouble timePerFrame = 1000000000.0 / FPS_SET;\n\t\tdouble timePerUpdate = 1000000000.0 / UPS_SET;\n\n\t\tlong previousTime = System.nanoTime();\n\n\t\tint frames = 0;\n\t\tint updates = 0;\n\t\tlong lastCheck = System.currentTimeMillis();\n\n\t\tdouble deltaU = 0;\n\t\tdouble deltaF = 0;\n\n\t\twhile (true) {\n\t\t\tlong currentTime = System.nanoTime();\n\n\t\t\tdeltaU += (currentTime - previousTime) / timePerUpdate;\n\t\t\tdeltaF += (currentTime - previousTime) / timePerFrame;\n\t\t\tpreviousTime = currentTime;\n\n\t\t\tif (deltaU >= 1) {\n\t\t\t\tupdate();\n\t\t\t\tupdates++;\n\t\t\t\tdeltaU--;\n\t\t\t}\n\n\t\t\tif (deltaF >= 1) {\n\t\t\t\tgamePanel.repaint();\n\t\t\t\tframes++;\n\t\t\t\tdeltaF--;\n\t\t\t}\n\n\t\t\tif (System.currentTimeMillis() - lastCheck >= 1000) {\n\t\t\t\tlastCheck = System.currentTimeMillis();\n\t\t\t\tSystem.out.println(\"FPS: \" + frames + \" | UPS: \" + updates);\n\t\t\t\tframes = 0;\n\t\t\t\tupdates = 0;\n\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void windowFocusLost() {\n\t\tif (Gamestate.state == Gamestate.PLAYING)\n\t\t\tplaying.getPlayer().resetDirBooleans();\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\tpublic Playing getPlaying() {\n\t\treturn playing;\n\t}\n\tpublic GameOptions getGameOptions() {\n\t\treturn gameOptions;\n\t}\n\tpublic AudioOptions getAudioOptions() {\n\t\treturn audioOptions;\n\t}\n\tpublic AudioPlayer getAudioPlayer() {\n\t\treturn audioPlayer;\n\t}\n}" } ]
import static utilz.Constants.Directions.RIGHT; import static utilz.Constants.EnemyConstants.*; import java.awt.geom.Rectangle2D; import main.Game;
2,109
package entities; public class Big_Bloated extends Enemy { private int attackBoxOffsetX; public Big_Bloated(float x, float y) { super(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED); initHitbox(22,30); initAttackBox(); } private void initAttackBox() {
package entities; public class Big_Bloated extends Enemy { private int attackBoxOffsetX; public Big_Bloated(float x, float y) { super(x, y, BIG_BLOATED_WIDTH, BIG_BLOATED_HEIGHT, BIG_BLOATED); initHitbox(22,30); initAttackBox(); } private void initAttackBox() {
attackBox = new Rectangle2D.Float(x,y,(int)(82 * Game.SCALE),(int)(30 * Game.SCALE));
2
2023-10-07 12:07:45+00:00
4k
yc-huang/bsdb
src/main/java/tech/bsdb/bench/UringAsyncFileBench.java
[ { "identifier": "NativeFileIO", "path": "src/main/java/tech/bsdb/io/NativeFileIO.java", "snippet": "public class NativeFileIO {\n public static final int PAGE_SIZE = 4096;\n public static int openForReadDirect(String file) throws IOException {\n return open(file, Native.O_DIRECT | Native.O_RDONLY | Native.O_NOATIME);\n }\n\n public static int open(String file, int flags) throws IOException {\n int fd = Native.open(file, flags);\n if (fd < 0) {\n throw new IOException(\"Error opening \" + file);\n } else {\n return fd;\n }\n }\n\n public static void close(int fd) {\n Native.close(fd);\n }\n\n public static int getBufferSizeForUnalignedRead(int readLen){\n return alignToPageSize(readLen + PAGE_SIZE);\n }\n\n /**\n * align to OS page size\n *\n * @param size\n * @return aligned size\n */\n public static int alignToPageSize(int size) {\n int r = size / PAGE_SIZE * PAGE_SIZE;\n if (r < size) r += PAGE_SIZE;\n return r;\n }\n\n public static ByteBuffer allocateAlignedBuffer(int size){\n return allocateAlignedBuffer(size, Common.MEMORY_ALIGN);\n //return ByteBuffer.allocateDirect(size + Common.MEMORY_ALIGN*2).alignedSlice(Common.MEMORY_ALIGN);\n }\n\n protected static ByteBuffer allocateAlignedBuffer(int size, int alignTo) {\n long addr = Native.allocateAligned(size, alignTo);\n if (addr > 0) {\n return UnsafeUtil.newDirectByteBuffer(addr, size, addr);\n } else {\n throw new RuntimeException(\"alloc failed\");\n }\n }\n\n public static void freeBuffer(ByteBuffer buffer) {\n //Native.free(((DirectBuffer) buffer).address());\n }\n\n public static long readAlignedTo512(int fd, long position, ByteBuffer dst, int len) throws IOException {\n return readAligned(fd, position, dst, len, -512L);\n }\n\n public static long readAlignedTo4096(int fd, long position, ByteBuffer dst, int len) throws IOException {\n return readAligned(fd, position, dst, len, -4096L);\n }\n\n private static long readAligned(int fd, long position, ByteBuffer dst, int len, long lenAlignMask) throws IOException {\n long alignedPos = position & -4096L; //position align to 4096\n int offset = (int) (position - alignedPos);\n int readLen = len + offset;\n int alignedLen = (int) (readLen & lenAlignMask); //read len align to\n if (alignedLen < readLen) alignedLen += (int) (-lenAlignMask);\n if (dst.remaining() < alignedLen)\n throw new IOException(\"no enough space in buffer to contain \" + alignedLen + \", space remain \" + dst.remaining() + \" \" + dst.position());\n\n long rLen = Native.pread(fd, alignedPos, ((DirectBuffer) dst).address(), alignedLen);\n if (rLen < 0) {\n throw new IOException(\"read return error:\" + rLen);\n } else {\n dst.limit((int) rLen);\n dst.position(offset);\n return rLen;\n }\n }\n}" }, { "identifier": "UringAsyncFileReader", "path": "src/main/java/tech/bsdb/io/UringAsyncFileReader.java", "snippet": "public class UringAsyncFileReader extends BaseAsyncFileReader {\n IOUring[] rings;\n long[][][] rss;\n Logger logger = LoggerFactory.getLogger(UringAsyncFileReader.class);\n\n public UringAsyncFileReader(int maxReadSize, int submitThreads, String tag) {\n super(maxReadSize, submitThreads, 0, tag);\n rings = new IOUring[submitThreads];\n rss = new long[submitThreads][][];\n for (int i = 0; i < submitThreads; i++) {\n rings[i] = new IOUring(QD, 0);\n rss[i] = new long[][]{new long[QD], new long[QD]};\n rings[i].registerBuffer(getPartitionPooledBuffer(i));\n }\n }\n\n\n public void registerFile(int[] fds) {\n for (IOUring ring : rings) ring.registerFile(fds);\n }\n\n @Override\n void submitRequest(int partition, ReadOperation[] reqs, int num) {\n for (int i = 0; i < num; i++) {\n ReadOperation op = reqs[i];\n op.readBuffer = getPartitionPooledBuffer(partition)[i];\n op.readBuffer.clear();\n op.reqId = i;\n //this.resultMaps[partition].put(op.reqId, op);\n }\n int cur = 0;\n while (num > cur) {\n int c = submit0(rings[partition], reqs, cur, num);\n cur += c;\n //if(c == 0) pollResponseAndCallback(partition, resultMap);//\n }\n\n long[][] rs = rss[partition];\n\n int resp = 0;\n while (resp < num) {\n //wait results for all submitted requests\n int c = rings[partition].peekCQEntriesNoop(rs);\n if (c > 0) {\n for (int i = 0; i < c; i++) {\n long reqId = rs[0][i];\n int bytesRead = (int) rs[1][i];\n ReadOperation op = reqs[(int) reqId];\n if (op != null) {\n callback(op, bytesRead);\n } else {\n logger.error(\"op should not be null, reqid:{}\", reqId);\n }\n }\n rings[partition].seenCQEntry(c);\n resp += c;\n }\n }\n }\n\n @Override\n boolean pollResponseAndCallback(int partition) {\n /*\n boolean progress = false;\n long[][] rs = rss[partition];\n int c = rings[partition].peekCQEntriesNoop(rs);\n if (c > 0) {\n for (int i = 0; i < c; i++) {\n long reqId = rs[0][i];\n int bytesRead = (int) rs[1][i];\n ReadOperation op = this.resultMaps[partition].remove(reqId);\n if (op != null) {\n callback(op, bytesRead);\n } else {\n //logger.error(\"op should not be null, reqid:{}, resultMap size:{}\", reqId, resultMaps[partition].mappingCount());\n }\n }\n rings[partition].seenCQEntry(c);\n progress = true;\n }\n\n return progress;\n */\n return false;\n }\n\n @Override\n void close0() {\n for (IOUring ring : rings) {\n ring.shutdown();\n }\n }\n\n private int submit0(IOUring ring, ReadOperation[] ops, int from, int to) {\n int freeSqs = ring.availableSQ();\n if (freeSqs <= 0) {\n LockSupport.parkNanos(100);\n return 0;\n } else {\n int available = Math.min(from + freeSqs, to);\n\n for (int i = from; i < available; i++) {\n ReadOperation op = ops[i];\n //ring.prepareRead(op.reqId, op.fd, op.readPosition, op.readBuffer, op.alignedReadSize);\n ring.prepareReadFixed(op.reqId, op.fd, op.readPosition, op.readBuffer, op.alignedReadSize, (int) op.reqId);//reqId is the same as buffer index\n }\n int s = ring.submit();\n return Math.max(s, 0);\n }\n }\n}" } ]
import tech.bsdb.io.NativeFileIO; import tech.bsdb.io.UringAsyncFileReader; import java.nio.ByteBuffer; import java.nio.channels.CompletionHandler; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.atomic.AtomicLong;
2,245
package tech.bsdb.bench; public class UringAsyncFileBench { static AtomicLong readBytes = new AtomicLong(0); static AtomicLong ios = new AtomicLong(0); static AtomicLong failed = new AtomicLong(0); static AtomicLong submited = new AtomicLong(0); static boolean finished = false; static long iteration = 50000 * 1000 * 1000L; public static void main(String[] args) throws Exception { Path path = FileSystems.getDefault().getPath(args[0]); int parallel = Integer.parseInt(args[1]); int readLen = Integer.parseInt(args[2]); int submitThreads = Integer.parseInt(args[3]); //int callbackThreads = Integer.parseInt(args[4]); long fileLen = path.toFile().length(); new Thread(() -> { while (ios.get() < iteration) { long c = ios.get(); long start = System.currentTimeMillis(); try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.err.printf("submit:%d, complete %d failed %d read bytes %d, iops %d %n", submited.get(), ios.get(), failed.get(), readBytes.get(), (ios.get() - c) * 1000 / (System.currentTimeMillis() - start)); } finished = true; }).start(); for (int i = 0; i < parallel; i++) {
package tech.bsdb.bench; public class UringAsyncFileBench { static AtomicLong readBytes = new AtomicLong(0); static AtomicLong ios = new AtomicLong(0); static AtomicLong failed = new AtomicLong(0); static AtomicLong submited = new AtomicLong(0); static boolean finished = false; static long iteration = 50000 * 1000 * 1000L; public static void main(String[] args) throws Exception { Path path = FileSystems.getDefault().getPath(args[0]); int parallel = Integer.parseInt(args[1]); int readLen = Integer.parseInt(args[2]); int submitThreads = Integer.parseInt(args[3]); //int callbackThreads = Integer.parseInt(args[4]); long fileLen = path.toFile().length(); new Thread(() -> { while (ios.get() < iteration) { long c = ios.get(); long start = System.currentTimeMillis(); try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.err.printf("submit:%d, complete %d failed %d read bytes %d, iops %d %n", submited.get(), ios.get(), failed.get(), readBytes.get(), (ios.get() - c) * 1000 / (System.currentTimeMillis() - start)); } finished = true; }).start(); for (int i = 0; i < parallel; i++) {
UringAsyncFileReader reader = new UringAsyncFileReader(readLen, submitThreads, "");
1
2023-10-07 03:32:27+00:00
4k
reinershir/Shir-Boot
src/main/java/io/github/reinershir/boot/core/query/QueryHelper.java
[ { "identifier": "QueryRuleEnum", "path": "src/main/java/io/github/reinershir/boot/core/query/annotation/QueryRuleEnum.java", "snippet": "public enum QueryRuleEnum {\n\n\t/**查询规则 大于*/\n GT(\">\",\"gt\",\"大于\"),\n /**查询规则 大于等于*/\n GE(\">=\",\"ge\",\"大于等于\"),\n /**查询规则 小于*/\n LT(\"<\",\"lt\",\"小于\"),\n /**查询规则 小于等于*/\n LE(\"<=\",\"le\",\"小于等于\"),\n /**查询规则 等于*/\n EQ(\"=\",\"eq\",\"等于\"),\n /**查询规则 不等于*/\n NE(\"!=\",\"ne\",\"不等于\"),\n /**查询规则 包含*/\n IN(\"IN\",\"in\",\"包含\"),\n /**查询规则 全模糊*/\n LIKE(\"LIKE\",\"like\",\"全模糊\"),\n /**查询规则 左模糊*/\n LEFT_LIKE(\"LEFT_LIKE\",\"left_like\",\"左模糊\"),\n /**查询规则 右模糊*/\n RIGHT_LIKE(\"RIGHT_LIKE\",\"right_like\",\"右模糊\"),\n /** 值为空 */\n EMPTY(\"EMPTY\",\"empty\",\"值为空\"),\n /** 值不为空 */\n NOT_EMPTY(\"NOT_EMPTY\",\"not_empty\",\"值不为空\"),\n /**查询规则 不包含*/\n NOT_IN(\"NOT_IN\",\"not_in\",\"不包含\"),\n HIDDEN(\"HIDDEN\",\"hidden\",\"隐藏\");\n \n\tprivate String value;\n \n private String condition; \n\n private String msg;\n\n QueryRuleEnum(String value, String condition, String msg){\n this.value = value;\n this.condition = condition;\n this.msg = msg;\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 String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n public String getCondition() {\n\t\treturn condition;\n\t}\n\n\tpublic void setCondition(String condition) {\n\t\tthis.condition = condition;\n\t}\n\n\tpublic static QueryRuleEnum getByValue(String value){\n \tif(!StringUtils.hasText(value)) {\n \t\treturn null;\n \t}\n for(QueryRuleEnum val :values()){\n if (val.getValue().equals(value) || val.getCondition().equals(value)){\n return val;\n }\n }\n return null;\n }\n}" }, { "identifier": "User", "path": "src/main/java/io/github/reinershir/boot/model/User.java", "snippet": "@Data\n@TableName(\"USER\")\npublic class User{\n\n\t/**\n\t * \n\t */\n\t@TableId(type = IdType.AUTO)\n\t@NotNull(message = \"ID不能为空!\",groups = ValidateGroups.UpdateGroup.class)\n\t@Schema(description = \"用户ID,修改用户信息时不能为空\",example = \"3\",nullable = true)\n\tprivate Long id;\n\t\n\t/**\n\t * 登陆名\n\t */\n\t@Schema(description = \"用户登陆名\", required = true, example = \"zhangsan\")\n\t@NotBlank(message = \"登陆名不能为空!\",groups = ValidateGroups.AddGroup.class)\n\tprivate String loginName;\n\t\n\t/**\n\t * 密码\n\t */\n\t@Schema(description = \"登陆密码(前端需要MD5加密再传输,修改信息时无需传此字段)\", required = true, example = \"zhangsan123\")\n\t@NotBlank(message = \"密码不能为空!\",groups = ValidateGroups.AddGroup.class)\n\t@Size(max = 32,min = 6,message = \"密码长度最大32位,最小6位!\",groups = ValidateGroups.AddGroup.class)\n\tprivate String password;\n\t\n\t/**\n\t * 用户名称\n\t */\n\t@Schema(description = \"用户名称\", required = true, example = \"李四\")\n\t@NotBlank(message = \"用户名称不能为空!\")\n\tprivate String nickName;\n\t\n\t/**\n\t * 邮箱\n\t */\n\t@Schema(description = \"邮箱\", required = false, example = \"[email protected]\")\n\tprivate String email;\n\t\n\t/**\n\t * 电话号码\n\t */\n\t@Schema(description = \"电话\", required = false, example = \"110\")\n\tprivate String phoneNumber;\n\t\n\t@Schema(hidden = true)\n\tprivate Integer status;\n\t\n\t/**\n\t * 创建时间\n\t */\n\t@Schema(hidden = true)\n\tprivate Date createDate;\n\t\n\t@Schema(description = \"Profile\", required = false, example = \"https://reiner.host/img/head.jpg\")\n\tprivate String profile;\n\t\n\t/**\n\t * \n\t */\n\t@Schema(hidden = true)\n\tprivate Date updateDate;\n\t\n\t/**\n\t * 其它说明 \n\t */\n\t@Schema(description = \"电话\", required = false, example = \"其它说明\")\n\tprivate String remark;\n\t\n\t/**\n\t * @Title: 逻辑删除标识\n\t * @Description: \n\t * @author ReinerShir\n\t * @return\n\t */\n\t@TableLogic\n\t@TableField(\"IS_DELETE\")\n\t@Schema(hidden = true)\n\tprivate Integer isDelete;\n\t\n\n}" }, { "identifier": "FieldUtils", "path": "src/main/java/io/github/reinershir/boot/utils/FieldUtils.java", "snippet": "public class FieldUtils {\n\n\t/**\n\t * 将驼峰命名转化成下划线\n\t * @param para\n\t * @return\n\t */\n\tpublic static String camelToUnderline(String para){\n\t int length = 3;\n if(para.length()<length){\n \treturn para.toLowerCase(); \n }\n StringBuilder sb=new StringBuilder(para);\n //定位\n int temp=0;\n //从第三个字符开始 避免命名不规范 \n for(int i=2;i<para.length();i++){\n if(Character.isUpperCase(para.charAt(i))){\n sb.insert(i+temp, \"_\");\n temp+=1;\n }\n }\n return sb.toString().toLowerCase(); \n\t}\n}" } ]
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import cn.hutool.core.bean.BeanUtil; import io.github.reinershir.boot.core.query.annotation.QueryRule; import io.github.reinershir.boot.core.query.annotation.QueryRuleEnum; import io.github.reinershir.boot.model.User; import io.github.reinershir.boot.utils.FieldUtils;
1,900
package io.github.reinershir.boot.core.query; /** * Copyright: Copyright (c) 2023 reiner * @ClassName: QueryHelper.java * @Description: * @version: v1.0.0 * @author: ReinerShir * @date: 2023年7月30日 下午10:50:57 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2023年7月30日 ReinerShir v1.0.0 */ public class QueryHelper { public static <T> QueryWrapper<T> initQueryWrapper(T entity){ PropertyDescriptor[] properties = BeanUtil.getPropertyDescriptors(entity.getClass()); QueryWrapper<T> wrapper = new QueryWrapper<T>(); for (PropertyDescriptor property : properties) { String name = property.getName(); Object value=null; try { value = property.getReadMethod().invoke(entity); } catch (Exception e) { e.printStackTrace(); } if(value!=null&&!"".equals(value)) { Field filed=null; try { filed = entity.getClass().getDeclaredField(name); } catch (Exception e) { e.printStackTrace(); } if(filed!=null) { QueryRule queryRule = filed.getAnnotation(QueryRule.class);
package io.github.reinershir.boot.core.query; /** * Copyright: Copyright (c) 2023 reiner * @ClassName: QueryHelper.java * @Description: * @version: v1.0.0 * @author: ReinerShir * @date: 2023年7月30日 下午10:50:57 * * Modification History: * Date Author Version Description *---------------------------------------------------------* * 2023年7月30日 ReinerShir v1.0.0 */ public class QueryHelper { public static <T> QueryWrapper<T> initQueryWrapper(T entity){ PropertyDescriptor[] properties = BeanUtil.getPropertyDescriptors(entity.getClass()); QueryWrapper<T> wrapper = new QueryWrapper<T>(); for (PropertyDescriptor property : properties) { String name = property.getName(); Object value=null; try { value = property.getReadMethod().invoke(entity); } catch (Exception e) { e.printStackTrace(); } if(value!=null&&!"".equals(value)) { Field filed=null; try { filed = entity.getClass().getDeclaredField(name); } catch (Exception e) { e.printStackTrace(); } if(filed!=null) { QueryRule queryRule = filed.getAnnotation(QueryRule.class);
String columnName = FieldUtils.camelToUnderline(name);
2
2023-10-10 13:06:54+00:00
4k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/panel/BossingPanel.java
[ { "identifier": "Format", "path": "src/main/java/net/wiseoldman/util/Format.java", "snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n DecimalFormat df = new DecimalFormat();\n df.setGroupingUsed(false);\n df.setRoundingMode(RoundingMode.FLOOR);\n df.setMaximumFractionDigits(2);\n\n // < 10 million\n if (num < 10_000_000 && num > -10_000_000)\n {\n df.setMaximumFractionDigits(0);\n return df.format(num / 1000.0) + \"k\";\n }\n\n // < 1 billion\n if (num < 1_000_000_000 && num > -1_000_000_000)\n {\n return df.format( num / 1_000_000.0) + \"m\";\n }\n\n return df.format(num / 1_000_000_000.0) + \"b\";\n }\n\n public static String formatNumber(double num)\n {\n if ((num < 10000 && num > -10000))\n {\n return String.format(\"%.0f\", num);\n }\n\n DecimalFormat df = new DecimalFormat();\n df.setRoundingMode(RoundingMode.FLOOR);\n df.setMaximumFractionDigits(2);\n\n return df.format(num / 1000.0) + \"k\";\n }\n\n public static String formatDate(String date, boolean relative)\n {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd MMM yyyy, HH:mm\");\n ZoneId localZone = ZoneId.systemDefault();\n ZonedDateTime updatedAt = Instant.parse(date).atZone(localZone);\n\n if (relative)\n {\n String lastUpdated = \"\";\n ZonedDateTime now = Instant.now().atZone(localZone);\n long difference = Duration.between(updatedAt, now).toHours();\n\n if (difference == 0)\n {\n return \"less than 1 hour ago\";\n }\n\n long days = difference / 24;\n long hours = difference % 24;\n\n String dayUnit = days > 1 ? \" days, \" : \" day, \";\n String hourUnit = hours > 1 ? \" hours ago\" : \" hour ago\";\n\n lastUpdated += days > 0 ? days + dayUnit : \"\";\n lastUpdated += hours > 0 ? hours + hourUnit : \"\";\n\n return lastUpdated;\n }\n else\n {\n return formatter.format(updatedAt);\n }\n }\n}" }, { "identifier": "PlayerInfo", "path": "src/main/java/net/wiseoldman/beans/PlayerInfo.java", "snippet": "@Value\npublic class PlayerInfo\n{\n int id;\n String username;\n String displayName;\n PlayerType type;\n PlayerBuild build;\n String country;\n boolean flagged;\n long exp;\n double ehp;\n double ehb;\n double ttm;\n double tt200m;\n String registeredAt;\n String updatedAt;\n String lastChangedAt;\n String lastImportedAt;\n int combatLevel;\n Snapshot latestSnapshot;\n}" }, { "identifier": "Snapshot", "path": "src/main/java/net/wiseoldman/beans/Snapshot.java", "snippet": "@Value\npublic class Snapshot\n{\n\tint id;\n\tint playerId;\n\tString createdAt;\n\tString importedAt;\n\tSnapshotData data;\n}" }, { "identifier": "Computed", "path": "src/main/java/net/wiseoldman/beans/Computed.java", "snippet": "@Value\npublic class Computed\n{\n String metric;\n double value;\n int rank;\n}" } ]
import com.google.common.collect.ImmutableList; import net.wiseoldman.util.Format; import net.wiseoldman.beans.PlayerInfo; import net.wiseoldman.beans.Snapshot; import net.wiseoldman.beans.Computed; import net.runelite.client.ui.ColorScheme; import net.runelite.client.util.QuantityFormatter; import net.runelite.client.hiscore.HiscoreSkill; import net.runelite.client.hiscore.HiscoreSkillType; import javax.inject.Inject; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import static net.runelite.client.hiscore.HiscoreSkill.*;
1,813
package net.wiseoldman.panel; class BossingPanel extends JPanel { /** * Bosses, ordered in the way they should be displayed in the panel. */ private static final List<HiscoreSkill> BOSSES = ImmutableList.of( ABYSSAL_SIRE, ALCHEMICAL_HYDRA, ARTIO, BARROWS_CHESTS, BRYOPHYTA, CALLISTO, CALVARION, CERBERUS, CHAMBERS_OF_XERIC, CHAMBERS_OF_XERIC_CHALLENGE_MODE, CHAOS_ELEMENTAL, CHAOS_FANATIC, COMMANDER_ZILYANA, CORPOREAL_BEAST, DAGANNOTH_PRIME, DAGANNOTH_REX, DAGANNOTH_SUPREME, CRAZY_ARCHAEOLOGIST, DERANGED_ARCHAEOLOGIST, DUKE_SUCELLUS, GENERAL_GRAARDOR, GIANT_MOLE, GROTESQUE_GUARDIANS, HESPORI, KALPHITE_QUEEN, KING_BLACK_DRAGON, KRAKEN, KREEARRA, KRIL_TSUTSAROTH, MIMIC, NEX, NIGHTMARE, PHOSANIS_NIGHTMARE, OBOR, PHANTOM_MUSPAH, SARACHNIS, SCORPIA, SKOTIZO, SPINDEL, TEMPOROSS, THE_GAUNTLET, THE_CORRUPTED_GAUNTLET, THE_LEVIATHAN, THE_WHISPERER, THEATRE_OF_BLOOD, THEATRE_OF_BLOOD_HARD_MODE,THERMONUCLEAR_SMOKE_DEVIL, TOMBS_OF_AMASCUT, TOMBS_OF_AMASCUT_EXPERT, TZKAL_ZUK, TZTOK_JAD, VARDORVIS, VENENATIS, VETION, VORKATH, WINTERTODT, ZALCANO, ZULRAH ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; TableRow totalEhbRow; List<RowPair> tableRows = new ArrayList<>(); @Inject private BossingPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("bossing"); // Handle total ehb row separately because it's special totalEhbRow = new TableRow( "ehb", "EHB", HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); totalEhbRow.setBackground(ROW_COLORS[1]); add(tableHeader); add(totalEhbRow); for (int i = 0; i < BOSSES.size(); i++) { HiscoreSkill boss = BOSSES.get(i); TableRow row = new TableRow( boss.name(), boss.getName(), HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); row.setBackground(ROW_COLORS[i%2]); tableRows.add(new RowPair(boss, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; } Snapshot latestSnapshot = info.getLatestSnapshot(); for (RowPair rp : tableRows) { HiscoreSkill boss = rp.getSkill(); TableRow row = rp.getRow(); row.update(latestSnapshot.getData().getBosses().getBoss(boss), boss); } updateTotalEhb(latestSnapshot.getData().getComputed().getEhb()); }
package net.wiseoldman.panel; class BossingPanel extends JPanel { /** * Bosses, ordered in the way they should be displayed in the panel. */ private static final List<HiscoreSkill> BOSSES = ImmutableList.of( ABYSSAL_SIRE, ALCHEMICAL_HYDRA, ARTIO, BARROWS_CHESTS, BRYOPHYTA, CALLISTO, CALVARION, CERBERUS, CHAMBERS_OF_XERIC, CHAMBERS_OF_XERIC_CHALLENGE_MODE, CHAOS_ELEMENTAL, CHAOS_FANATIC, COMMANDER_ZILYANA, CORPOREAL_BEAST, DAGANNOTH_PRIME, DAGANNOTH_REX, DAGANNOTH_SUPREME, CRAZY_ARCHAEOLOGIST, DERANGED_ARCHAEOLOGIST, DUKE_SUCELLUS, GENERAL_GRAARDOR, GIANT_MOLE, GROTESQUE_GUARDIANS, HESPORI, KALPHITE_QUEEN, KING_BLACK_DRAGON, KRAKEN, KREEARRA, KRIL_TSUTSAROTH, MIMIC, NEX, NIGHTMARE, PHOSANIS_NIGHTMARE, OBOR, PHANTOM_MUSPAH, SARACHNIS, SCORPIA, SKOTIZO, SPINDEL, TEMPOROSS, THE_GAUNTLET, THE_CORRUPTED_GAUNTLET, THE_LEVIATHAN, THE_WHISPERER, THEATRE_OF_BLOOD, THEATRE_OF_BLOOD_HARD_MODE,THERMONUCLEAR_SMOKE_DEVIL, TOMBS_OF_AMASCUT, TOMBS_OF_AMASCUT_EXPERT, TZKAL_ZUK, TZTOK_JAD, VARDORVIS, VENENATIS, VETION, VORKATH, WINTERTODT, ZALCANO, ZULRAH ); static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)}; TableRow totalEhbRow; List<RowPair> tableRows = new ArrayList<>(); @Inject private BossingPanel() { setLayout(new GridLayout(0, 1)); StatsTableHeader tableHeader = new StatsTableHeader("bossing"); // Handle total ehb row separately because it's special totalEhbRow = new TableRow( "ehb", "EHB", HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); totalEhbRow.setBackground(ROW_COLORS[1]); add(tableHeader); add(totalEhbRow); for (int i = 0; i < BOSSES.size(); i++) { HiscoreSkill boss = BOSSES.get(i); TableRow row = new TableRow( boss.name(), boss.getName(), HiscoreSkillType.BOSS, "kills", "rank", "ehb" ); row.setBackground(ROW_COLORS[i%2]); tableRows.add(new RowPair(boss, row)); add(row); } } public void update(PlayerInfo info) { if (info == null) { return; } Snapshot latestSnapshot = info.getLatestSnapshot(); for (RowPair rp : tableRows) { HiscoreSkill boss = rp.getSkill(); TableRow row = rp.getRow(); row.update(latestSnapshot.getData().getBosses().getBoss(boss), boss); } updateTotalEhb(latestSnapshot.getData().getComputed().getEhb()); }
private void updateTotalEhb(Computed ehb)
3
2023-10-09 14:23:06+00:00
4k
PinkGoosik/player-nametags
src/main/java/pinkgoosik/playernametags/command/PlayerNametagsCommands.java
[ { "identifier": "PlayerNametagsMod", "path": "src/main/java/pinkgoosik/playernametags/PlayerNametagsMod.java", "snippet": "public class PlayerNametagsMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"player-nametags\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\tpublic static LinkedHashMap<UUID, ElementHolder> holders = new LinkedHashMap<>();\n\n\tpublic static PlayerNametagsConfig config;\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tconfig = PlayerNametagsConfig.read();\n\t\tPlayerNametagsCommands.init();\n\n\t\tServerTickEvents.END_SERVER_TICK.register(server -> {\n\t\t\tif(config.enabled) {\n\t\t\t\tserver.getPlayerManager().getPlayerList().forEach(PlayerNametagsMod::updateHolder);\n\n\t\t\t\tif(config.updateRate >= 1 && server.getTicks() % config.updateRate == 0) {\n\t\t\t\t\tupdateNametags(server);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif(!holders.isEmpty()) {\n\t\t\t\t\tholders.forEach((uuid, holder) -> holder.destroy());\n\t\t\t\t\tholders.clear();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static ElementHolder updateHolder(ServerPlayerEntity player) {\n\t\tElementHolder holder;\n\n\t\tif (!holders.containsKey(player.getUuid())) {\n\t\t\tholder = new ElementHolder();\n\n\t\t\tItemDisplayElement element = new ItemDisplayElement();\n\t\t\telement.setBillboardMode(DisplayEntity.BillboardMode.CENTER);\n\n\t\t\tText text = Placeholders.parseText(TextParserUtils.formatText(getFormat(player)), PlaceholderContext.of(player));\n\n\t\t\telement.setCustomName(text);\n\t\t\telement.setCustomNameVisible(!player.isInvisible());\n\n\t\t\tholder.addElement(element);\n\t\t\tholders.put(player.getUuid(), holder);\n\t\t}\n\t\telse {\n\t\t\tholder = holders.get(player.getUuid());\n\t\t}\n\n\t\tholder.getElements().forEach(virtualElement -> {\n\t\t\tif(virtualElement instanceof ItemDisplayElement element) {\n\t\t\t\tif(player.isSneaking()) {\n\t\t\t\t\tswitch (config.whenSneaking) {\n\t\t\t\t\t\tcase \"gray-out\" -> element.setSneaking(true);\n\t\t\t\t\t\tcase \"hide\" -> element.setCustomNameVisible(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\telement.setSneaking(false);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tEntityAttachment.of(holder, player);\n\t\tVirtualEntityUtils.addVirtualPassenger(player, holder.getEntityIds().getInt(0));\n\n\t\treturn holder;\n\t}\n\n\tpublic static void updateNametags(MinecraftServer server) {\n\t\tholders.forEach((uuid, holder) -> {\n\t\t\tvar player = server.getPlayerManager().getPlayer(uuid);\n\t\t\tif(player != null) {\n\t\t\t\tText text = Placeholders.parseText(TextParserUtils.formatText(getFormat(player)), PlaceholderContext.of(player));\n\t\t\t\tholder.getElements().forEach(virtualElement -> {\n\t\t\t\t\tif(virtualElement instanceof ItemDisplayElement element) {\n\t\t\t\t\t\telement.setCustomName(text);\n\t\t\t\t\t\telement.tick();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static String getFormat(ServerPlayerEntity player) {\n\n\t\tfor(Map.Entry<String, String> entry : config.formatPerPermission.entrySet()) {\n\t\t\tif(Permissions.check(player, entry.getKey())) return entry.getValue();\n\t\t}\n\n\t\treturn config.format;\n\t}\n}" }, { "identifier": "PlayerNametagsConfig", "path": "src/main/java/pinkgoosik/playernametags/config/PlayerNametagsConfig.java", "snippet": "public class PlayerNametagsConfig {\n\tpublic static final Gson GSON = new GsonBuilder().setLenient().setPrettyPrinting().disableHtmlEscaping().create();\n\n\tpublic boolean enabled = false;\n\tpublic String format = \"%player:name%\";\n\tpublic int updateRate = 20;\n\tpublic String whenSneaking = \"gray-out\";\n\n\tpublic LinkedHashMap<String, String> formatPerPermission = new LinkedHashMap<>(Map.of(\"example.admin\", \"<red>[Admin] %player:name%\"));\n\n\tpublic static PlayerNametagsConfig read() {\n\t\tString filePath = FabricLoader.getInstance().getConfigDir().resolve(\"player-nametags.json\").toString();\n\t\ttry {\n\t\t\tBufferedReader reader = new BufferedReader(new FileReader(filePath, StandardCharsets.UTF_8));\n\t\t\tvar config = GSON.fromJson(reader, PlayerNametagsConfig.class);\n\t\t\tconfig.save();\n\t\t\treturn config;\n\t\t}\n\t\tcatch(FileNotFoundException e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"File \" + filePath + \" is not found! Setting to default.\");\n\t\t\tvar conf = new PlayerNametagsConfig();\n\t\t\tconf.save();\n\t\t\treturn conf;\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"Failed to read player-nametags config due to an exception. \" +\n\t\t\t\t\"Please delete player-nametags.json to regenerate config or fix the issue:\\n\" + e);\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(0);\n\t\t\treturn new PlayerNametagsConfig();\n\t\t}\n\t}\n\n\tpublic void save() {\n\t\ttry {\n\t\t\tString filePath = FabricLoader.getInstance().getConfigDir().resolve(\"player-nametags.json\").toString();\n\t\t\ttry(FileWriter writer = new FileWriter(filePath, StandardCharsets.UTF_8)) {\n\t\t\t\twriter.write(GSON.toJson(this));\n\t\t\t}\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\tPlayerNametagsMod.LOGGER.info(\"Failed to save player-nametags config due to an exception:\\n\" + e);\n\t\t}\n\t}\n}" } ]
import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.BoolArgumentType; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.suggestion.SuggestionProvider; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.text.Text; import pinkgoosik.playernametags.PlayerNametagsMod; import pinkgoosik.playernametags.config.PlayerNametagsConfig; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal;
1,697
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining(); for(String permission : PlayerNametagsMod.config.formatPerPermission.keySet()) { if(permission.contains(remains)) { builder.suggest(permission); } } return builder.buildFuture(); }; static final String[] modes = new String[]{"gray-out", "hide", "none"}; public static final SuggestionProvider<ServerCommandSource> SUGGEST_SNEAKING_MODE = (context, builder) -> { String remains = builder.getRemaining(); for(String mode : modes) { if(mode.contains(remains)) { builder.suggest(mode); } } return builder.buildFuture(); }; public static void init() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> register(dispatcher)); } private static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal("player-nametags").requires(source -> source.hasPermissionLevel(3)).then(literal("reload").executes(context -> {
package pinkgoosik.playernametags.command; public class PlayerNametagsCommands { public static final SuggestionProvider<ServerCommandSource> SUGGEST_PERMISSION = (context, builder) -> { String remains = builder.getRemaining(); for(String permission : PlayerNametagsMod.config.formatPerPermission.keySet()) { if(permission.contains(remains)) { builder.suggest(permission); } } return builder.buildFuture(); }; static final String[] modes = new String[]{"gray-out", "hide", "none"}; public static final SuggestionProvider<ServerCommandSource> SUGGEST_SNEAKING_MODE = (context, builder) -> { String remains = builder.getRemaining(); for(String mode : modes) { if(mode.contains(remains)) { builder.suggest(mode); } } return builder.buildFuture(); }; public static void init() { CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> register(dispatcher)); } private static void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literal("player-nametags").requires(source -> source.hasPermissionLevel(3)).then(literal("reload").executes(context -> {
PlayerNametagsMod.config = PlayerNametagsConfig.read();
1
2023-10-10 10:12:09+00:00
4k
vaylor27/config
common/src/main/java/net/vakror/jamesconfig/config/example/ExampleConfigs.java
[ { "identifier": "CompoundRegistryObject", "path": "common/src/main/java/net/vakror/jamesconfig/config/config/object/default_objects/registry/CompoundRegistryObject.java", "snippet": "public class CompoundRegistryObject extends RegistryConfigObject {\n /**\n * a list of sub-objects to serialize and deserialize\n * do not modify directly, instead, use {@link #addObject}\n */\n public List<ConfigObject> objects = new ArrayList<>();\n\n /**\n * A simple constructor which initializes {@link #objects}\n * @param name the name of this registry object\n * @param objects the initial value of {@link #objects}\n */\n public CompoundRegistryObject(String name, List<ConfigObject> objects) {\n this(name);\n this.objects = objects;\n }\n\n /**\n * @param name the name of this registry object\n */\n public CompoundRegistryObject(String name) {\n super(name, new ResourceLocation(JamesConfigMod.MOD_ID, \"compound\"));\n }\n\n /**\n * a simple method which adds objects to the compound\n * @param object the object to add\n */\n public void addObject(ConfigObject object) {\n objects.add(object);\n }\n\n /**\n * A mirror method to {@link #deserialize} to serialize this compound and all children, including other compounds into a {@link JsonElement}\n * @return the serialized version of this compound\n */\n @Override\n public JsonElement serialize() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"type\", getType().toString());\n for (ConfigObject object : objects) {\n jsonObject.add(object.getName(), object.serialize());\n }\n return jsonObject;\n }\n\n /**\n * A mirror method to {@link #serialize)} which deserializes this compound and all children, including other compounds, from a {@link JsonElement}\n * @param name the name of the compound\n * @param element the {@link JsonElement} to deserialize from\n * @param defaultValue the default value – used if the element is invalid or the wrong type to reset the value of the primitive to default, null if called from a registry config\n * @param configName the name of the config containing this value\n * @return the deserialized form of the compound\n */\n @Override\n public ConfigObject deserialize(String name, JsonElement element, ConfigObject defaultValue, String configName) {\n JsonObject object = (JsonObject) element;\n CompoundRegistryObject compoundObject = new CompoundRegistryObject(name);\n\n for (Map.Entry<String, JsonElement> entry : object.entrySet()) {\n String key = entry.getKey();\n ConfigObject configObject = ConfigObject.deserializeUnknown(key, object.get(key), this.getName());\n if (configObject != null) {\n compoundObject.addObject(configObject);\n }\n }\n compoundObject.setName(name);\n return compoundObject;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof CompoundRegistryObject that)) return false;\n return Objects.equals(objects, that.objects) && Objects.equals(getName(), that.getName());\n }\n\n @Override\n public int hashCode() {\n return getName().hashCode();\n }\n}" }, { "identifier": "ExampleMultiObjectRegistryConfigImpl", "path": "common/src/main/java/net/vakror/jamesconfig/config/example/configs/ExampleMultiObjectRegistryConfigImpl.java", "snippet": "public class ExampleMultiObjectRegistryConfigImpl extends SimpleMultiObjectRegistryConfigImpl {\n public static final ResourceLocation NAME = new ResourceLocation(JamesConfigMod.MOD_ID, \"exampleconfig\");\n public ExampleMultiObjectRegistryConfigImpl() {\n super(\"example/config\", NAME);\n }\n\n @Override\n protected void resetToDefault() {\n CompoundRegistryObject test = new CompoundRegistryObject(\"test object\");\n CompoundRegistryObject object = new CompoundRegistryObject(\"this is a registry config\");\n object.addObject(new StringPrimitiveObject(\"will be loaded into the config\", \"all of these entries\"));\n test.addObject(object);\n test.addObject(new BooleanPrimitiveObject(\"doesThisWork\", true));\n add(test);\n }\n}" }, { "identifier": "ExampleSettingConfig", "path": "common/src/main/java/net/vakror/jamesconfig/config/example/configs/ExampleSettingConfig.java", "snippet": "public class ExampleSettingConfig extends SimpleSettingConfigImpl {\n public ExampleSettingConfig() {\n super(\"example/config/setting\", new ResourceLocation(JamesConfigMod.MOD_ID, \"setting\"));\n }\n\n @Override\n public List<ConfigObject> getRequiredSettings() {\n return List.of(\n new TestSettingObject(\"this is a setting config\").setValue(\"all the files in this directory will not be loaded\",\n new StringPrimitiveObject(\"into the config, only this one will with exactly these options\")), new BooleanPrimitiveObject(\"doesThisWork\", true));\n }\n\n public static class TestSettingObject extends SimpleSettingConfigObject {\n public TestSettingObject(String name) {\n super(name);\n }\n\n @Override\n public List<ConfigObject> getRequiredSettings() {\n return List.of(new StringPrimitiveObject(\"all the files in this directory will not be loaded\", \"\"));\n }\n\n @Override\n public SettingConfigObject newDefinition(String name) {\n return new TestSettingObject(name);\n }\n }\n}" }, { "identifier": "ExampleSingleObjectRegistryConfigImpl", "path": "common/src/main/java/net/vakror/jamesconfig/config/example/configs/ExampleSingleObjectRegistryConfigImpl.java", "snippet": "public class ExampleSingleObjectRegistryConfigImpl extends SimpleSingleObjectRegistryConfigImpl<StringWithContents> {\n public static final ResourceLocation NAME = new ResourceLocation(JamesConfigMod.MOD_ID, \"exampleconfigone\");\n public ExampleSingleObjectRegistryConfigImpl() {\n super(\"example/test\", NAME);\n }\n\n @Override\n public StringWithContents decode(JsonObject object) {\n return (StringWithContents) new StringWithContents(\"\", \"\").deserialize(\"\", object, null, this.getName().toString());\n }\n\n @Override\n protected void resetToDefault() {\n StringWithContents root = new StringWithContents(\"root\", \"hallo\");\n StringWithContents test = new StringWithContents(\"test\", \"hello?\");\n StringWithContents hallo = new StringWithContents(\"hallo\", \"does this work?\");\n add(root);\n add(test);\n add(hallo);\n }\n}" }, { "identifier": "SimpleConfigManager", "path": "common/src/main/java/net/vakror/jamesconfig/config/manager/config/SimpleConfigManager.java", "snippet": "public class SimpleConfigManager extends ConfigManager {\n public static final SimpleConfigManager INSTANCE = new SimpleConfigManager();\n}" }, { "identifier": "SimpleConfigObjectManager", "path": "common/src/main/java/net/vakror/jamesconfig/config/manager/object/SimpleConfigObjectManager.java", "snippet": "public class SimpleConfigObjectManager extends ConfigObjectManager {\n public static final SimpleConfigObjectManager INSTANCE = new SimpleConfigObjectManager();\n}" } ]
import net.vakror.jamesconfig.config.config.object.default_objects.registry.CompoundRegistryObject; import net.vakror.jamesconfig.config.example.configs.ExampleMultiObjectRegistryConfigImpl; import net.vakror.jamesconfig.config.example.configs.ExampleSettingConfig; import net.vakror.jamesconfig.config.example.configs.ExampleSingleObjectRegistryConfigImpl; import net.vakror.jamesconfig.config.manager.config.SimpleConfigManager; import net.vakror.jamesconfig.config.manager.object.SimpleConfigObjectManager;
1,707
package net.vakror.jamesconfig.config.example; public class ExampleConfigs { public static void addExampleConfig() {
package net.vakror.jamesconfig.config.example; public class ExampleConfigs { public static void addExampleConfig() {
SimpleConfigManager.INSTANCE.register(new ExampleMultiObjectRegistryConfigImpl());
1
2023-10-07 23:04:49+00:00
4k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/effect/MRPGCEffects.java
[ { "identifier": "MRPGCMod", "path": "src/main/java/net/more_rpg_classes/MRPGCMod.java", "snippet": "public class MRPGCMod implements ModInitializer {\n\tpublic static final String MOD_ID = \"more_rpg_classes\";\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"more_rpg_classes\");\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tMRPGCItems.registerModItems();\n\t\tMRPGCGroup.registerItemGroups();\n\t\tMRPGCLootTableEntityModifiers.modifyLootEntityTables();\n\t\tMRPGCLootTableChestModifiers.modifyChestLootTables();\n\t\tMRPGCEffects.register();\n\t\tMRPGCBooks.register();\n\t\tCustomSpells.register();\n\t\tMRPGCEntityAttributes.registerAttributes();\n\t\tMoreParticles.register();\n\t\tModSounds.register();\n\t}\n}" }, { "identifier": "MRPGCEntityAttributes", "path": "src/main/java/net/more_rpg_classes/entity/attribute/MRPGCEntityAttributes.java", "snippet": "public class MRPGCEntityAttributes{\n\n public static final EntityAttribute INCOMING_DAMAGE_MODIFIER = createAttribute(\n \"incoming_damage_modifier\", 0.0f, -10.0f, 10.0f);\n\n\n\n public static EntityAttribute register(String id, EntityAttribute attribute){\n return Registry.register(Registries.ATTRIBUTE, new Identifier(MRPGCMod.MOD_ID, id), attribute);\n }\n private static EntityAttribute createAttribute(final String name, double base, double min, double max){\n return new ClampedEntityAttribute(\"attribute.name.generic.\" + MRPGCMod.MOD_ID + '.' +name, base, min, max).setTracked(true);\n }\n\n public static void registerAttributes(){\n register(\"incoming_damage_modifier\", INCOMING_DAMAGE_MODIFIER);\n }\n}" } ]
import net.minecraft.entity.attribute.EntityAttributeModifier; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectCategory; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.util.Identifier; import net.more_rpg_classes.MRPGCMod; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.spell_engine.api.effect.ActionImpairing; import net.spell_engine.api.effect.EntityActionsAllowed; import net.spell_engine.api.effect.RemoveOnHit; import net.spell_engine.api.effect.Synchronized; import net.spell_power.api.MagicSchool; import net.spell_power.api.SpellPower;
1,643
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(MRPGCEntityAttributes.INCOMING_DAMAGE_MODIFIER, "0bf30a36-798a-450d-bd74-959910e6778e", rage_incoming_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "3098b421-2316-4b40-9fcf-71c84fd85fc3", rage_attack_speed_increase, EntityAttributeModifier.Operation.ADDITION); //MOLTEN_ARMOR public static final StatusEffect MOLTEN_ARMOR = new MoltenArmorEffect(StatusEffectCategory.HARMFUL,0xdd4e00) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR, "d20cbd0d-4101-4dc8-9bbc-140494951dc8", molten_armor_reduce_factor, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR_TOUGHNESS, "0371dbb7-136a-471e-a7a8-512afa10389c", molten_toughness_reduce_factor, EntityAttributeModifier.Operation.ADDITION); //BARQ_ESNA public static StatusEffect BARQ_ESNA = new BarqEsnaEffect(StatusEffectCategory.HARMFUL, 0x8db4fe) .setVulnerability(MagicSchool.ARCANE, new SpellPower.Vulnerability(0.2F, 0.1F, 0F)); //MOONLIGHT public static StatusEffect MOONLIGHT = new MoonLightEffect(StatusEffectCategory.HARMFUL, 0xbce5fe); //STONE_HAND public static StatusEffect STONE_HAND = new StoneHandEffect(StatusEffectCategory.BENEFICIAL, 0xbce5fe) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", stone_hand_attack, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "9bf58fe9-4b58-4174-9f41-a492a3510271", stone_hand_attack_speed, EntityAttributeModifier.Operation.ADDITION); //STUNNED public static StatusEffect STUNNED = new StunEffect(StatusEffectCategory.HARMFUL, 0xfffeca); //FROZEN_SOLID public static StatusEffect FROZEN_SOLID= new FrozenSolidEffect(StatusEffectCategory.HARMFUL, 0x3beeff); //AERONDIGHT_CHARGE public static StatusEffect AERONDIGHT_CHARGE= new AerondightChargeEffect(StatusEffectCategory.BENEFICIAL, 0x6afecf) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", aerondight_attack, EntityAttributeModifier.Operation.ADDITION); //QUEN SHIELD public static StatusEffect QUEN_SHIELD= new QuenEffect(StatusEffectCategory.BENEFICIAL, 0x3beeff); public static void register(){ Synchronized.configure(RAGE,true); Synchronized.configure(MOLTEN_ARMOR,true); Synchronized.configure(BARQ_ESNA,true); Synchronized.configure(MOONLIGHT,true); Synchronized.configure(STONE_HAND,true); Synchronized.configure(STUNNED,true); ActionImpairing.configure(STUNNED, EntityActionsAllowed.STUN); ActionImpairing.configure(FROZEN_SOLID, EntityActionsAllowed.STUN); RemoveOnHit.configure(FROZEN_SOLID, true); Synchronized.configure(FROZEN_SOLID,true); Synchronized.configure(AERONDIGHT_CHARGE,true); Synchronized.configure(QUEN_SHIELD,true); int mrpgc_spellid = 900;
package net.more_rpg_classes.effect; public class MRPGCEffects { public static float rage_damage_increase = +0.5f; public static float rage_incoming_damage_increase = 0.5f; public static float rage_attack_speed_increase = +0.2f; public static float molten_armor_reduce_factor = -2.0f; public static float molten_toughness_reduce_factor = -1.0f; public static float stone_hand_attack = 1.0f; public static float stone_hand_attack_speed = -0.7f; public static float aerondight_attack = 0.1f; //RAGE public static StatusEffect RAGE = new RageStatusEffect(StatusEffectCategory.BENEFICIAL, 0xf70000) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "0b0701a4-4bdc-42a7-9b7e-06d0e397ae77", rage_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(MRPGCEntityAttributes.INCOMING_DAMAGE_MODIFIER, "0bf30a36-798a-450d-bd74-959910e6778e", rage_incoming_damage_increase, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "3098b421-2316-4b40-9fcf-71c84fd85fc3", rage_attack_speed_increase, EntityAttributeModifier.Operation.ADDITION); //MOLTEN_ARMOR public static final StatusEffect MOLTEN_ARMOR = new MoltenArmorEffect(StatusEffectCategory.HARMFUL,0xdd4e00) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR, "d20cbd0d-4101-4dc8-9bbc-140494951dc8", molten_armor_reduce_factor, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ARMOR_TOUGHNESS, "0371dbb7-136a-471e-a7a8-512afa10389c", molten_toughness_reduce_factor, EntityAttributeModifier.Operation.ADDITION); //BARQ_ESNA public static StatusEffect BARQ_ESNA = new BarqEsnaEffect(StatusEffectCategory.HARMFUL, 0x8db4fe) .setVulnerability(MagicSchool.ARCANE, new SpellPower.Vulnerability(0.2F, 0.1F, 0F)); //MOONLIGHT public static StatusEffect MOONLIGHT = new MoonLightEffect(StatusEffectCategory.HARMFUL, 0xbce5fe); //STONE_HAND public static StatusEffect STONE_HAND = new StoneHandEffect(StatusEffectCategory.BENEFICIAL, 0xbce5fe) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", stone_hand_attack, EntityAttributeModifier.Operation.ADDITION) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_SPEED, "9bf58fe9-4b58-4174-9f41-a492a3510271", stone_hand_attack_speed, EntityAttributeModifier.Operation.ADDITION); //STUNNED public static StatusEffect STUNNED = new StunEffect(StatusEffectCategory.HARMFUL, 0xfffeca); //FROZEN_SOLID public static StatusEffect FROZEN_SOLID= new FrozenSolidEffect(StatusEffectCategory.HARMFUL, 0x3beeff); //AERONDIGHT_CHARGE public static StatusEffect AERONDIGHT_CHARGE= new AerondightChargeEffect(StatusEffectCategory.BENEFICIAL, 0x6afecf) .addAttributeModifier(EntityAttributes.GENERIC_ATTACK_DAMAGE, "d1843e0f-8a63-4c96-a854-9c9444981042", aerondight_attack, EntityAttributeModifier.Operation.ADDITION); //QUEN SHIELD public static StatusEffect QUEN_SHIELD= new QuenEffect(StatusEffectCategory.BENEFICIAL, 0x3beeff); public static void register(){ Synchronized.configure(RAGE,true); Synchronized.configure(MOLTEN_ARMOR,true); Synchronized.configure(BARQ_ESNA,true); Synchronized.configure(MOONLIGHT,true); Synchronized.configure(STONE_HAND,true); Synchronized.configure(STUNNED,true); ActionImpairing.configure(STUNNED, EntityActionsAllowed.STUN); ActionImpairing.configure(FROZEN_SOLID, EntityActionsAllowed.STUN); RemoveOnHit.configure(FROZEN_SOLID, true); Synchronized.configure(FROZEN_SOLID,true); Synchronized.configure(AERONDIGHT_CHARGE,true); Synchronized.configure(QUEN_SHIELD,true); int mrpgc_spellid = 900;
Registry.register(Registries.STATUS_EFFECT, mrpgc_spellid++, new Identifier(MRPGCMod.MOD_ID, "rage").toString(), RAGE);
0
2023-10-14 12:44:07+00:00
4k
PhoenixOrigin/websocket-client
src/main/java/net/phoenix/websocketclient/client/Websocket_clientClient.java
[ { "identifier": "SimpleConfig", "path": "src/main/java/net/phoenix/websocketclient/SimpleConfig.java", "snippet": "public class SimpleConfig {\n\n private static final Logger LOGGER = LogManager.getLogger(\"SimpleConfig\");\n private final HashMap<String, String> config = new HashMap<>();\n private final ConfigRequest request;\n private boolean broken = false;\n\n private SimpleConfig(ConfigRequest request) {\n this.request = request;\n String identifier = \"Config '\" + request.filename + \"'\";\n\n if (!request.file.exists()) {\n LOGGER.info(identifier + \" is missing, generating default one...\");\n\n try {\n createConfig();\n } catch (IOException e) {\n LOGGER.error(identifier + \" failed to generate!\");\n LOGGER.trace(e);\n broken = true;\n }\n }\n\n if (!broken) {\n try {\n loadConfig();\n } catch (Exception e) {\n LOGGER.error(identifier + \" failed to load!\");\n LOGGER.trace(e);\n broken = true;\n }\n }\n\n }\n\n /**\n * Creates new config request object, ideally `namespace`\n * should be the name of the mod id of the requesting mod\n *\n * @param filename - name of the config file\n * @return new config request object\n */\n public static ConfigRequest of(String filename) {\n Path path = FabricLoader.getInstance().getConfigDir();\n return new ConfigRequest(path.resolve(filename + \".yml\").toFile(), filename);\n }\n\n private void createConfig() throws IOException {\n\n // try creating missing files\n request.file.getParentFile().mkdirs();\n Files.createFile(request.file.toPath());\n\n // write default config data\n PrintWriter writer = new PrintWriter(request.file, StandardCharsets.UTF_8);\n writer.write(request.getConfig());\n writer.close();\n\n }\n\n private void loadConfig() throws IOException {\n Scanner reader = new Scanner(request.file);\n for (int line = 1; reader.hasNextLine(); line++) {\n parseConfigEntry(reader.nextLine(), line);\n }\n }\n\n // Modification by Kaupenjoe\n private void parseConfigEntry(String entry, int line) {\n if (!entry.isEmpty() && !entry.startsWith(\"#\")) {\n String[] parts = entry.split(\"=\", 2);\n if (parts.length == 2) {\n // Recognizes comments after a value\n String temp = parts[1].split(\" #\")[0];\n config.put(parts[0], temp);\n } else {\n throw new RuntimeException(\"Syntax error in config file on line \" + line + \"!\");\n }\n }\n }\n\n /**\n * Queries a value from config, returns `null` if the\n * key does not exist.\n *\n * @return value corresponding to the given key\n * @see SimpleConfig#getOrDefault\n */\n public String get(String key) {\n return config.get(key);\n }\n\n /**\n * Returns string value from config corresponding to the given\n * key, or the default string if the key is missing.\n *\n * @return value corresponding to the given key, or the default value\n */\n public String getOrDefault(String key, String def) {\n String val = get(key);\n return val == null ? def : val;\n }\n\n /**\n * Returns integer value from config corresponding to the given\n * key, or the default integer if the key is missing or invalid.\n *\n * @return value corresponding to the given key, or the default value\n */\n public int getOrDefault(String key, int def) {\n try {\n return Integer.parseInt(get(key));\n } catch (Exception e) {\n return def;\n }\n }\n\n /**\n * Returns boolean value from config corresponding to the given\n * key, or the default boolean if the key is missing.\n *\n * @return value corresponding to the given key, or the default value\n */\n public boolean getOrDefault(String key, boolean def) {\n String val = get(key);\n if (val != null) {\n return val.equalsIgnoreCase(\"true\");\n }\n\n return def;\n }\n\n /**\n * Returns double value from config corresponding to the given\n * key, or the default string if the key is missing or invalid.\n *\n * @return value corresponding to the given key, or the default value\n */\n public double getOrDefault(String key, double def) {\n try {\n return Double.parseDouble(get(key));\n } catch (Exception e) {\n return def;\n }\n }\n\n /**\n * If any error occurred during loading or reading from the config\n * a 'broken' flag is set, indicating that the config's state\n * is undefined and should be discarded using `delete()`\n *\n * @return the 'broken' flag of the configuration\n */\n public boolean isBroken() {\n return broken;\n }\n\n /**\n * deletes the config file from the filesystem\n *\n * @return true if the operation was successful\n */\n public boolean delete() {\n LOGGER.warn(\"Config '\" + request.filename + \"' was removed from existence! Restart the game to regenerate it.\");\n return request.file.delete();\n }\n\n public interface DefaultConfig {\n static String empty(String namespace) {\n return \"\";\n }\n\n String get(String namespace);\n }\n\n public static class ConfigRequest {\n\n private final File file;\n private final String filename;\n private DefaultConfig provider;\n\n private ConfigRequest(File file, String filename) {\n this.file = file;\n this.filename = filename;\n this.provider = DefaultConfig::empty;\n }\n\n /**\n * Sets the default config provider, used to generate the\n * config if it's missing.\n *\n * @param provider default config provider\n * @return current config request object\n * @see DefaultConfig\n */\n public ConfigRequest provider(DefaultConfig provider) {\n this.provider = provider;\n return this;\n }\n\n /**\n * Loads the config from the filesystem.\n *\n * @return config object\n * @see SimpleConfig\n */\n public SimpleConfig request() {\n return new SimpleConfig(this);\n }\n\n private String getConfig() {\n return provider.get(filename) + \"\\n\";\n }\n\n }\n\n}" }, { "identifier": "WebsocketHandler", "path": "src/main/java/net/phoenix/websocketclient/WebsocketHandler.java", "snippet": "public class WebsocketHandler extends WebSocketClient {\n\n public boolean dc = false;\n private MessageHandler messageHandler = null;\n\n public WebsocketHandler(URI serverUri, Draft draft) {\n super(serverUri, draft);\n }\n\n public WebsocketHandler(URI serverURI) {\n super(serverURI);\n }\n\n public WebsocketHandler(URI serverUri, Map<String, String> httpHeaders) {\n super(serverUri, httpHeaders);\n }\n\n @Override\n public void onOpen(ServerHandshake handshakedata) {\n MinecraftClient client = MinecraftClient.getInstance();\n client.execute(() -> {\n if (client.player != null) {\n client.player.sendMessage(Text.literal(\"Connected to websocket\"));\n }\n });\n }\n\n @Override\n public void onMessage(String message) {\n messageHandler.handleMessage(message);\n }\n\n @Override\n public void onClose(int code, String reason, boolean remote) {\n MinecraftClient client = MinecraftClient.getInstance();\n client.execute(() -> {\n if (client.player != null) {\n client.player.sendMessage(Text.literal(\"Disconnected from websocket\"));\n }\n });\n if (dc) return;\n client.execute(super::reconnect);\n }\n\n @Override\n public void onError(Exception ex) {\n ex.printStackTrace();\n }\n\n public void setMessageHandler(MessageHandler messageHandler) {\n this.messageHandler = messageHandler;\n }\n\n public abstract static class MessageHandler {\n public abstract void handleMessage(String message);\n }\n\n}" }, { "identifier": "WebsocketCommand", "path": "src/main/java/net/phoenix/websocketclient/commands/WebsocketCommand.java", "snippet": "public class WebsocketCommand {\n\n private int terminate(CommandContext<FabricClientCommandSource> ctx) {\n MinecraftClient client = MinecraftClient.getInstance();\n if(client.player == null) return -1;\n if(Websocket_clientClient.websocket.isClosed()) {\n MinecraftClient.getInstance().player.sendMessage(Text.literal(\"You are already disconnected the server!\"));\n return 0;\n }\n Websocket_clientClient.websocket.dc = true;\n Websocket_clientClient.websocket.close();\n MinecraftClient.getInstance().player.sendMessage(Text.literal(\"You have disconnected from the server!\"));\n return 0;\n }\n\n private int connect(CommandContext<FabricClientCommandSource> ctx) {\n if(Websocket_clientClient.websocket.isOpen()) {\n MinecraftClient.getInstance().player.sendMessage(Text.literal(\"You are already connected to the server!\"));\n return 0;\n }\n Websocket_clientClient.websocket.dc = false;\n Websocket_clientClient.connectWebsocket();\n return 0;\n }\n\n private int manualSend(CommandContext<FabricClientCommandSource> ctx) {\n return send(ctx, \"manualSend\");\n }\n\n private int command(CommandContext<FabricClientCommandSource> ctx) {\n return send(ctx, \"command\");\n }\n\n private int execute(CommandContext<FabricClientCommandSource> ctx) {\n return send(ctx, \"chat\");\n }\n\n public int send(CommandContext<FabricClientCommandSource> ctx, String type) {\n String token = Websocket_clientClient.config.get(\"token\");\n MinecraftClient client = MinecraftClient.getInstance();\n String username = client.player.getName().getString();\n String uuid = client.player.getUuidAsString();\n\n JsonObject obj = new JsonObject();\n obj.addProperty(\"wsToken\", token);\n obj.addProperty(\"username\", username);\n obj.addProperty(\"uuid\", uuid);\n obj.addProperty(\"message\", ctx.getArgument(\"content\", String.class).replace(\"\\n\", \"\\\\n\"));\n obj.addProperty(\"type\", type);\n\n Websocket_clientClient.websocket.send(obj.toString());\n return 0;\n }\n\n\n\n public LiteralArgumentBuilder<FabricClientCommandSource> build(){\n return literal(\"websocket\")\n .then(literal(\"terminate\").executes(this::terminate))\n .then(literal(\"send\")\n .then(argument(\"content\", StringArgumentType.greedyString()).executes(this::manualSend)))\n .then(literal(\"command\")\n .then(argument(\"content\", StringArgumentType.greedyString()).executes(this::command)))\n .then(literal(\"connect\").executes(this::connect))\n .executes(this::execute);\n }\n\n\n\n}" } ]
import com.google.gson.JsonObject; import com.mojang.brigadier.tree.LiteralCommandNode; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import net.phoenix.websocketclient.SimpleConfig; import net.phoenix.websocketclient.WebsocketHandler; import net.phoenix.websocketclient.commands.WebsocketCommand; import java.net.URI; import java.net.URISyntaxException;
2,827
package net.phoenix.websocketclient.client; public class Websocket_clientClient implements ClientModInitializer { public static SimpleConfig config = null; public static WebsocketHandler websocket = null; /** * Runs the mod initializer on the client environment. */ @Override public void onInitializeClient() { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
package net.phoenix.websocketclient.client; public class Websocket_clientClient implements ClientModInitializer { public static SimpleConfig config = null; public static WebsocketHandler websocket = null; /** * Runs the mod initializer on the client environment. */ @Override public void onInitializeClient() { ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
LiteralCommandNode<FabricClientCommandSource> node = dispatcher.register(new WebsocketCommand().build());
2
2023-10-11 16:32:13+00:00
4k
pasindusampath/Spring-Boot-Final
Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/api/GuideAPI.java
[ { "identifier": "GuideDTO", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/dto/GuideDTO.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GuideDTO {\n private int id;\n private String name;\n private String address;\n private String contact;\n private LocalDate birthDate;\n private double manDayValue;\n private String experience;\n private byte[] guideIdFront;\n private byte[] guideIdRear;\n private byte[] nicFront;\n private byte[] nicRear;\n private byte[] profilePic;\n}" }, { "identifier": "SaveFailException", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/exception/SaveFailException.java", "snippet": "public class SaveFailException extends Exception{\n public SaveFailException(String message){\n super(message);\n }\n\n public SaveFailException(String message, Throwable cause){\n super(message, cause);\n }\n}" }, { "identifier": "SearchFailException", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/exception/SearchFailException.java", "snippet": "public class SearchFailException extends Exception{\n public SearchFailException(String message){\n super(message);\n }\n\n public SearchFailException(String message, Throwable cause){\n super(message, cause);\n }\n}" }, { "identifier": "UpdateFailException", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/exception/UpdateFailException.java", "snippet": "public class UpdateFailException extends Exception{\n public UpdateFailException(String message){\n super(message);\n }\n\n public UpdateFailException(String message, Throwable cause){\n super(message, cause);\n }\n}" }, { "identifier": "GuidService", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/service/GuidService.java", "snippet": "public interface GuidService {\n int saveGuide(GuideDTO guideDTO) throws SaveFailException;\n void updateGuide(GuideDTO guideDTO) throws UpdateFailException;\n void deleteGuide(int id) throws DeleteFailException;\n GuideDTO getGuide(int id) throws SearchFailException;\n}" }, { "identifier": "GuideServiceIMPL", "path": "Guide Micro Service/src/main/java/lk/ijse/gdse63/springfinal/service/impl/GuideServiceIMPL.java", "snippet": "@Service\npublic class GuideServiceIMPL implements GuidService {\n ModelMapper mapper;\n Gson gson;\n GuideRepo repo;\n public GuideServiceIMPL(ModelMapper mapper, Gson gson, GuideRepo repo) {\n this.mapper = mapper;\n this.gson = gson;\n this.repo = repo;\n }\n\n @Override\n public int saveGuide(GuideDTO guideDTO) throws SaveFailException {\n try {\n Guide map = mapper.map(guideDTO, Guide.class);\n map.setBirthDate(Date.valueOf(guideDTO.getBirthDate()));\n exportImages(guideDTO, map);\n return repo.save(map).getId();\n }catch (Exception e){\n throw new SaveFailException(\"Operation Fail\", e);\n }\n }\n\n @Override\n public void updateGuide(GuideDTO guideDTO) throws UpdateFailException {\n try {\n Optional<Guide> byId = repo.findById(guideDTO.getId());\n if (byId.isPresent()){\n deleteImages(byId.get());\n Guide map = mapper.map(guideDTO, Guide.class);\n map.setBirthDate(Date.valueOf(guideDTO.getBirthDate()));\n exportImages(guideDTO, map);\n repo.save(map);\n }else {\n throw new NotFoundException(\"Not Found\");\n }\n\n }catch (Exception e){\n throw new UpdateFailException(\"Operation Fail\", e);\n }\n }\n\n @Override\n public void deleteGuide(int id) throws DeleteFailException {\n try {\n repo.findById(id).ifPresent(this::deleteImages);\n repo.deleteById(id);\n\n }catch (Exception e){\n throw new DeleteFailException(\"Operation Fail\", e);\n }\n\n }\n\n @Override\n public GuideDTO getGuide(int id) throws SearchFailException{\n try {\n Optional<Guide> byId = repo.findById(id);\n if (byId.isPresent()){\n GuideDTO guide = mapper.map(byId.get(), GuideDTO.class);\n guide.setBirthDate(byId.get().getBirthDate().toLocalDate());\n importImages(guide,byId.get());\n return guide;\n }\n throw new NotFoundException(\"Not Found\");\n }catch (Exception e){\n throw new SearchFailException(\"Operation Fail\", e);\n }\n }\n\n public void exportImages(GuideDTO guideDTO, Guide guide) {\n String dt = LocalDate.now().toString().replace(\"-\", \"_\") + \"__\"\n + LocalTime.now().toString().replace(\":\", \"_\");\n try {\n InputStream is = new ByteArrayInputStream(guideDTO.getGuideIdFront());\n BufferedImage bi = ImageIO.read(is);\n File outputfile = new File(\"images/guide/front/\" + dt + \"_\" + \".jpg\");\n ImageIO.write(bi, \"jpg\", outputfile);\n guide.setGuideIdFront(outputfile.getAbsolutePath());\n\n is = new ByteArrayInputStream(guideDTO.getGuideIdRear());\n bi = ImageIO.read(is);\n outputfile = new File(\"images/guide/rear/\" + dt + \"_\" + \".jpg\");\n ImageIO.write(bi, \"jpg\", outputfile);\n guide.setGuideIdRear(outputfile.getAbsolutePath());\n\n is = new ByteArrayInputStream(guideDTO.getNicFront());\n bi = ImageIO.read(is);\n outputfile = new File(\"images/guide/nic/front/\" + dt + \"_\" + \".jpg\");\n ImageIO.write(bi, \"jpg\", outputfile);\n guide.setNicFront(outputfile.getAbsolutePath());\n\n is = new ByteArrayInputStream(guideDTO.getNicRear());\n bi = ImageIO.read(is);\n outputfile = new File(\"images/guide/nic/rear/\" + dt + \"_\" + \".jpg\");\n ImageIO.write(bi, \"jpg\", outputfile);\n guide.setNicRear(outputfile.getAbsolutePath());\n\n is = new ByteArrayInputStream(guideDTO.getProfilePic());\n bi = ImageIO.read(is);\n outputfile = new File(\"images/guide/profile/\" + dt + \"_\" + \".jpg\");\n ImageIO.write(bi, \"jpg\", outputfile);\n guide.setProfilePic(outputfile.getAbsolutePath());\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void importImages(GuideDTO guideDTO, Guide guide) {\n try {\n BufferedImage r = ImageIO.read(new File(guide.getGuideIdFront()));\n ByteArrayOutputStream b = new ByteArrayOutputStream();\n ImageIO.write(r, \"jpg\", b);\n byte[] imgData= b.toByteArray();\n guideDTO.setGuideIdFront(imgData);\n\n r = ImageIO.read(new File(guide.getGuideIdRear()));\n b = new ByteArrayOutputStream();\n ImageIO.write(r, \"jpg\", b);\n imgData= b.toByteArray();\n guideDTO.setGuideIdRear(imgData);\n\n r = ImageIO.read(new File(guide.getNicFront()));\n b = new ByteArrayOutputStream();\n ImageIO.write(r, \"jpg\", b);\n imgData= b.toByteArray();\n guideDTO.setNicFront(imgData);\n\n r = ImageIO.read(new File(guide.getNicRear()));\n b = new ByteArrayOutputStream();\n ImageIO.write(r, \"jpg\", b);\n imgData= b.toByteArray();\n guideDTO.setNicRear(imgData);\n\n r = ImageIO.read(new File(guide.getProfilePic()));\n b = new ByteArrayOutputStream();\n ImageIO.write(r, \"jpg\", b);\n imgData= b.toByteArray();\n guideDTO.setProfilePic(imgData);\n\n\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n public void deleteImages(Guide guide) {\n File file = new File(guide.getGuideIdFront());\n boolean delete = file.delete();\n System.out.println(\"Images \" + delete);\n\n file = new File(guide.getGuideIdRear());\n delete = file.delete();\n System.out.println(\"Images \" + delete);\n\n file = new File(guide.getNicFront());\n delete = file.delete();\n System.out.println(\"Images \" + delete);\n\n file = new File(guide.getNicRear());\n delete = file.delete();\n System.out.println(\"Images \" + delete);\n\n file = new File(guide.getProfilePic());\n delete = file.delete();\n System.out.println(\"Images \" + delete);\n\n }\n\n}" } ]
import lk.ijse.gdse63.springfinal.dto.GuideDTO; import lk.ijse.gdse63.springfinal.exception.SaveFailException; import lk.ijse.gdse63.springfinal.exception.SearchFailException; import lk.ijse.gdse63.springfinal.exception.UpdateFailException; import lk.ijse.gdse63.springfinal.service.GuidService; import lk.ijse.gdse63.springfinal.service.impl.GuideServiceIMPL; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.time.LocalDate;
2,932
package lk.ijse.gdse63.springfinal.api; @RestController @RequestMapping("/api/v1/guide") @CrossOrigin public class GuideAPI { GuidService service; public GuideAPI(GuidService service) { this.service = service; } @PostMapping public ResponseEntity saveGuide(@RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { int i = service.saveGuide(guideDTO); return new ResponseEntity<>(i, HttpStatus.CREATED); } catch (SaveFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @DeleteMapping("/{id:\\d+}") public ResponseEntity deleteGuide(@PathVariable int id) { try { service.deleteGuide(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @PutMapping("/{id:\\d+}") public ResponseEntity updateGuide(@PathVariable int id, @RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setId(id); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { service.updateGuide(guideDTO); return new ResponseEntity<>(HttpStatus.OK); } catch (UpdateFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @GetMapping("/{id:\\d+}") public ResponseEntity getGuide(@PathVariable int id) { try { GuideDTO guide = service.getGuide(id); return new ResponseEntity<>(guide, HttpStatus.OK);
package lk.ijse.gdse63.springfinal.api; @RestController @RequestMapping("/api/v1/guide") @CrossOrigin public class GuideAPI { GuidService service; public GuideAPI(GuidService service) { this.service = service; } @PostMapping public ResponseEntity saveGuide(@RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { int i = service.saveGuide(guideDTO); return new ResponseEntity<>(i, HttpStatus.CREATED); } catch (SaveFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @DeleteMapping("/{id:\\d+}") public ResponseEntity deleteGuide(@PathVariable int id) { try { service.deleteGuide(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @PutMapping("/{id:\\d+}") public ResponseEntity updateGuide(@PathVariable int id, @RequestParam("name")String name, @RequestParam("address")String address, @RequestParam("contact") String contact, @RequestParam("birthDate") LocalDate birthDate, @RequestParam("manDayValue") double manDayValue, @RequestParam("experience") String experience, @RequestPart("guideIdFront") byte[] guideIdFront, @RequestPart("guideIdRear") byte[] guideIdRear, @RequestPart("nicFront") byte[] nicFront, @RequestPart("nicRear") byte[] nicRear, @RequestPart("profilePic") byte[] profilePic) { GuideDTO guideDTO = new GuideDTO(); guideDTO.setId(id); guideDTO.setName(name); guideDTO.setAddress(address); guideDTO.setContact(contact); guideDTO.setBirthDate(birthDate); guideDTO.setManDayValue(manDayValue); guideDTO.setExperience(experience); guideDTO.setGuideIdFront(guideIdFront); guideDTO.setGuideIdRear(guideIdRear); guideDTO.setNicFront(nicFront); guideDTO.setNicRear(nicRear); guideDTO.setProfilePic(profilePic); try { service.updateGuide(guideDTO); return new ResponseEntity<>(HttpStatus.OK); } catch (UpdateFailException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT); } } @GetMapping("/{id:\\d+}") public ResponseEntity getGuide(@PathVariable int id) { try { GuideDTO guide = service.getGuide(id); return new ResponseEntity<>(guide, HttpStatus.OK);
} catch (SearchFailException e) {
2
2023-10-15 06:40:35+00:00
4k
juzi45/XianTech
src/main/java/com/qq/xiantech/block/BlockInit.java
[ { "identifier": "XianTech", "path": "src/main/java/com/qq/xiantech/XianTech.java", "snippet": "@Slf4j\n@Mod(XianTech.MOD_ID)\npublic class XianTech {\n\n /**\n * 模组ID,必须和 META-INF/mods.toml中保持一致\n */\n public static final String MOD_ID = \"xiantech\";\n\n public XianTech() {\n // Forge事件总线\n MinecraftForge.EVENT_BUS.register(this);\n\n // Mod事件总线\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // 添加监听方法\n modEventBus.addListener(this::commonSetup);\n modEventBus.addListener(this::addCreative);\n\n BlockInit.BLOCKS.register(modEventBus);\n ItemInit.ITEMS.register(modEventBus);\n TabInit.TABS.register(modEventBus);\n\n // mod加载的上下文中,注册自定义配置类\n ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, XianTechConfiguration.SPEC);\n }\n\n /**\n * mod 加载时的监听\n *\n * @param event FMLCommonSetupEvent\n */\n private void commonSetup(final FMLCommonSetupEvent event) {\n // Some common setup code\n log.info(\"HELLO FROM COMMON SETUP\");\n log.info(\"DIRT BLOCK >> {}\", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));\n\n if (XianTechConfiguration.logDirtBlock) {\n log.info(\"DIRT BLOCK >> {}\", ForgeRegistries.BLOCKS.getKey(Blocks.DIRT));\n }\n\n log.info(XianTechConfiguration.magicNumberIntroduction + XianTechConfiguration.magicNumber);\n\n XianTechConfiguration.items.forEach((item) -> log.info(\"ITEM >> {}\", item.toString()));\n }\n\n /**\n * Add the example block item to the building blocks tab\n *\n * @param event BuildCreativeModeTabContentsEvent\n */\n private void addCreative(BuildCreativeModeTabContentsEvent event) {\n\n }\n\n\n /**\n * 订阅 EventBus 上的事件\n */\n @SubscribeEvent\n public void allEvent(Event event) {\n if (event instanceof RegisterEvent) {\n log.info(\"Event {}\", event);\n }\n }\n\n /**\n * 实例事件\n *\n * @param event ServerStartingEvent\n */\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event) {\n // Do something when the server starts\n log.info(\"HELLO from server starting\");\n }\n\n\n}" }, { "identifier": "DeepSlateStringCrystalOre", "path": "src/main/java/com/qq/xiantech/block/ore/DeepSlateStringCrystalOre.java", "snippet": "public class DeepSlateStringCrystalOre extends Block {\n\n /**\n * 默认属性\n */\n private final static Properties DEFAULT_PROPERTIES = Properties.of()\n .mapColor(MapColor.STONE)\n .sound(SoundType.METAL)\n .strength(2f);\n\n public DeepSlateStringCrystalOre() {\n super(DEFAULT_PROPERTIES);\n }\n\n}" }, { "identifier": "DeepSlateStringCrystalOreItem", "path": "src/main/java/com/qq/xiantech/block/ore/DeepSlateStringCrystalOreItem.java", "snippet": "public class DeepSlateStringCrystalOreItem extends BlockItem {\n\n /**\n * 默认属性\n */\n private final static Item.Properties DEFAULT_PROPERTIES = new Item.Properties();\n\n public DeepSlateStringCrystalOreItem(Block block) {\n super(block, DEFAULT_PROPERTIES);\n }\n\n}" }, { "identifier": "StringCrystalOre", "path": "src/main/java/com/qq/xiantech/block/ore/StringCrystalOre.java", "snippet": "public class StringCrystalOre extends DropExperienceBlock {\n\n /**\n * 默认属性\n */\n private final static Properties DEFAULT_PROPERTIES = Properties.of()\n .mapColor(MapColor.STONE)\n .sound(SoundType.METAL)\n .strength(1f);\n\n /**\n * 掉落经验\n */\n private final static IntProvider DEFAULT_INT_PROVIDER = UniformInt.of(3, 10);\n\n public StringCrystalOre() {\n super(DEFAULT_PROPERTIES, DEFAULT_INT_PROVIDER);\n }\n\n\n}" }, { "identifier": "StringCrystalOreItem", "path": "src/main/java/com/qq/xiantech/block/ore/StringCrystalOreItem.java", "snippet": "public class StringCrystalOreItem extends BlockItem {\n\n /**\n * 默认属性\n */\n private final static Properties DEFAULT_PROPERTIES = new Properties();\n\n public StringCrystalOreItem(Block block) {\n super(block, DEFAULT_PROPERTIES);\n }\n\n\n}" }, { "identifier": "ItemInit", "path": "src/main/java/com/qq/xiantech/item/ItemInit.java", "snippet": "public class ItemInit {\n\n /**\n * 延迟注册器(物品)\n */\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, XianTech.MOD_ID);\n\n public static final RegistryObject<Item> STRING_CRYSTAL = register(\"string_crystal\", StringCrystal::new);\n\n public static final RegistryObject<Item> STRING_ENERGY_BOARD = register(\"string_energy_board\", StringEnergyBoard::new);\n\n\n /**\n * 注册(物品)\n *\n * @param name 注册 ID\n * @param item 物品 Supplier\n * @param <T> ? extends Item\n * @return 注册对象\n */\n public static <T extends Item> RegistryObject<T> register(final String name, final Supplier<T> item) {\n return ITEMS.register(name, item);\n }\n}" } ]
import com.qq.xiantech.XianTech; import com.qq.xiantech.block.ore.DeepSlateStringCrystalOre; import com.qq.xiantech.block.ore.DeepSlateStringCrystalOreItem; import com.qq.xiantech.block.ore.StringCrystalOre; import com.qq.xiantech.block.ore.StringCrystalOreItem; import com.qq.xiantech.item.ItemInit; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import java.util.function.Function; import java.util.function.Supplier;
1,637
package com.qq.xiantech.block; /** * 方块初始化 * * @author Pig-Gua * @date 2023-10-18 */ public class BlockInit { /** * 延迟注册器(方块) */ public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, XianTech.MOD_ID); /** * 延迟注册器(物品) */ public static final DeferredRegister<Item> ITEMS = ItemInit.ITEMS; public static final RegistryObject<Block> STRING_CRYSTAL_ORE = register("string_crystal_ore", StringCrystalOre::new,
package com.qq.xiantech.block; /** * 方块初始化 * * @author Pig-Gua * @date 2023-10-18 */ public class BlockInit { /** * 延迟注册器(方块) */ public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, XianTech.MOD_ID); /** * 延迟注册器(物品) */ public static final DeferredRegister<Item> ITEMS = ItemInit.ITEMS; public static final RegistryObject<Block> STRING_CRYSTAL_ORE = register("string_crystal_ore", StringCrystalOre::new,
object -> () -> new StringCrystalOreItem(object.get()));
4
2023-10-13 12:32:28+00:00
4k
uku3lig/ukuwayplus
src/main/java/net/uku3lig/ukuway/ui/JukeboxScreen.java
[ { "identifier": "UkuwayPlus", "path": "src/main/java/net/uku3lig/ukuway/UkuwayPlus.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class UkuwayPlus implements ClientModInitializer {\n @Getter\n private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.class, \"ukuway-plus\");\n\n @Getter\n private static final Logger logger = LoggerFactory.getLogger(UkuwayPlus.class);\n\n @Getter\n public static final Jukebox jukebox = new Jukebox();\n\n @Getter\n public static final Shop shop = new Shop();\n\n public static final String PUBLIC_BUKKIT_VALUES = \"PublicBukkitValues\";\n\n private long ticksElapsed = 0;\n\n @Override\n public void onInitializeClient() {\n KeyboardManager.register();\n\n if (UkuwayConfig.get().isDiscordRPC()) DiscordManager.start();\n\n ClientTickEvents.END_CLIENT_TICK.register(client -> {\n if (UkuwayPlus.isConnected()) {\n jukebox.tick();\n shop.tick();\n Wardrobe.tick();\n\n if (!FriendListManager.isInit() || client.currentScreen instanceof GenericContainerScreen) {\n FriendListManager.tick();\n }\n }\n\n if (ticksElapsed % 200 == 0) {\n try {\n DiscordManager.update();\n } catch (Exception e) {\n logger.warn(\"An error occurred while updating Discord RPC\", e);\n }\n }\n\n ticksElapsed++;\n });\n }\n\n public static boolean isConnected() {\n if (MinecraftClient.getInstance().getCurrentServerEntry() != null) {\n return MinecraftClient.getInstance().getCurrentServerEntry().address.endsWith(\"playhideaway.com\");\n } else {\n return false;\n }\n }\n\n public static Optional<String> findVersion() {\n return FabricLoader.getInstance().getModContainer(\"ukuway-plus\").map(container -> container.getMetadata().getVersion().getFriendlyString());\n }\n\n public static void setCosmeticVisibility(LivingEntity entity, EquipmentSlot slot, ItemStack oldHeadStack, Consumer<ItemStack> setter) {\n boolean hasCosmetic = entity.getEquippedStack(slot).isOf(Items.LEATHER_HORSE_ARMOR);\n if (hasCosmetic) {\n setter.accept(entity.getEquippedStack(slot));\n if (UkuwayConfig.get().isHideCosmetics()) {\n entity.equipStack(slot, ItemStack.EMPTY);\n }\n } else if (!UkuwayConfig.get().isHideCosmetics() && oldHeadStack != null) {\n entity.equipStack(slot, oldHeadStack);\n }\n }\n}" }, { "identifier": "JukeboxTrack", "path": "src/main/java/net/uku3lig/ukuway/jukebox/JukeboxTrack.java", "snippet": "@AllArgsConstructor\n@Getter\npublic enum JukeboxTrack {\n ACTIVITY_BOUNCE_BATTLE(\n \"Bounce Battle\",\n List.of(createPart(\"activities.bounce_battle_music_loop\", 40)),\n Category.ACTIVITIES\n ),\n ACTIVITY_KING_OF_THE_CASTLE(\n \"King of the Castle\",\n List.of(\n createPart(\"activities.event_jazzyjingle1\", 19),\n createPart(\"activities.event_jazzyjingle2\", 19),\n createPart(\"activities.event_jazzyjingle3\", 19)\n ),\n Category.ACTIVITIES\n ),\n ACTIVITY_JETSKI_RACE(\n \"Jet Ski Race\",\n List.of(createPart(\"activities.jet_ski_race_music_loop\", 34.5)),\n Category.ACTIVITIES\n ),\n ACTIVITY_TREASURE_DIVING(\n \"Treasure Diving\",\n List.of(createPart(\"activities.treasure_diving_music_loop\", 86.5)),\n Category.ACTIVITIES\n ),\n ACTIVITY_VOLLEYBALL(\n \"Volleyball\",\n List.of(createPart(\"activities.volleyball_music_loop\", 46.5)),\n Category.ACTIVITIES\n ),\n\n ARCADE_BIRDSPOTTING(\n \"Birdspotting\",\n List.of(createPart(\"arcade.birdspotting_music_loop\", 25.5)),\n Category.ARCADE\n ),\n ARCADE_BUNCHABUGS(\n \"Bunch-A-Bugs\",\n List.of(createPart(\"arcade.bunchabugs_music_loop\", 22)),\n Category.ARCADE\n ),\n ARCADE_FRUIT_JUICED(\n \"Fruit Juiced\",\n List.of(createPart(\"arcade.fruitjuiced_music_loop\", 31.5)),\n Category.ARCADE\n ),\n ARCADE_SAND_STACKER(\n \"Sand Stacker\",\n List.of(createPart(\"arcade.sandstacker_music_loop\", 23.5)),\n Category.ARCADE\n ),\n ARCADE_SEAFLOOR_URCHINS(\n \"The Seafloor is Urchins\",\n List.of(createPart(\"arcade.theseafloorisurchins_music_loop\", 50.5)),\n Category.ARCADE\n ),\n ARCADE_VOLCANIC_PANIC(\n \"Volcanic Panic\",\n List.of(createPart(\"arcade.volcanicpanic_music_loop\", 34.5)),\n Category.ARCADE\n ),\n\n WARDROBE(\n \"Wardrobe Theme\",\n List.of(createPart(\"ui.wardrobe.song_loop\", 23)),\n Category.MISC\n ),\n\n// fixme These tracks use positional audio (somehow) so function incorrectly\n//\n// ACTIVITY_BREAKFAST(\"Breakfast\", new Identifier(\"hideaway\", \"activities.breakfast_music_loop\"), Category.ACTIVITIES),\n// ACTIVITY_BEACH_BONFIRE(\"Bonfire\", new Identifier(\"hideaway\", \"activities.beach_bonfire_music_loop\"), Category.ACTIVITIES),\n// ACTIVITY_POOL_PARTY(\"Pool Party\", new Identifier(\"hideaway\", \"activities.pool_party_music_loop\"), Category.ACTIVITIES),\n// TITO_TRADEUP_SHACK(\"Tito's Trade-up Shack Theme\", new Identifier(\"hideaway\", \"ambient.tradeup.radio_loop\"), Category.MISC),\n// TINTS_N_TEXTURES(\"Tints'N'Textures Theme\", new Identifier(\"hideaway\", \"ambient.tints_n_textures.radio_loop\"), Category.MISC),\n// UNCLE_GUITAR(\"Uncle's Song\", new Identifier(\"hideaway\", \"ambient.uncle.guitar_loop\"), Category.MISC),\n ;\n\n\n private final String trackName;\n private final List<Part> parts;\n private final Category category;\n\n private static Part createPart(String path, double seconds) {\n return new Part(new Identifier(\"hideaway\", path), (long) (seconds * 20));\n }\n\n public enum Category {\n ARCADE, ACTIVITIES, MISC\n }\n\n public record Part(Identifier id, long length) {\n }\n}" } ]
import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.GridWidget; import net.minecraft.client.gui.widget.SimplePositioningWidget; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Text; import net.uku3lig.ukuway.UkuwayPlus; import net.uku3lig.ukuway.jukebox.JukeboxTrack;
1,827
package net.uku3lig.ukuway.ui; public class JukeboxScreen extends Screen { private final Screen parent; public JukeboxScreen(Screen parent) { super(Text.translatable("jukebox.title")); this.parent = parent; } @Override protected void init() { super.init(); GridWidget grid = new GridWidget(); GridWidget.Adder rowHelper = grid.setSpacing(4).createAdder(2);
package net.uku3lig.ukuway.ui; public class JukeboxScreen extends Screen { private final Screen parent; public JukeboxScreen(Screen parent) { super(Text.translatable("jukebox.title")); this.parent = parent; } @Override protected void init() { super.init(); GridWidget grid = new GridWidget(); GridWidget.Adder rowHelper = grid.setSpacing(4).createAdder(2);
for (JukeboxTrack track : JukeboxTrack.values()) {
1
2023-10-07 00:02:04+00:00
4k
YumiProject/yumi-gradle-licenser
src/main/java/dev/yumi/gradle/licenser/api/rule/HeaderRule.java
[ { "identifier": "RuleToken", "path": "src/main/java/dev/yumi/gradle/licenser/api/rule/token/RuleToken.java", "snippet": "public interface RuleToken {\n}" }, { "identifier": "VariableType", "path": "src/main/java/dev/yumi/gradle/licenser/api/rule/variable/VariableType.java", "snippet": "public interface VariableType<D> {\n\t/**\n\t * The name of the default variable that represents the creation year, whose value is {@value}.\n\t */\n\tString CREATION_YEAR_VAR_NAME = \"CREATION_YEAR\";\n\t/**\n\t * The name of the default variable that represents the file name, whose value is {@value}.\n\t */\n\tString FILE_NAME_VAR_NAME = \"FILE_NAME\";\n\n\t/**\n\t * The known variable types.\n\t */\n\tMap<String, VariableType<?>> TYPES = Map.of(\n\t\t\tCREATION_YEAR_VAR_NAME, CreationYearVariableType.INSTANCE,\n\t\t\tFILE_NAME_VAR_NAME, FileNameVariableType.INSTANCE,\n\t\t\t\"YEAR_LENIENT_RANGE\", YearLenientRangeVariableType.INSTANCE,\n\t\t\t\"YEAR_LIST\", YearListVariableType.INSTANCE\n\t);\n\t/**\n\t * The default variables with their type.\n\t */\n\tMap<String, VariableType<?>> DEFAULT_VARIABLES = Map.of(\n\t\t\tCREATION_YEAR_VAR_NAME, CreationYearVariableType.INSTANCE,\n\t\t\tFILE_NAME_VAR_NAME, FileNameVariableType.INSTANCE\n\t);\n\n\t/**\n\t * Parses the given string input for this variable type.\n\t *\n\t * @param input the string input\n\t * @param start the start index of the variable in the given string input\n\t * @return the parsed data if successful, or {@linkplain Optional#empty() empty} otherwise\n\t */\n\t@Contract(pure = true)\n\t@NotNull Optional<ParseResult<D>> parseVar(@NotNull String input, int start);\n\n\t/**\n\t * Returns the string representation of the given value whose type is this variable type.\n\t *\n\t * @param value the value\n\t * @return the string representation\n\t */\n\t@Contract(pure = true)\n\t@NotNull String getAsString(@NotNull D value);\n\n\t/**\n\t * Returns the up-to-date value for this variable type given the file context and the old value.\n\t *\n\t * @param context the context of which file is updated\n\t * @param old the previous known value for this variable type, or {@code null} if unknown\n\t * @return the up-to-date value for this variable type\n\t */\n\t@NotNull D getUpToDate(@NotNull HeaderFileContext context, @Nullable D old);\n\n\t/**\n\t * Represents the result of a parsed variable.\n\t *\n\t * @param data the data parsed\n\t * @param end the end index of the variable value in the source string\n\t * @param <D> the type of data\n\t */\n\trecord ParseResult<D>(D data, int end) {}\n}" }, { "identifier": "Utils", "path": "src/main/java/dev/yumi/gradle/licenser/util/Utils.java", "snippet": "@ApiStatus.Internal\npublic final class Utils {\n\tprivate Utils() {\n\t\tthrow new UnsupportedOperationException(\"Utils only contains static definitions.\");\n\t}\n\n\t/**\n\t * Matches a character in a string at a given index which could be out of bounds.\n\t *\n\t * @param source the source string\n\t * @param index the index, which may be out of bounds\n\t * @param expected the expected character at the given index\n\t * @return {@code true} if the character matched at the given index, or {@code false} otherwise\n\t */\n\tpublic static boolean matchCharAt(String source, int index, char expected) {\n\t\treturn index >= 0\n\t\t\t\t&& index < source.length()\n\t\t\t\t&& source.charAt(index) == expected;\n\t}\n\n\t/**\n\t * Matches the lack of a character in a string at a given index which could be out of bounds.\n\t *\n\t * @param source the source string\n\t * @param index the index, which may be out of bounds\n\t * @param unexpected the unexpected character at the given index\n\t * @return {@code true} if the character hasn't matched at the given index, or {@code false} otherwise\n\t */\n\tpublic static boolean matchOtherCharAt(String source, int index, char unexpected) {\n\t\treturn index >= 0\n\t\t\t\t&& index < source.length()\n\t\t\t\t&& source.charAt(index) != unexpected;\n\t}\n\n\t/**\n\t * Attempts to read an integer from the given string at the given index.\n\t *\n\t * @param source the string to read from\n\t * @param start the index where the integer should start\n\t * @return the end index of the integer if an integer has been found, or {@code -1} otherwise\n\t */\n\tpublic static int findInteger(@NotNull String source, @Range(from = 0, to = Integer.MAX_VALUE) int start) {\n\t\tfor (int i = start; i < source.length(); i++) {\n\t\t\tchar c = source.charAt(i);\n\n\t\t\tif (!(c >= '0' && c <= '9')) {\n\t\t\t\treturn i == start ? -1 : i;\n\t\t\t}\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\t/**\n\t * Trims empty lines in the given line list.\n\t *\n\t * @param list the line list\n\t * @param emptyPredicate the predicate which returns {@code true} if the given line is empty, or {@code false} otherwise\n\t * @param <T> the type of the lines\n\t */\n\tpublic static <T> void trimLines(@NotNull List<T> list, @NotNull Predicate<T> emptyPredicate) {\n\t\tvar it = list.iterator();\n\t\twhile (it.hasNext()) {\n\t\t\tif (emptyPredicate.test(it.next())) {\n\t\t\t\tit.remove();\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tint toRemoveAtEnd = list.size();\n\t\tfor (int i = toRemoveAtEnd - 1; i >= 0; i--) {\n\t\t\tif (!emptyPredicate.test(list.get(i))) {\n\t\t\t\ttoRemoveAtEnd = i + 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (toRemoveAtEnd != list.size()) {\n\t\t\tlist.subList(toRemoveAtEnd, list.size()).clear();\n\t\t}\n\t}\n\n\t/**\n\t * Gets the backup path for a given source file in the specified project.\n\t *\n\t * @param project the project\n\t * @param rootPath the root path\n\t * @param path the path of the file to back up\n\t * @return the backup path, or {@code null} if something went wrong\n\t * @throws IOException if the backup directories couldn't be created\n\t */\n\tpublic static @Nullable Path getBackupPath(Project project, Path rootPath, Path path) throws IOException {\n\t\tPath backupDir = project.getLayout().getBuildDirectory().getAsFile().get().toPath().resolve(\"yumi/licenser\");\n\n\t\tFiles.createDirectories(backupDir);\n\n\t\tvar pathAsString = path.toAbsolutePath().toString();\n\t\tvar rootPathAsString = rootPath.toString();\n\n\t\tif (pathAsString.startsWith(rootPathAsString)) {\n\t\t\treturn backupDir.resolve(Paths.get(pathAsString.substring(rootPathAsString.length() + 1)))\n\t\t\t\t\t.normalize();\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Gets the project creation year for the given project.\n\t *\n\t * @param project the project\n\t * @return the creation year\n\t */\n\tpublic static int getProjectCreationYear(Project project) {\n\t\tif (project.getRootProject() != project) {\n\t\t\tvar ext = project.getRootProject().getExtensions().findByType(YumiLicenserGradleExtension.class);\n\n\t\t\tif (ext != null) {\n\t\t\t\tif (ext.getProjectCreationYear().isPresent()) {\n\t\t\t\t\treturn ext.getProjectCreationYear().get();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn getProjectCreationYear(project.getRootProject());\n\t\t}\n\n\t\ttry {\n\t\t\tInstant instant = Files.readAttributes(project.getProjectDir().toPath(), BasicFileAttributes.class).creationTime().toInstant();\n\t\t\tLocalDate localDate = LocalDate.ofInstant(instant, ZoneId.systemDefault());\n\t\t\tint localCreationYear = localDate.getYear();\n\n\t\t\treturn localCreationYear;\n\t\t} catch (IOException e) {\n\t\t\tthrow new GradleException(\"Could not read creation year of the root project directory.\");\n\t\t}\n\t}\n}" } ]
import dev.yumi.gradle.licenser.api.rule.token.RuleToken; import dev.yumi.gradle.licenser.api.rule.token.TextToken; import dev.yumi.gradle.licenser.api.rule.token.VarToken; import dev.yumi.gradle.licenser.api.rule.variable.VariableType; import dev.yumi.gradle.licenser.util.Utils; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnmodifiableView; import java.util.*;
3,384
/* * Copyright 2023 Yumi Project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package dev.yumi.gradle.licenser.api.rule; /** * Represents a header rule which describes how a header should look like. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ public class HeaderRule { private final String name; private final List<HeaderLine> lines; private final Map<String, VariableType<?>> variables; private final LicenseYearSelectionMode yearSelectionMode; public HeaderRule( @NotNull String name, @NotNull List<HeaderLine> lines, @NotNull Map<String, VariableType<?>> variables, @NotNull LicenseYearSelectionMode yearSelectionMode ) { this.name = name; this.lines = lines; this.variables = variables; this.yearSelectionMode = yearSelectionMode; } /** * {@return the name of this header rule} */ @Contract(pure = true) public @NotNull String getName() { return this.name; } /** * {@return a view of the lines of this header} */ @Contract(pure = true) public @UnmodifiableView @NotNull List<HeaderLine> getLines() { return Collections.unmodifiableList(this.lines); } /** * {@return the year selection mode} */ @Contract(pure = true) public @NotNull LicenseYearSelectionMode getYearSelectionMode() { return this.yearSelectionMode; } /** * Parses the given header according to the current rules, may throw an exception if the header is not valid. * * @param header the header to check * @return parsed data, contain the successfully parsed variables, and the error if parsing failed */ public @NotNull ParsedData parseHeader(@NotNull List<String> header) { var variableValues = new HashMap<String, Object>(); var presentOptionalLines = new HashSet<Integer>(); int headerLineIndex = 0, ruleLineIndex = 0; for (; headerLineIndex < header.size(); headerLineIndex++) { String headerLine = header.get(headerLineIndex); if (ruleLineIndex >= this.lines.size()) { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, "There is unexpected extra header lines.")); } HeaderLine ruleLine = this.lines.get(ruleLineIndex); String error; while ((error = this.parseLine(headerLine, ruleLine, variableValues)) != null) { if (ruleLine.optional()) { // If the line is optional, attempts to check the next line. ruleLine = this.lines.get(++ruleLineIndex); } else { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, error)); } } if (ruleLine.optional()) { presentOptionalLines.add(ruleLineIndex); } ruleLineIndex++; } return new ParsedData(variableValues, presentOptionalLines, null); } private @Nullable String parseLine( @NotNull String headerLine, @NotNull HeaderLine currentLine, @NotNull Map<String, Object> variablesMap ) { int currentIndex = 0; for (var token : currentLine.tokens()) { if (token instanceof TextToken textToken) { String text = textToken.content(); int theoreticalEnd = currentIndex + text.length(); if (theoreticalEnd > headerLine.length()) { return "Header is cut short, stopped at " + headerLine.length() + " instead of " + theoreticalEnd + "."; } String toCheck = headerLine.substring(currentIndex, theoreticalEnd); if (!text.equals(toCheck)) { return "Text differs at " + currentIndex + ", got \"" + toCheck + "\", expected \"" + text + "\"."; } currentIndex = currentIndex + text.length(); } else if (token instanceof VarToken varToken) { var type = this.variables.get(varToken.variable()); var result = type.parseVar(headerLine, currentIndex); if (result.isEmpty()) { return "Failed to parse variable \"" + varToken.variable() + "\" at " + currentIndex + "."; } var old = variablesMap.put(varToken.variable(), result.get().data()); if (old != null && !old.equals(result.get().data())) { return "Diverging variable values for \"" + varToken.variable() + "\"."; } currentIndex = result.get().end(); } } return null; } /** * Applies this header rule to the provided parsed data to create a valid up-to-date header comment. * * @param data the data parsed by attempting to read the header comment * @param context the context of the file to update * @return the updated header comment */ @SuppressWarnings({"rawtypes", "unchecked"}) public @NotNull List<String> apply(@NotNull ParsedData data, @NotNull HeaderFileContext context) { var result = new ArrayList<String>(); for (int i = 0; i < this.lines.size(); i++) { var line = this.lines.get(i); if (!line.optional() || data.presentOptionalLines.contains(i)) { var builder = new StringBuilder(); for (var token : line.tokens()) { if (token instanceof TextToken textToken) { builder.append(textToken.content()); } else if (token instanceof VarToken varToken) { var type = (VariableType) this.variables.get(varToken.variable()); var previous = data.variables.get(varToken.variable()); var newValue = type.getUpToDate(context, previous); builder.append(type.getAsString(newValue)); } } result.add(builder.toString()); } }
/* * Copyright 2023 Yumi Project * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package dev.yumi.gradle.licenser.api.rule; /** * Represents a header rule which describes how a header should look like. * * @author LambdAurora * @version 1.0.0 * @since 1.0.0 */ public class HeaderRule { private final String name; private final List<HeaderLine> lines; private final Map<String, VariableType<?>> variables; private final LicenseYearSelectionMode yearSelectionMode; public HeaderRule( @NotNull String name, @NotNull List<HeaderLine> lines, @NotNull Map<String, VariableType<?>> variables, @NotNull LicenseYearSelectionMode yearSelectionMode ) { this.name = name; this.lines = lines; this.variables = variables; this.yearSelectionMode = yearSelectionMode; } /** * {@return the name of this header rule} */ @Contract(pure = true) public @NotNull String getName() { return this.name; } /** * {@return a view of the lines of this header} */ @Contract(pure = true) public @UnmodifiableView @NotNull List<HeaderLine> getLines() { return Collections.unmodifiableList(this.lines); } /** * {@return the year selection mode} */ @Contract(pure = true) public @NotNull LicenseYearSelectionMode getYearSelectionMode() { return this.yearSelectionMode; } /** * Parses the given header according to the current rules, may throw an exception if the header is not valid. * * @param header the header to check * @return parsed data, contain the successfully parsed variables, and the error if parsing failed */ public @NotNull ParsedData parseHeader(@NotNull List<String> header) { var variableValues = new HashMap<String, Object>(); var presentOptionalLines = new HashSet<Integer>(); int headerLineIndex = 0, ruleLineIndex = 0; for (; headerLineIndex < header.size(); headerLineIndex++) { String headerLine = header.get(headerLineIndex); if (ruleLineIndex >= this.lines.size()) { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, "There is unexpected extra header lines.")); } HeaderLine ruleLine = this.lines.get(ruleLineIndex); String error; while ((error = this.parseLine(headerLine, ruleLine, variableValues)) != null) { if (ruleLine.optional()) { // If the line is optional, attempts to check the next line. ruleLine = this.lines.get(++ruleLineIndex); } else { return new ParsedData(variableValues, presentOptionalLines, new HeaderParseException(headerLineIndex, error)); } } if (ruleLine.optional()) { presentOptionalLines.add(ruleLineIndex); } ruleLineIndex++; } return new ParsedData(variableValues, presentOptionalLines, null); } private @Nullable String parseLine( @NotNull String headerLine, @NotNull HeaderLine currentLine, @NotNull Map<String, Object> variablesMap ) { int currentIndex = 0; for (var token : currentLine.tokens()) { if (token instanceof TextToken textToken) { String text = textToken.content(); int theoreticalEnd = currentIndex + text.length(); if (theoreticalEnd > headerLine.length()) { return "Header is cut short, stopped at " + headerLine.length() + " instead of " + theoreticalEnd + "."; } String toCheck = headerLine.substring(currentIndex, theoreticalEnd); if (!text.equals(toCheck)) { return "Text differs at " + currentIndex + ", got \"" + toCheck + "\", expected \"" + text + "\"."; } currentIndex = currentIndex + text.length(); } else if (token instanceof VarToken varToken) { var type = this.variables.get(varToken.variable()); var result = type.parseVar(headerLine, currentIndex); if (result.isEmpty()) { return "Failed to parse variable \"" + varToken.variable() + "\" at " + currentIndex + "."; } var old = variablesMap.put(varToken.variable(), result.get().data()); if (old != null && !old.equals(result.get().data())) { return "Diverging variable values for \"" + varToken.variable() + "\"."; } currentIndex = result.get().end(); } } return null; } /** * Applies this header rule to the provided parsed data to create a valid up-to-date header comment. * * @param data the data parsed by attempting to read the header comment * @param context the context of the file to update * @return the updated header comment */ @SuppressWarnings({"rawtypes", "unchecked"}) public @NotNull List<String> apply(@NotNull ParsedData data, @NotNull HeaderFileContext context) { var result = new ArrayList<String>(); for (int i = 0; i < this.lines.size(); i++) { var line = this.lines.get(i); if (!line.optional() || data.presentOptionalLines.contains(i)) { var builder = new StringBuilder(); for (var token : line.tokens()) { if (token instanceof TextToken textToken) { builder.append(textToken.content()); } else if (token instanceof VarToken varToken) { var type = (VariableType) this.variables.get(varToken.variable()); var previous = data.variables.get(varToken.variable()); var newValue = type.getUpToDate(context, previous); builder.append(type.getAsString(newValue)); } } result.add(builder.toString()); } }
Utils.trimLines(result, String::isEmpty);
2
2023-10-08 20:51:43+00:00
4k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/library/gyroscopes/pigeon2/SubSys_PigeonGyro.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n public static final class Robot {\n\n public static final class Calibrations {\n\n public static final class DriveTrain {\n public static final double PerfModeTransitionTime = 2.0; // s\n\n public static final class PerformanceMode_Default {\n // Default Performance Mode Speeds\n public static double DriveTrainMaxPctOutput = 0.50; // 0-1\n public static double DriveTrainMaxSpd = 4.0; // m/s\n public static double DriveTrainMaxAccel = 0.35; // m/s^2\n public static double DriveTrainMaxRotPctOutput = 0.4; // 0-1\n public static double DriveTrainMaxRotSpd = 250 * Math.PI / 180; // rad/s\n public static double DriveTrainMaxRotAccel = 200 * Math.PI / 180; // rad/s^2\n }\n\n public static final class PerformanceMode_A {\n // Performance Mode A Speeds (Slow)\n public static double DriveTrainMaxPctOutput = 0.25; // 0-1\n public static double DriveTrainMaxSpd = 2.0; // m/s\n public static double DriveTrainMaxAccel = 0.35; // m/s^2\n public static double DriveTrainMaxRotPctOutput = 0.6; // 0-1\n public static double DriveTrainMaxRotSpd = 100 * Math.PI / 180; // rad/s\n public static double DriveTrainMaxRotAccel = 100 * Math.PI / 180; // rad/s^2\n }\n\n public static final class PerformanceMode_B {\n // Performance Mode B Speeds (Fast)\n public static double DriveTrainMaxPctOutput = 0.75; // 0-1\n public static double DriveTrainMaxSpd = 5; // m/s\n public static double DriveTrainMaxAccel = 1.00; // m/s^2\n public static double DriveTrainMaxRotPctOutput = 0.2; // 0-1\n public static double DriveTrainMaxRotSpd = 360 * Math.PI / 180; // rad/s\n public static double DriveTrainMaxRotAccel = 360 * Math.PI / 180; // rad/s^2\n }\n\n public static final class DriveTrainTrajSettings {\n // PathPlanner Speeds\n public static double DriveTrainMaxPctOutput = 0.50; // 0-1\n public static double DriveTrainMaxSpd = 4.0; // m/s\n public static double DriveTrainMaxAccel = 0.35; // m/s^2\n public static double DriveTrainMaxRotPctOutput = 0.4; // 0-1\n public static double DriveTrainMaxRotSpd = 140 * Math.PI / 180; // rad/s\n public static double DriveTrainMaxRotAccel = 200 * Math.PI / 180; // rad/s^2\n }\n }\n\n public static final class Arm {\n public static double ArmMaxRotSpd = 100 * Math.PI / 150; // rad/s //150\n public static double ArmMaxRotAccel = 150 * Math.PI / 180; // rad/s/s\n\n public static double ArmExtensionMaxSpd = 0.5; // m/s\n public static double ArmExtensionMaxAccel = 0.5; // m/s/s\n\n public static double ArmExtendPosCtrlFastSpd = 0.8; // %\n public static double ArmExtendPosCtrlSlowRange = 0.1; // m\n public static double ArmExtendPosCtrlSlowSpd = 0.15; // %\n public static double ArmExtendPosCtrlAtPositionRange = 0.02; // m\n\n public static double HighConeArmPosInit = -158; // degree\n public static double HighConeArmExtensionInit = -158; // degree\n public static double HighConeArmPosFinal = -158; // degree\n public static double HighConeArmExtensionFinal = -158; // degree\n }\n }\n\n public static final class MaxSpeeds {\n // Maximum Achieveable Speeds\n public static final class DriveTrain {\n // public static double DriveTrainMaxPctOutput = 1.00; // 0-1\n public static double DriveTrainMaxSpd = 5.4; // m/s\n public static double DriveTrainMaxAccel = 5.0; // m/s^2\n // public static double DriveTrainMaxRotPctOutput = 1.0; // 0-1\n public static double DriveTrainMaxRotSpeed = 360 * Math.PI / 180; // rad/s\n public static double DriveTrainMaxRotAccel = 360 * Math.PI / 180; // rad/s^2\n }\n\n public static final class Arm {\n public static double ArmShoulderMaxRotSpd = 360 * Math.PI / 180; // rad/s\n public static double ArmShoulderMaxRotAccel = 360 * Math.PI / 180; // rad/s\n\n public static double ArmExtensionMaxSpd = 1.0; // m/s\n public static double ArmExtensionMaxAccel = 1.0; // m/s/s\n }\n }\n\n public static final class Dimensions {\n\n public static final class Frame {\n // Robot Origin (0,0,0 at center and bottom of wheels)\n public static final Translation3d FrameOrigin = new Translation3d(0, 0, 0);\n\n public static final double Length = Units.inchesToMeters(23.75);\n public static final double Width = Units.inchesToMeters(23.85);\n public static final double BumperThickness = Units.inchesToMeters(3.25);\n }\n\n public static final class DriveTrain {\n public static final double WheelBase = Units.inchesToMeters(18.5);\n public static final double TrackWidth = Units.inchesToMeters(18.5);\n }\n\n public static final class Arm {\n public static final Translation3d ArmShoulder =\n new Translation3d(\n Units.inchesToMeters(-2.0),\n Units.inchesToMeters(.0),\n Units.inchesToMeters(23.5)); // Relative to Frame Origin\n public static final double ArmMinLength = Units.inchesToMeters(22);\n public static final double ArmMaxExtensionLength = Units.inchesToMeters(54.5);\n }\n\n public static final class Hand {\n public static final double HandForwardLength = Units.inchesToMeters(9.75);\n public static final double HandRetractLength = Units.inchesToMeters(7.75);\n }\n\n public static final class RobotBoundaries {\n public static final double MaxExtensionOverFrame = 1.20; // .120m or 120cm (width)\n public static final double MaxHeight = 1.98; // .198m or 198cm (Height)\n public static final double MinHeight = 0.01;\n }\n\n public static final class Limelight {\n public static final double kCameraHeight = Units.inchesToMeters(35); // m\n public static final double kCameraAngle = 29.0; // Degrees\n }\n }\n }\n\n public static final class Field {\n public static final class Hub {\n public static final Translation2d kHubCenter =\n new Translation2d(Units.inchesToMeters(324), Units.inchesToMeters(162));\n\n public static final Translation2d kH1 =\n new Translation2d(Units.inchesToMeters(308), Units.inchesToMeters(130));\n\n public static final Translation2d kH2 =\n new Translation2d(Units.inchesToMeters(294), Units.inchesToMeters(174));\n\n public static final double kTargetRingHeight = Units.inchesToMeters(105);\n\n public static final double kTargetRingDist2Ctr = Units.inchesToMeters(26);\n }\n\n public static final class Tarmac {\n public static final Translation2d kT11 =\n new Translation2d(Units.inchesToMeters(364), Units.inchesToMeters(53));\n\n public static final Translation2d kT12 =\n new Translation2d(Units.inchesToMeters(281), Units.inchesToMeters(51));\n\n public static final Translation2d kT13 =\n new Translation2d(Units.inchesToMeters(221), Units.inchesToMeters(108));\n }\n }\n\n public static final class CAN_IDs {\n public static final int PDP_CAN_ID = 1;\n public static final int PCM_CAN_ID = 2;\n\n public static final int Pigeon2_ID = 20;\n\n public static final int ArmShoulderMtr_CAN_ID = 30;\n public static final int ArmShoulderFollowerMtr_CAN_ID = 35;\n public static final int ArmShoulderCANCoder_CAN_ID = 31;\n public static final int ArmExtensionMtr_CAN_ID = 32;\n public static final int ArmExtensionCANCoder_CAN_ID = 34;\n\n public static final int FrontLeftDriveMtr_CAN_ID = 51;\n public static final int FrontLeftSteerMtr_CAN_ID = 52;\n public static final int FrontLeftSteerCANCoder_CAN_ID = 53;\n public static final int FrontRightDriveMtr_CAN_ID = 54;\n public static final int FrontRightSteerMtr_CAN_ID = 55;\n public static final int FrontRightSteerCANCoder_CAN_ID = 56;\n public static final int BackLeftDriveMtr_CAN_ID = 57;\n public static final int BackLeftSteerMtr_CAN_ID = 58;\n public static final int BackLeftSteerCANCoder_CAN_ID = 59;\n public static final int BackRightDriveMtr_CAN_ID = 60;\n public static final int BackRightSteerMtr_CAN_ID = 61;\n public static final int BackRightSteerCANCoder_CAN_ID = 62;\n }\n\n public static final class AnalogInput_IDs {}\n\n public static final class DigitalIO_IDs {}\n\n public static final class PWM_IDs {}\n}" }, { "identifier": "SubSys_NavXGyro_Constants", "path": "src/main/java/frc/robot/library/gyroscopes/navx/SubSys_NavXGyro_Constants.java", "snippet": "public class SubSys_NavXGyro_Constants {\n\n // NavXGyro Subsystem Enable Shuffleboard\n public static final boolean NavXGyroSubSys_Shuffleboard_Enable = true;\n\n // Gyro Reversed\n public static final boolean GyroReversed = false;\n}" } ]
import com.ctre.phoenix.sensors.Pigeon2; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.library.gyroscopes.navx.SubSys_NavXGyro_Constants;
3,167
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.library.gyroscopes.pigeon2; public class SubSys_PigeonGyro extends SubsystemBase { /** Creates a new NavXGyro. */ private Pigeon2 pigeon2Gyro; private double gyroOffsetDegrees; public SubSys_PigeonGyro() { this.pigeon2Gyro = new Pigeon2(Constants.CAN_IDs.Pigeon2_ID); this.gyroOffsetDegrees = 0.0; // m_Pigeon2Gyro.setYaw(0); } @Override public void periodic() { // This method will be called once per scheduler run // Display SmartDashboard.putNumber("Pigeon_getRawYaw", getRawYaw()); SmartDashboard.putNumber("Pigeon_getYaw", getYaw()); SmartDashboard.putNumber("Pigeon_getYawRotation2d", getYawRotation2d().getDegrees()); // SmartDashboard.putNumber("GyroCompass", m_Pigeon2Gyro.getCompassHeading()); } public double getRawGyroPitch() { return this.pigeon2Gyro.getPitch(); } public double getRawGyroRoll() { return this.pigeon2Gyro.getRoll(); } /** * Return Raw Gyro Angle * * @return Raw Angle double raw Gyro Angle */ public double getRawYaw() { return this.pigeon2Gyro.getYaw(); } public double getYaw() { return getRawYaw() - this.gyroOffsetDegrees; } /** * Return Gyro Angle in Degrees * * @return Gyro Angle double Degrees */ public double getYawAngle() { return Math.IEEEremainder(getYaw(), 360)
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.library.gyroscopes.pigeon2; public class SubSys_PigeonGyro extends SubsystemBase { /** Creates a new NavXGyro. */ private Pigeon2 pigeon2Gyro; private double gyroOffsetDegrees; public SubSys_PigeonGyro() { this.pigeon2Gyro = new Pigeon2(Constants.CAN_IDs.Pigeon2_ID); this.gyroOffsetDegrees = 0.0; // m_Pigeon2Gyro.setYaw(0); } @Override public void periodic() { // This method will be called once per scheduler run // Display SmartDashboard.putNumber("Pigeon_getRawYaw", getRawYaw()); SmartDashboard.putNumber("Pigeon_getYaw", getYaw()); SmartDashboard.putNumber("Pigeon_getYawRotation2d", getYawRotation2d().getDegrees()); // SmartDashboard.putNumber("GyroCompass", m_Pigeon2Gyro.getCompassHeading()); } public double getRawGyroPitch() { return this.pigeon2Gyro.getPitch(); } public double getRawGyroRoll() { return this.pigeon2Gyro.getRoll(); } /** * Return Raw Gyro Angle * * @return Raw Angle double raw Gyro Angle */ public double getRawYaw() { return this.pigeon2Gyro.getYaw(); } public double getYaw() { return getRawYaw() - this.gyroOffsetDegrees; } /** * Return Gyro Angle in Degrees * * @return Gyro Angle double Degrees */ public double getYawAngle() { return Math.IEEEremainder(getYaw(), 360)
* (SubSys_NavXGyro_Constants.GyroReversed ? -1.0 : 1.0);
1
2023-10-09 00:27:11+00:00
4k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/parser/LogParser.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n private long size;\n @JsonIgnore\n private boolean deleted = false;\n private long signature;\n private int signatureLength;\n @JsonIgnore\n private boolean changed = false;\n @JsonIgnore\n private RandomAccessFile raFile;\n private long pointer = 0;\n private long newPointer = 0; // указатель на позицию после чтения записей лога ДО подтверждения получения клиентом; ПОСЛЕ подтверждения нужно pointer = newPointer\n @JsonIgnore\n private FileState oldFileState;\n @JsonIgnore\n private PredefinedFields fields;\n @JsonIgnore\n private Filter filter;\n @JsonIgnore\n private boolean matchedToNewFile = false;\n @JsonProperty(\"log format\")\n private LogFormat logFormat;\n private String encoding;\n \n public FileState() {\n }\n\n public FileState(File file) throws IOException {\n this.file = file;\n directory = file.getCanonicalFile().getParent();\n fileName = file.getName();\n raFile = null;\n lastModified = file.lastModified();\n size = file.length();\n logFormat = null;\n encoding = \"UTF-8\";\n }\n\n private void setFileFromDirectoryAndName() throws FileNotFoundException, IOException {\n file = new File(directory + File.separator + fileName);\n if (file.exists()) {\n directory = file.getCanonicalFile().getParent();\n raFile = null;\n lastModified = file.lastModified();\n size = file.length();\n }\n else {\n deleted = true;\n }\n }\n\n public File getFile() {\n return file;\n }\n\n public long getLastModified() {\n return lastModified;\n }\n\n public long getSize() {\n return size;\n }\n\n public String getDirectory() {\n return directory;\n }\n\n public void setDirectory(String directory) throws FileNotFoundException, IOException {\n this.directory = directory;\n if (fileName != null && directory != null) {\n setFileFromDirectoryAndName();\n }\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public void setFileName(String fileName) throws FileNotFoundException, IOException {\n this.fileName = fileName;\n if (fileName != null && directory != null) {\n setFileFromDirectoryAndName();\n }\n }\n\n public boolean isDeleted() {\n return deleted || file == null || !file.exists();\n }\n\n public void setDeleted() {\n deleted = true;\n }\n\n public boolean hasChanged() {\n return changed;\n }\n\n public void setChanged(boolean changed) {\n this.changed = changed;\n }\n\n public long getSignature() {\n return signature;\n }\n\n public void setSignature(long signature) {\n this.signature = signature;\n }\n\n @JsonIgnore\n public RandomAccessFile getRandomAccessFile() {\n return file.exists() ? raFile : null;\n }\n\n @JsonIgnore\n public RandomAccessFile getOpenedRandomAccessFile() {\n if (!isRandomAccessFileOpened()) {\n try {\n // reopen random access file if it closed\n raFile = new RandomAccessFile(file, \"r\");\n }\n catch (FileNotFoundException ex) {\n raFile = null; // was nothing\n }\n }\n return raFile;\n }\n\n public long getPointer() {\n return pointer;\n }\n\n public void setPointer(long pointer) {\n this.pointer = pointer;\n }\n\n public long getNewPointer() {\n return newPointer;\n }\n\n public void setNewPointer(long newPointer) {\n this.newPointer = newPointer;\n }\n \n public int getSignatureLength() {\n return signatureLength;\n }\n\n public void setSignatureLength(int signatureLength) {\n this.signatureLength = signatureLength;\n }\n\n public FileState getOldFileState() {\n return oldFileState;\n }\n\n public void setOldFileState(FileState oldFileState) {\n this.oldFileState = oldFileState;\n oldFileState.setMatchedToNewFile(true);\n }\n \n @JsonIgnore\n public boolean isRandomAccessFileOpened() {\n if (raFile == null) {\n return false;\n }\n try {\n raFile.getFilePointer(); // check for random access file readability\n return true;\n }\n catch (IOException e) {\n return false;\n }\n }\n \n public final boolean closeRandomAccessFile() {\n try {\n if (isRandomAccessFileOpened()) {\n getRandomAccessFile().close();\n }\n return true;\n }\n catch (IOException e) {\n return false;\n }\n }\n\n public void deleteOldFileState() {\n if (oldFileState.closeRandomAccessFile()) {\n oldFileState = null;\n }\n }\n\n public PredefinedFields getFields() {\n return fields;\n }\n\n public void setFields(PredefinedFields fields) {\n this.fields = fields;\n }\n\n public Filter getFilter() {\n return filter;\n }\n\n public void setFilter(Filter filter) {\n this.filter = filter;\n }\n\n public LogFormat getLogFormat() {\n return logFormat;\n }\n\n public void setLogFormat(LogFormat logFormat) {\n this.logFormat = logFormat;\n }\n\n public void setLogFormat(String kind) {\n if (\"one_c_tech_journal\".equalsIgnoreCase(kind)) {\n this.logFormat = LogFormat.ONE_C_TECH_JOURNAL;\n }\n else if (\"perfomance_monitor\".equalsIgnoreCase(kind)) {\n this.logFormat = LogFormat.PERFOMANCE_MONITOR;\n }\n }\n\n public String getEncoding() {\n return encoding;\n }\n\n public void setEncoding(String encoding) {\n this.encoding = encoding;\n }\n\n public boolean isMatchedToNewFile() {\n return matchedToNewFile;\n }\n\n public void setMatchedToNewFile(boolean matchedToNewFile) {\n this.matchedToNewFile = matchedToNewFile;\n }\n \n public long length() {\n return file == null ? 0 : file.length();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this).\n append(\"fileName\", fileName).\n append(\"directory\", directory).\n append(\"pointer\", pointer).\n append(\"newPointer\", newPointer).\n append(\"signature\", signature).\n append(\"signatureLength\", signatureLength).\n append(\"encoding\", encoding).\n toString();\n }\n\n}" }, { "identifier": "Filter", "path": "src/main/java/com/monitor/agent/server/filter/Filter.java", "snippet": "public class Filter {\n \n @JsonIgnore\n Filter source = null;\n \n public static Filter fromJson(String filterJson) throws UnsupportedEncodingException, JsonProcessingException {\n ObjectMapper mapper = new ObjectMapper();\n mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);\n\n Map<String, Object> filtersMap = mapper.readValue(filterJson, Map.class);\n return fromMap(filtersMap);\n }\n\n public static Filter fromMap(Map<String, Object> map) throws UnsupportedEncodingException, IllegalArgumentException {\n Filter result;\n \n if (map == null) {\n result = null;\n }\n else if (map.containsKey(\"pattern\")) {\n result = new FilterValue(map);\n }\n else if (map.containsKey(\"and\")) {\n FilterAnd filterAnd = new FilterAnd();\n ArrayList<Map<String, Object>> filterMaps = (ArrayList<Map<String, Object>>) map.get(\"and\");\n for (Map<String, Object> filterMap : filterMaps) {\n Filter filter = Filter.fromMap(filterMap);\n filterAnd.add(filter);\n }\n result = filterAnd;\n }\n else if (map.containsKey(\"or\")) {\n FilterOr filterOr = new FilterOr();\n ArrayList<Map<String, Object>> filterMaps = (ArrayList<Map<String, Object>>) map.get(\"or\");\n for (Map<String, Object> filterMap : filterMaps) {\n Filter filter = Filter.fromMap(filterMap);\n filterOr.add(filter);\n }\n result = filterOr;\n }\n else if (map.containsKey(\"not\")) {\n Filter filter = Filter.fromMap((Map<String, Object>) map.get(\"not\"));\n result = new FilterNot(filter);\n }\n else {\n throw new IllegalArgumentException();\n }\n \n return result;\n }\n \n public static Filter and(Filter f1, Filter f2) {\n if (f1 != null && f2 != null) {\n return new FilterAnd().add(f1).add(f2);\n }\n if (f1 != null) {\n return f1;\n }\n return f2;\n }\n \n public boolean accept(Map<String, Object> record) {\n return false;\n }\n\n public Filter copy() {\n ObjectMapper mapper = new ObjectMapper();\n try {\n Filter clone = fromMap(mapper.readValue(mapper.writeValueAsString(this), Map.class));\n clone.source = source == null ? this : source;\n return clone;\n }\n catch (JsonProcessingException | UnsupportedEncodingException ex) {\n throw new RuntimeException(ex);\n }\n }\n\n @Override\n public int hashCode() {\n if (source != null) {\n return source.hashCode();\n }\n return super.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Filter other = (Filter) obj;\n if (source != null && source == other.source \n || source != null && source == other \n || other.source != null && other.source == this) {\n return true;\n }\n return super.equals(other);\n }\n \n}" }, { "identifier": "ParserRecordsStorage", "path": "src/main/java/com/monitor/parser/reader/ParserRecordsStorage.java", "snippet": "public interface ParserRecordsStorage {\r\n \r\n public void put(byte[] record) throws Exception;\r\n \r\n public int size();\r\n \r\n public void clear();\r\n \r\n public List<byte[]> getAll();\r\n\r\n}\r" } ]
import com.monitor.agent.server.FileState; import com.monitor.agent.server.filter.Filter; import com.monitor.parser.reader.ParserRecordsStorage; import java.io.IOException;
2,810
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public interface LogParser { public void parse(FileState state, String encoding, long fromPosition, int maxRecords, Filter filter, ParserParameters parameters) throws IOException, ParseException;
package com.monitor.parser; /* * Copyright 2021 Aleksei Andreev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ public interface LogParser { public void parse(FileState state, String encoding, long fromPosition, int maxRecords, Filter filter, ParserParameters parameters) throws IOException, ParseException;
public void setRecordsStorage(ParserRecordsStorage storage);
2
2023-10-11 20:25:12+00:00
4k
mhaupt/basicode
src/test/java/de/haupz/basicode/DimTest.java
[ { "identifier": "ArrayType", "path": "src/main/java/de/haupz/basicode/array/ArrayType.java", "snippet": "public enum ArrayType {\n NUMBER,\n STRING;\n}" }, { "identifier": "BasicArray", "path": "src/main/java/de/haupz/basicode/array/BasicArray.java", "snippet": "public abstract class BasicArray {\n\n /**\n * The type of data (numbers or strings) this array contains.\n */\n private final ArrayType type;\n\n /**\n * The actual data storage.\n */\n protected final Object[] data;\n\n /**\n * Create a BASIC array and fill it with default values (0 for numbers, or empty strings).\n *\n * @param type the type of data stored in this array.\n * @param storageSize the number of elements this array will contain.\n */\n protected BasicArray(ArrayType type, int storageSize) {\n this.type = type;\n data = new Object[storageSize];\n switch (type) {\n case NUMBER -> Arrays.fill(data, Double.valueOf(0.0));\n case STRING -> Arrays.fill(data, \"\");\n }\n }\n\n /**\n * @return the type of data this array stores.\n */\n public ArrayType getType() {\n return type;\n }\n\n /**\n * @return the number of elements on this array's first dimension.\n */\n public abstract int getDim1();\n\n /**\n * @return the number of elements on this array's second dimension. This will throw an exception if called on\n * one-dimensional arrays.\n */\n public abstract int getDim2();\n\n /**\n * @return {@code true} if this is a one-dimensional array.\n */\n public boolean is1D() {\n return false;\n }\n\n /**\n * @return {@code true} if this is a two-dimensional array.\n */\n public boolean is2D() {\n return false;\n }\n\n /**\n * Retrieve an element from this array.\n *\n * @param a the index into the first dimension of this array.\n * @param b the index into the second dimension of this array. This will be ignored by one-dimensional arrays.\n * @return the element at the specified position.\n */\n public abstract Object at(int a, int b);\n\n /**\n * Store an element in this array.\n *\n * @param a the index into the first dimension of this array.\n * @param b the index into the second dimension of this array. This will be ignored by one-dimensional arrays.\n * @param v the value to store.\n */\n public abstract void setAt(int a, int b, Object v);\n\n}" }, { "identifier": "BasicArray1D", "path": "src/main/java/de/haupz/basicode/array/BasicArray1D.java", "snippet": "public class BasicArray1D extends BasicArray {\n\n /**\n * The size of this array. Note that it will be one greater than the value given for initialisation, as a BASIC\n * array with a size of {@code N} can have indices in the range 0 <= {@code i} <= {@code N}.\n */\n private final int dim;\n\n /**\n * Construct a one-dimensional BASIC array.\n *\n * @param type the array's type.\n * @param d the {@linkplain BasicArray1D#dim dimension} of the array.\n */\n public BasicArray1D(ArrayType type, int d) {\n super(type, d + 1);\n dim = d + 1;\n }\n\n /**\n * @return the {@linkplain BasicArray1D#dim dimension} of this array.\n */\n @Override\n public int getDim1() {\n return dim;\n }\n\n /**\n * This will throw an exception for one-dimensional arrays.\n */\n @Override\n public int getDim2() {\n throw new IllegalStateException(\"1D array has no second dimension\");\n }\n\n /**\n * @return {@code true}.\n */\n @Override\n public boolean is1D() {\n return true;\n }\n\n /**\n * Retrieve an element from this array.\n *\n * @param a the index of the element to retrieve.\n * @param b this will be ignored.\n * @return the element at the position indicated by {@code a} in this array.\n */\n @Override\n public Object at(int a, int b) {\n // ignore b\n checkBoundary(a);\n return data[a];\n }\n\n /**\n * Store a value in this array.\n *\n * @param a the index at which to store the element.\n * @param b this will be ignored.\n * @param v the value to store.\n */\n @Override\n public void setAt(int a, int b, Object v) {\n // ignore b\n checkBoundary(a);\n data[a] = v;\n }\n\n /**\n * Helper: check if the passed index is within the acceptable boundaries of this array, and throw an exception if\n * that is not the case.\n *\n * @param a the index to check.\n */\n private void checkBoundary(int a) {\n if (a >= dim) {\n throw new IllegalStateException(String.format(\"out of bounds access (%d) in 1D array [%d]\", a, dim));\n }\n }\n\n}" }, { "identifier": "BasicArray2D", "path": "src/main/java/de/haupz/basicode/array/BasicArray2D.java", "snippet": "public class BasicArray2D extends BasicArray {\n\n /**\n * The amount of elements on the first dimension of this array. Note that it will be one greater than the value\n * given for initialisation, as a BASIC array with a size of {@code N} can have indices in the range 0 <= {@code i}\n * <= {@code N}.\n */\n private final int dim1;\n\n /**\n * The amount of elements on the second dimension of this array. Note that it will be one greater than the value\n * given for initialisation, as a BASIC array with a size of {@code N} can have indices in the range 0 <= {@code i}\n * <= {@code N}.\n */\n private final int dim2;\n\n /**\n * Construct a two-dimensional BASIC array.\n *\n * @param type the array's type.\n * @param d1 the {@linkplain BasicArray2D#dim1 first dimension} of the array.\n * @param d2 the {@linkplain BasicArray2D#dim2 second dimension} of the array.\n */\n public BasicArray2D(ArrayType type, int d1, int d2) {\n super(type, (d1 + 1) * (d2 + 1));\n dim1 = d1 + 1;\n dim2 = d2 + 1;\n }\n\n /**\n * @return the {@linkplain BasicArray2D#dim1 first dimension} of the array.\n */\n @Override\n public int getDim1() {\n return dim1;\n }\n\n /**\n * @return the {@linkplain BasicArray2D#dim2 second dimension} of the array.\n */\n @Override\n public int getDim2() {\n return dim2;\n }\n\n /**\n * @return {@code true}.\n */\n @Override\n public boolean is2D() {\n return true;\n }\n\n /**\n * Retrieve an element from this array.\n *\n * @param a the index into the first dimension of this array.\n * @param b the index into the second dimension of this array.\n * @return the element at the position indicated by {@code a} and {@code b} in this array.\n */\n @Override\n public Object at(int a, int b) {\n checkBoundaries(a, b);\n return data[a * dim2 + b];\n }\n\n /**\n * Store a value in this array.\n *\n * @param a the index into the first dimension of this array.\n * @param b the index into the second dimension of this array.\n * @param v the value to store.\n */\n @Override\n public void setAt(int a, int b, Object v) {\n checkBoundaries(a, b);\n data[a * dim2 + b] = v;\n }\n\n /**\n * Helper: check if the passed indices are within the acceptable boundaries of this array, and throw an exception if\n * that is not the case.\n *\n * @param a the index into the first dimension of this array.\n * @param b the index into the second dimension of this array.\n */\n private void checkBoundaries(int a, int b) {\n if (a >= dim1 || b >= dim2) {\n throw new IllegalStateException(\n String.format(\"out of bounds access (%d,%d) in 1D array [%d,%d]\", a, b, dim1, dim2));\n }\n }\n\n}" } ]
import de.haupz.basicode.array.ArrayType; import de.haupz.basicode.array.BasicArray; import de.haupz.basicode.array.BasicArray1D; import de.haupz.basicode.array.BasicArray2D; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*;
2,311
package de.haupz.basicode; public class DimTest extends StatementTest { @Test public void test1DNonString() { run("DIM A(7)"); Optional<BasicArray> v = state.getArray("A"); assertTrue(v.isPresent());
package de.haupz.basicode; public class DimTest extends StatementTest { @Test public void test1DNonString() { run("DIM A(7)"); Optional<BasicArray> v = state.getArray("A"); assertTrue(v.isPresent());
assertEquals(BasicArray1D.class, v.get().getClass());
2
2023-10-14 12:20:59+00:00
4k
Thenuka22/BakerySalesnOrdering_System
BakeryPosSystem/src/bakerypossystem/View/PanelLoginAndRegister.java
[ { "identifier": "Button", "path": "BakeryPosSystem/src/CustomComponents/Button.java", "snippet": "public class Button extends JButton {\n\n public Color getEffectColor() {\n return effectColor;\n }\n\n public void setEffectColor(Color effectColor) {\n this.effectColor = effectColor;\n }\n\n private Animator animator;\n private int targetSize;\n private float animatSize;\n private Point pressedPoint;\n private float alpha;\n private Color effectColor = new Color(255, 255, 255);\n\n public Button() {\n setContentAreaFilled(false);\n setBorder(new EmptyBorder(5, 0, 5, 0));\n setBackground(Color.WHITE);\n setCursor(new Cursor(Cursor.HAND_CURSOR));\n addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent me) {\n targetSize = Math.max(getWidth(), getHeight()) * 2;\n animatSize = 0;\n pressedPoint = me.getPoint();\n alpha = 0.5f;\n if (animator.isRunning()) {\n animator.stop();\n }\n animator.start();\n }\n });\n TimingTarget target = new TimingTargetAdapter() {\n @Override\n public void timingEvent(float fraction) {\n if (fraction > 0.5f) {\n alpha = 1 - fraction;\n }\n animatSize = fraction * targetSize;\n repaint();\n }\n };\n animator = new Animator(700, target);\n animator.setAcceleration(0.5f);\n animator.setDeceleration(0.5f);\n animator.setResolution(0);\n }\n\n @Override\n protected void paintComponent(Graphics grphcs) {\n int width = getWidth();\n int height = getHeight();\n BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = img.createGraphics();\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(getBackground());\n g2.fillRoundRect(0, 0, width, height, height, height);\n if (pressedPoint != null) {\n g2.setColor(effectColor);\n g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));\n g2.fillOval((int) (pressedPoint.x - animatSize / 2), (int) (pressedPoint.y - animatSize / 2), (int) animatSize, (int) animatSize);\n }\n g2.dispose();\n grphcs.drawImage(img, 0, 0, null);\n super.paintComponent(grphcs);\n }\n}" }, { "identifier": "MyPasswordField", "path": "BakeryPosSystem/src/CustomComponents/MyPasswordField.java", "snippet": "public class MyPasswordField extends JPasswordField {\n\n public String getHint() {\n return hint;\n }\n\n public void setHint(String hint) {\n this.hint = hint;\n }\n\n public Icon getPrefixIcon() {\n return prefixIcon;\n }\n\n public void setPrefixIcon(Icon prefixIcon) {\n this.prefixIcon = prefixIcon;\n initBorder();\n }\n\n public Icon getSuffixIcon() {\n return suffixIcon;\n }\n\n public void setSuffixIcon(Icon suffixIcon) {\n this.suffixIcon = suffixIcon;\n initBorder();\n }\n\n private Icon prefixIcon;\n private Icon suffixIcon;\n private String hint = \"\";\n\n public MyPasswordField() {\n setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));\n setBackground(new Color(0, 0, 0, 0));\n setForeground(Color.decode(\"#7A8C8D\"));\n setFont(new java.awt.Font(\"sansserif\", 0, 13));\n setSelectionColor(new Color(75, 175, 152));\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(new Color(230, 245, 241));\n g2.fillRoundRect(0, 0, getWidth(), getHeight(), 5, 5);\n paintIcon(g);\n super.paintComponent(g);\n }\n\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n if (getPassword().length == 0) {\n int h = getHeight();\n ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n Insets ins = getInsets();\n FontMetrics fm = g.getFontMetrics();\n g.setColor(new Color(200, 200, 200));\n g.drawString(hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);\n }\n }\n\n private void paintIcon(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n if (prefixIcon != null) {\n Image prefix = ((ImageIcon) prefixIcon).getImage();\n int y = (getHeight() - prefixIcon.getIconHeight()) / 2;\n g2.drawImage(prefix, 10, y, this);\n }\n if (suffixIcon != null) {\n Image suffix = ((ImageIcon) suffixIcon).getImage();\n int y = (getHeight() - suffixIcon.getIconHeight()) / 2;\n g2.drawImage(suffix, getWidth() - suffixIcon.getIconWidth() - 10, y, this);\n }\n }\n\n private void initBorder() {\n int left = 15;\n int right = 15;\n // 5 is default\n if (prefixIcon != null) {\n // prefix is left\n left = prefixIcon.getIconWidth() + 15;\n }\n if (suffixIcon != null) {\n // suffix is right\n right = suffixIcon.getIconWidth() + 15;\n }\n setBorder(javax.swing.BorderFactory.createEmptyBorder(10, left, 10, right));\n }\n}" }, { "identifier": "MyTextField", "path": "BakeryPosSystem/src/CustomComponents/MyTextField.java", "snippet": "public class MyTextField extends JTextField {\n\n public String getHint() {\n return hint;\n }\n\n public void setHint(String hint) {\n this.hint = hint;\n }\n\n public Icon getPrefixIcon() {\n return prefixIcon;\n }\n\n public void setPrefixIcon(Icon prefixIcon) {\n this.prefixIcon = prefixIcon;\n initBorder();\n }\n\n public Icon getSuffixIcon() {\n return suffixIcon;\n }\n\n public void setSuffixIcon(Icon suffixIcon) {\n this.suffixIcon = suffixIcon;\n initBorder();\n }\n\n private Icon prefixIcon;\n private Icon suffixIcon;\n private String hint = \"\";\n\n public MyTextField() {\n setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));\n setBackground(new Color(0, 0, 0, 0));\n setForeground(Color.decode(\"#7A8C8D\"));\n setFont(new java.awt.Font(\"sansserif\", 0, 13));\n setSelectionColor(new Color(75, 175, 152));\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n g2.setColor(new Color(230, 245, 241));\n g2.fillRoundRect(0, 0, getWidth(), getHeight(), 5, 5);\n paintIcon(g);\n super.paintComponent(g);\n }\n\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n if (getText().length() == 0) {\n int h = getHeight();\n ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n Insets ins = getInsets();\n FontMetrics fm = g.getFontMetrics();\n g.setColor(new Color(200, 200, 200));\n g.drawString(hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);\n }\n }\n\n private void paintIcon(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n if (prefixIcon != null) {\n Image prefix = ((ImageIcon) prefixIcon).getImage();\n int y = (getHeight() - prefixIcon.getIconHeight()) / 2;\n g2.drawImage(prefix, 10, y, this);\n }\n if (suffixIcon != null) {\n Image suffix = ((ImageIcon) suffixIcon).getImage();\n int y = (getHeight() - suffixIcon.getIconHeight()) / 2;\n g2.drawImage(suffix, getWidth() - suffixIcon.getIconWidth() - 10, y, this);\n }\n }\n\n private void initBorder() {\n int left = 15;\n int right = 15;\n // 5 is default\n if (prefixIcon != null) {\n // prefix is left\n left = prefixIcon.getIconWidth() + 15;\n }\n if (suffixIcon != null) {\n // suffix is right\n right = suffixIcon.getIconWidth() + 15;\n }\n setBorder(javax.swing.BorderFactory.createEmptyBorder(10, left, 10, right));\n }\n}" }, { "identifier": "CUserSignIn", "path": "BakeryPosSystem/src/bakerypossystem/Controller/CUserSignIn.java", "snippet": "public class CUserSignIn {\n LoginValidation mSignIn;\n public int signIn(String username, String password) {\n mSignIn = new LoginValidation();\n if(mSignIn.signIn(username, password)==true) {\n return 1;\n }\n else\n return 0;\n }\n}" } ]
import CustomComponents.Button; import CustomComponents.MyPasswordField; import CustomComponents.MyTextField; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import bakerypossystem.Controller.CUserSignIn; import net.miginfocom.swing.MigLayout;
3,459
package bakerypossystem.View; public class PanelLoginAndRegister extends javax.swing.JLayeredPane { public PanelLoginAndRegister() { initComponents(); initRegister(); initLogin(); login.setVisible(false); register.setVisible(true); } private void initRegister() { register.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Customer Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); register.add(label); MyTextField txtUser = new MyTextField(); txtUser.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/user_1.png"))); txtUser.setHint("Username"); register.add(txtUser, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); register.add(txtPass, "w 60%"); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Log in"); register.add(cmd, "w 40%, h 40"); JLabel label1 = new JLabel("Use Guest Account Instead"); label1.setFont(new Font("sansserif", 1, 20)); label1.setForeground(new Color(7, 164, 121)); register.add(label1); // Add an ActionListener to cmd1 button label1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { openAnotherFrame(); JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(PanelLoginAndRegister.this); frame.dispose(); } @Override public void mouseEntered(MouseEvent e){ label1.setCursor(new Cursor(Cursor.HAND_CURSOR)); } }); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtUser.getText(); String password = txtPass.getText(); CustomerView DashBoardCustomize = new CustomerView(); //CUserSignIn nn = new CUserSignIn(); if(username.equals("Thenuka" )&& password.equals("1234")) { DashBoardCustomize.show(); } else JOptionPane.showMessageDialog(null, "Sign In Unsuccessful.", "ERROR", JOptionPane.ERROR_MESSAGE); } }); } private void openAnotherFrame() { // Create and open another frame here CustomerView anotherFrame = new CustomerView(); // Add components, set properties, and customize the new frame as needed anotherFrame.setVisible(true); } private void initLogin() { login.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Bakery Staff Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); login.add(label); MyTextField txtEmail = new MyTextField(); txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/mail.png"))); txtEmail.setHint("Email"); login.add(txtEmail, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); login.add(txtPass, "w 60%"); JButton cmdForget = new JButton("Forgot your password ?"); cmdForget.setForeground(new Color(100, 100, 100)); cmdForget.setFont(new Font("sansserif", 1, 12)); cmdForget.setContentAreaFilled(false); cmdForget.setCursor(new Cursor(Cursor.HAND_CURSOR)); login.add(cmdForget); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Login"); login.add(cmd, "w 40%, h 40"); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtEmail.getText(); String password = txtPass.getText(); DashBoardCustomize DashBoardCustomize = new DashBoardCustomize();
package bakerypossystem.View; public class PanelLoginAndRegister extends javax.swing.JLayeredPane { public PanelLoginAndRegister() { initComponents(); initRegister(); initLogin(); login.setVisible(false); register.setVisible(true); } private void initRegister() { register.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Customer Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); register.add(label); MyTextField txtUser = new MyTextField(); txtUser.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/user_1.png"))); txtUser.setHint("Username"); register.add(txtUser, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); register.add(txtPass, "w 60%"); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Log in"); register.add(cmd, "w 40%, h 40"); JLabel label1 = new JLabel("Use Guest Account Instead"); label1.setFont(new Font("sansserif", 1, 20)); label1.setForeground(new Color(7, 164, 121)); register.add(label1); // Add an ActionListener to cmd1 button label1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { openAnotherFrame(); JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(PanelLoginAndRegister.this); frame.dispose(); } @Override public void mouseEntered(MouseEvent e){ label1.setCursor(new Cursor(Cursor.HAND_CURSOR)); } }); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtUser.getText(); String password = txtPass.getText(); CustomerView DashBoardCustomize = new CustomerView(); //CUserSignIn nn = new CUserSignIn(); if(username.equals("Thenuka" )&& password.equals("1234")) { DashBoardCustomize.show(); } else JOptionPane.showMessageDialog(null, "Sign In Unsuccessful.", "ERROR", JOptionPane.ERROR_MESSAGE); } }); } private void openAnotherFrame() { // Create and open another frame here CustomerView anotherFrame = new CustomerView(); // Add components, set properties, and customize the new frame as needed anotherFrame.setVisible(true); } private void initLogin() { login.setLayout(new MigLayout("wrap", "push[center]push", "push[]25[]10[]10[]25[]push")); JLabel label = new JLabel("Bakery Staff Login"); label.setFont(new Font("sansserif", 1, 30)); label.setForeground(new Color(7, 164, 121)); login.add(label); MyTextField txtEmail = new MyTextField(); txtEmail.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/mail.png"))); txtEmail.setHint("Email"); login.add(txtEmail, "w 60%"); MyPasswordField txtPass = new MyPasswordField(); txtPass.setPrefixIcon(new ImageIcon(getClass().getResource("/icon/pass.png"))); txtPass.setHint("Password"); login.add(txtPass, "w 60%"); JButton cmdForget = new JButton("Forgot your password ?"); cmdForget.setForeground(new Color(100, 100, 100)); cmdForget.setFont(new Font("sansserif", 1, 12)); cmdForget.setContentAreaFilled(false); cmdForget.setCursor(new Cursor(Cursor.HAND_CURSOR)); login.add(cmdForget); Button cmd = new Button(); cmd.setBackground(new Color(7, 164, 121)); cmd.setForeground(new Color(250, 250, 250)); cmd.setText("Login"); login.add(cmd, "w 40%, h 40"); cmd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = txtEmail.getText(); String password = txtPass.getText(); DashBoardCustomize DashBoardCustomize = new DashBoardCustomize();
CUserSignIn nn = new CUserSignIn();
3
2023-10-11 16:55:32+00:00
4k
giteecode/bookmanage2-public
nhXJH-system/src/main/java/com/nhXJH/system/service/ISysRoleService.java
[ { "identifier": "SysRole", "path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysRole.java", "snippet": "public class SysRole extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 角色ID */\n @Excel(name = \"角色序号\", cellType = ColumnType.NUMERIC)\n private Long roleId;\n\n /** 角色名称 */\n @Excel(name = \"角色名称\")\n private String roleName;\n\n /** 角色权限 */\n @Excel(name = \"角色权限\")\n private String roleKey;\n\n /** 角色排序 */\n @Excel(name = \"角色排序\")\n private String roleSort;\n\n /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限) */\n @Excel(name = \"数据范围\", readConverterExp = \"1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限\")\n private String dataScope;\n\n /** 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示) */\n private boolean menuCheckStrictly;\n\n /** 部门树选择项是否关联显示(0:父子不互相关联显示 1:父子互相关联显示 ) */\n private boolean deptCheckStrictly;\n\n /** 角色状态(0正常 1停用) */\n @Excel(name = \"角色状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 用户是否存在此角色标识 默认不存在 */\n private boolean flag = false;\n\n /** 菜单组 */\n private Long[] menuIds;\n\n /** 部门组(数据权限) */\n private Long[] deptIds;\n\n public SysRole() {\n\n }\n\n public SysRole(Long roleId) {\n this.roleId = roleId;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n public boolean isAdmin() {\n return isAdmin(this.roleId);\n }\n\n public static boolean isAdmin(Long roleId) {\n return roleId != null && 1L == roleId;\n }\n\n @NotBlank(message = \"角色名称不能为空\")\n @Size(min = 0, max = 30, message = \"角色名称长度不能超过30个字符\")\n public String getRoleName() {\n return roleName;\n }\n\n public void setRoleName(String roleName) {\n this.roleName = roleName;\n }\n\n @NotBlank(message = \"权限字符不能为空\")\n @Size(min = 0, max = 100, message = \"权限字符长度不能超过100个字符\")\n public String getRoleKey() {\n return roleKey;\n }\n\n public void setRoleKey(String roleKey) {\n this.roleKey = roleKey;\n }\n\n @NotBlank(message = \"显示顺序不能为空\")\n public String getRoleSort() {\n return roleSort;\n }\n\n public void setRoleSort(String roleSort) {\n this.roleSort = roleSort;\n }\n\n public String getDataScope() {\n return dataScope;\n }\n\n public void setDataScope(String dataScope) {\n this.dataScope = dataScope;\n }\n\n public boolean isMenuCheckStrictly() {\n return menuCheckStrictly;\n }\n\n public void setMenuCheckStrictly(boolean menuCheckStrictly) {\n this.menuCheckStrictly = menuCheckStrictly;\n }\n\n public boolean isDeptCheckStrictly() {\n return deptCheckStrictly;\n }\n\n public void setDeptCheckStrictly(boolean deptCheckStrictly) {\n this.deptCheckStrictly = deptCheckStrictly;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getDelFlag() {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag) {\n this.delFlag = delFlag;\n }\n\n public boolean isFlag() {\n return flag;\n }\n\n public void setFlag(boolean flag) {\n this.flag = flag;\n }\n\n public Long[] getMenuIds() {\n return menuIds;\n }\n\n public void setMenuIds(Long[] menuIds) {\n this.menuIds = menuIds;\n }\n\n public Long[] getDeptIds() {\n return deptIds;\n }\n\n public void setDeptIds(Long[] deptIds) {\n this.deptIds = deptIds;\n }\n \n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"roleId\", getRoleId())\n .append(\"roleName\", getRoleName())\n .append(\"roleKey\", getRoleKey())\n .append(\"roleSort\", getRoleSort())\n .append(\"dataScope\", getDataScope())\n .append(\"menuCheckStrictly\", isMenuCheckStrictly())\n .append(\"deptCheckStrictly\", isDeptCheckStrictly())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}" }, { "identifier": "SysUserRole", "path": "nhXJH-system/src/main/java/com/nhXJH/system/domain/SysUserRole.java", "snippet": "public class SysUserRole {\n /** 用户ID */\n private Long userId;\n \n /** 角色ID */\n private Long roleId;\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public Long getRoleId() {\n return roleId;\n }\n\n public void setRoleId(Long roleId) {\n this.roleId = roleId;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"roleId\", getRoleId())\n .toString();\n }\n}" } ]
import java.util.List; import java.util.Set; import com.nhXJH.common.core.domain.entity.SysRole; import com.nhXJH.system.domain.SysUserRole;
2,586
package com.nhXJH.system.service; /** * 角色业务层 * * @author nhXJH */ public interface ISysRoleService { /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ public List<SysRole> selectRoleList(SysRole role); /** * 根据用户ID查询角色列表 * * @param userId 用户ID * @return 角色列表 */ public List<SysRole> selectRolesByUserId(Long userId); /** * 根据用户ID查询角色权限 * * @param userId 用户ID * @return 权限列表 */ public Set<String> selectRolePermissionByUserId(Long userId); /** * 查询所有角色 * * @return 角色列表 */ public List<SysRole> selectRoleAll(); /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ public List<Long> selectRoleListByUserId(Long userId); /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ public SysRole selectRoleById(Long roleId); /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleNameUnique(SysRole role); /** * 校验角色权限是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleKeyUnique(SysRole role); /** * 校验角色是否允许操作 * * @param role 角色信息 */ public void checkRoleAllowed(SysRole role); /** * 校验角色是否有数据权限 * * @param roleId 角色id */ public void checkRoleDataScope(Long roleId); /** * 通过角色ID查询角色使用数量 * * @param roleId 角色ID * @return 结果 */ public int countUserRoleByRoleId(Long roleId); /** * 新增保存角色信息 * * @param role 角色信息 * @return 结果 */ public int insertRole(SysRole role); /** * 修改保存角色信息 * * @param role 角色信息 * @return 结果 */ public int updateRole(SysRole role); /** * 修改角色状态 * * @param role 角色信息 * @return 结果 */ public int updateRoleStatus(SysRole role); /** * 修改数据权限信息 * * @param role 角色信息 * @return 结果 */ public int authDataScope(SysRole role); /** * 通过角色ID删除角色 * * @param roleId 角色ID * @return 结果 */ public int deleteRoleById(Long roleId); /** * 批量删除角色信息 * * @param roleIds 需要删除的角色ID * @return 结果 */ public int deleteRoleByIds(Long[] roleIds); /** * 取消授权用户角色 * * @param userRole 用户和角色关联信息 * @return 结果 */
package com.nhXJH.system.service; /** * 角色业务层 * * @author nhXJH */ public interface ISysRoleService { /** * 根据条件分页查询角色数据 * * @param role 角色信息 * @return 角色数据集合信息 */ public List<SysRole> selectRoleList(SysRole role); /** * 根据用户ID查询角色列表 * * @param userId 用户ID * @return 角色列表 */ public List<SysRole> selectRolesByUserId(Long userId); /** * 根据用户ID查询角色权限 * * @param userId 用户ID * @return 权限列表 */ public Set<String> selectRolePermissionByUserId(Long userId); /** * 查询所有角色 * * @return 角色列表 */ public List<SysRole> selectRoleAll(); /** * 根据用户ID获取角色选择框列表 * * @param userId 用户ID * @return 选中角色ID列表 */ public List<Long> selectRoleListByUserId(Long userId); /** * 通过角色ID查询角色 * * @param roleId 角色ID * @return 角色对象信息 */ public SysRole selectRoleById(Long roleId); /** * 校验角色名称是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleNameUnique(SysRole role); /** * 校验角色权限是否唯一 * * @param role 角色信息 * @return 结果 */ public String checkRoleKeyUnique(SysRole role); /** * 校验角色是否允许操作 * * @param role 角色信息 */ public void checkRoleAllowed(SysRole role); /** * 校验角色是否有数据权限 * * @param roleId 角色id */ public void checkRoleDataScope(Long roleId); /** * 通过角色ID查询角色使用数量 * * @param roleId 角色ID * @return 结果 */ public int countUserRoleByRoleId(Long roleId); /** * 新增保存角色信息 * * @param role 角色信息 * @return 结果 */ public int insertRole(SysRole role); /** * 修改保存角色信息 * * @param role 角色信息 * @return 结果 */ public int updateRole(SysRole role); /** * 修改角色状态 * * @param role 角色信息 * @return 结果 */ public int updateRoleStatus(SysRole role); /** * 修改数据权限信息 * * @param role 角色信息 * @return 结果 */ public int authDataScope(SysRole role); /** * 通过角色ID删除角色 * * @param roleId 角色ID * @return 结果 */ public int deleteRoleById(Long roleId); /** * 批量删除角色信息 * * @param roleIds 需要删除的角色ID * @return 结果 */ public int deleteRoleByIds(Long[] roleIds); /** * 取消授权用户角色 * * @param userRole 用户和角色关联信息 * @return 结果 */
public int deleteAuthUser(SysUserRole userRole);
1
2023-10-13 07:19:20+00:00
4k
M-D-Team/ait-fabric-1.20.1
src/main/java/mdteam/ait/tardis/console/BorealisConsole.java
[ { "identifier": "AITMod", "path": "src/main/java/mdteam/ait/AITMod.java", "snippet": "public class AITMod implements ModInitializer {\n public static final String MOD_ID = \"ait\";\n public static final Logger LOGGER = LoggerFactory.getLogger(\"ait\");\n public static final Boolean DEBUG = true;\n\n public static final AITConfig AIT_CONFIG = AITConfig.createAndLoad(); // if this doesnt exist for you run data gen\n public static final NeptuneItemGroup AIT_ITEM_GROUP = new NeptuneItemGroup(new Identifier(AITMod.MOD_ID, \"item_group\"), AITItems.TARDIS_ITEM.getDefaultStack());\n public static final ComponentKey<RadioNBTComponent> RADIONBT =\n ComponentRegistry.getOrCreate(new Identifier(AITMod.MOD_ID, \"radionbt\"), RadioNBTComponent.class);\n\n @Override\n public void onInitialize() {\n ServerAITNetworkManager.init();\n ConsoleRegistry.init();\n DesktopRegistry.init();\n ExteriorRegistry.init();\n HumsRegistry.init();\n CreakRegistry.init();\n SequenceRegistry.init();\n\n // These 3 have client registries which also need registering to.\n ConsoleVariantRegistry.init();\n ExteriorVariantRegistry.init();\n DoorRegistry.init();\n\n NeptuneInitHandler.register(AITItems.class, MOD_ID);\n NeptuneInitHandler.register(AITBlocks.class, MOD_ID);\n NeptuneInitHandler.register(AITSounds.class, MOD_ID);\n NeptuneInitHandler.register(AITBlockEntityTypes.class, MOD_ID);\n NeptuneInitHandler.register(AITEntityTypes.class, MOD_ID);\n\n\n TardisUtil.init();\n TardisManager.getInstance();\n TardisManager.init();\n RiftChunkManager.init();\n TardisCriterions.init();\n\n entityAttributeRegister();\n\n // ip support\n if (DependencyChecker.hasPortals())\n PortalsHandler.init();\n\n if (DependencyChecker.hasRegeneration())\n RegenHandler.init();\n\n CommandRegistrationCallback.EVENT.register(((dispatcher, registryAccess, environment) -> {\n TeleportInteriorCommand.register(dispatcher);\n UnlockInteriorsCommand.register(dispatcher);\n SummonTardisCommand.register(dispatcher);\n SetLockedCommand.register(dispatcher);\n // SetHumCommand.register(dispatcher);\n SetFuelCommand.register(dispatcher);\n AddFuelCommand.register(dispatcher);\n RemoveFuelCommand.register(dispatcher);\n ToggleHumCommand.register(dispatcher);\n ToggleAlarmCommand.register(dispatcher);\n ToggleSiegeModeCommand.register(dispatcher);\n RiftChunkCommand.register(dispatcher);\n RealWorldCommand.register(dispatcher);\n }));\n\n ServerBlockEntityEvents.BLOCK_ENTITY_LOAD.register(((blockEntity, world) -> {\n // fixme this doesnt seem to run??\n if (blockEntity instanceof ConsoleBlockEntity console) {\n console.markNeedsSyncing();\n }\n }));\n\n TardisEvents.LANDED.register((tardis -> {\n // stuff for resetting the ExteriorAnimation\n if (tardis.getTravel().getPosition().getWorld().getBlockEntity(tardis.getTravel().getExteriorPos()) instanceof ExteriorBlockEntity entity) {\n entity.getAnimation().setupAnimation(tardis.getTravel().getState());\n }\n }));\n\n TardisEvents.DEMAT.register((tardis -> {\n if (tardis.isGrowth() || tardis.getHandlers().getInteriorChanger().isGenerating() || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.HANDBRAKE) || PropertiesHandler.getBool(tardis.getHandlers().getProperties(), PropertiesHandler.IS_FALLING) || tardis.isRefueling())\n return true; // cancelled\n\n if (tardis.getDoor().isOpen() /*|| !tardis.getDoor().locked()*/)\n return true;\n\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.TAKEOFF.trigger((ServerPlayerEntity) player);\n }\n return false;\n }));\n\n TardisEvents.MAT.register((tardis -> {\n // Check that the tardis has finished flight\n boolean flightDone = tardis.getHandlers().getFlight().hasFinishedFlight();\n\n // Check if the Tardis is on cooldown\n boolean isCooldown = FlightUtil.isMaterialiseOnCooldown(tardis);\n\n // Check if the destination is already occupied\n boolean isDestinationOccupied = !tardis.getTravel().getPosition().equals(tardis.getTravel().getDestination()) && !tardis.getTravel().checkDestination();\n\n return /*!flightDone ||*/ isCooldown || isDestinationOccupied;\n }));\n\n TardisEvents.CRASH.register((tardis -> {\n for (PlayerEntity player : TardisUtil.getPlayersInInterior(tardis)) {\n TardisCriterions.CRASH.trigger((ServerPlayerEntity) player);\n }\n }));\n\n TardisEvents.OUT_OF_FUEL.register(Tardis::disablePower);\n TardisEvents.LOSE_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.SHUTDOWN, SoundCategory.AMBIENT, 10f, 1f);\n }\n\n // disabling protocols\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.AUTO_LAND, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.ANTIGRAVS_ENABLED, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HAIL_MARY, false);\n PropertiesHandler.setBool(tardis.getHandlers().getProperties(), PropertiesHandler.HADS_ENABLED, false);\n }));\n TardisEvents.REGAIN_POWER.register((tardis -> {\n if (tardis.getDesktop().getConsolePos() != null) {\n TardisUtil.getTardisDimension().playSound(null, tardis.getDesktop().getConsolePos(), AITSounds.POWERUP, SoundCategory.AMBIENT, 10f, 1f);\n }\n }));\n\n ServerPlayNetworking.registerGlobalReceiver(ConsoleBlockEntity.ASK, ((server, player, handler, buf, responseSender) -> {\n if (player.getServerWorld().getRegistryKey() != AITDimensions.TARDIS_DIM_WORLD) return;\n\n BlockPos consolePos = buf.readBlockPos();\n // fixme the gotten block entity is always null, shit.\n if (player.getServerWorld().getBlockEntity(consolePos) instanceof ConsoleBlockEntity console)\n console.markNeedsSyncing();\n }));\n\n\n ServerPlayNetworking.registerGlobalReceiver(ServerHumHandler.RECEIVE, ((server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n HumSound hum = HumSound.fromName(buf.readString(), buf.readString());\n\n if (tardis == null || hum == null) return;\n\n tardis.getHandlers().getHum().setHum(hum);\n }));\n\n ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {\n DesktopRegistry.syncToClient(handler.getPlayer());\n });\n\n\n ServerPlayNetworking.registerGlobalReceiver(TardisDesktop.CACHE_CONSOLE, (server, player, handler, buf, responseSender) -> {\n Tardis tardis = ServerTardisManager.getInstance().getTardis(buf.readUuid());\n TardisUtil.getServer().execute(() -> {\n if (tardis == null) return;\n tardis.getDesktop().cacheConsole();\n });\n });\n\n AIT_ITEM_GROUP.initialize();\n }\n\n public void entityAttributeRegister() {\n FabricDefaultAttributeRegistry.register(AITEntityTypes.CONTROL_ENTITY_TYPE, ConsoleControlEntity.createControlAttributes());\n }\n\n public static final Identifier OPEN_SCREEN_TARDIS = new Identifier(AITMod.MOD_ID, \"open_screen_tardis\"); // fixes \"AITModClient in env type SERVER\"\n\n public static void openScreen(ServerPlayerEntity player, int id, UUID tardis) {\n PacketByteBuf buf = PacketByteBufs.create();\n buf.writeInt(id);\n buf.writeUuid(tardis);\n ServerPlayNetworking.send(player, OPEN_SCREEN_TARDIS, buf);\n }\n}" }, { "identifier": "ControlTypes", "path": "src/main/java/mdteam/ait/tardis/control/ControlTypes.java", "snippet": "public class ControlTypes {\n private Control control;\n private EntityDimensions scale;\n private Vector3f offset;\n\n public ControlTypes(Control control, EntityDimensions scaling, Vector3f offset) {\n this.control = control;\n this.scale = scaling;\n this.offset = offset;\n }\n\n @Override\n public String toString() {\n return \"ControlTypes{\" +\n \"control=\" + control +\n \", scale=\" + scale +\n \", offset=\" + offset +\n '}';\n }\n\n public Control getControl() {\n return this.control;\n }\n\n public void setControl(String id) {\n this.control = new Control(id) {\n @Override\n public boolean runServer(Tardis tardis, ServerPlayerEntity player, ServerWorld world) {\n return true;\n }\n };\n }\n\n public EntityDimensions getScale() {\n return this.scale;\n }\n\n public void setScale(EntityDimensions scale) {\n this.scale = scale;\n }\n\n public Vector3f getOffset() {\n return this.offset;\n }\n\n public void setOffset(Vector3f offset) {\n this.offset = offset;\n }\n\n}" }, { "identifier": "IncrementControl", "path": "src/main/java/mdteam/ait/tardis/control/impl/pos/IncrementControl.java", "snippet": "public class IncrementControl extends Control {\n public IncrementControl() {\n super(\"increment\");\n }\n\n @Override\n public boolean runServer(Tardis tardis, ServerPlayerEntity player, ServerWorld world) {\n TardisTravel travel = tardis.getTravel();\n\n tardis.markDirty();\n\n PosManager postmanPat = travel.getPosManager(); // lol posmanager shortens to posman and postman pat sounds similar fixme if ur boring\n\n if (!player.isSneaking()) {\n postmanPat.nextIncrement();\n } else {\n postmanPat.prevIncrement();\n }\n\n messagePlayerIncrement(player, postmanPat);\n\n return true;\n }\n\n @Override\n public SoundEvent getSound() {\n return AITSounds.CRANK;\n }\n\n private void messagePlayerIncrement(ServerPlayerEntity player, PosManager manager) {\n Text text = Text.translatable(\"tardis.message.control.increment.info\").append(Text.literal(\"\" + manager.increment));\n player.sendMessage(text, true);\n }\n @Override\n public boolean shouldHaveDelay() {\n return false;\n }\n}" }, { "identifier": "XControl", "path": "src/main/java/mdteam/ait/tardis/control/impl/pos/XControl.java", "snippet": "public class XControl extends PosControl {\n public XControl() {\n super(PosType.X);\n }\n}" }, { "identifier": "YControl", "path": "src/main/java/mdteam/ait/tardis/control/impl/pos/YControl.java", "snippet": "public class YControl extends PosControl {\n public YControl() {\n super(PosType.Y);\n }\n}" }, { "identifier": "ZControl", "path": "src/main/java/mdteam/ait/tardis/control/impl/pos/ZControl.java", "snippet": "public class ZControl extends PosControl {\n public ZControl() {\n super(PosType.Z);\n }\n}" } ]
import mdteam.ait.AITMod; import mdteam.ait.tardis.control.ControlTypes; import mdteam.ait.tardis.control.impl.*; import mdteam.ait.tardis.control.impl.pos.IncrementControl; import mdteam.ait.tardis.control.impl.pos.XControl; import mdteam.ait.tardis.control.impl.pos.YControl; import mdteam.ait.tardis.control.impl.pos.ZControl; import net.minecraft.entity.EntityDimensions; import net.minecraft.util.Identifier; import org.joml.Vector3f;
2,881
package mdteam.ait.tardis.console; public class BorealisConsole extends ConsoleSchema { public static final Identifier REFERENCE = new Identifier(AITMod.MOD_ID, "console/borealis");
package mdteam.ait.tardis.console; public class BorealisConsole extends ConsoleSchema { public static final Identifier REFERENCE = new Identifier(AITMod.MOD_ID, "console/borealis");
private static final ControlTypes[] TYPES = new ControlTypes[] {
1
2023-10-08 00:38:53+00:00
4k
jianjian3219/044_bookmanage2-public
nhXJH-framework/src/main/java/com/nhXJH/framework/config/DruidConfig.java
[ { "identifier": "DataSourceType", "path": "nhXJH-common/src/main/java/com/nhXJH/common/enums/DataSourceType.java", "snippet": "public enum DataSourceType {\n /**\n * 主库\n */\n MASTER,\n\n /**\n * 从库\n */\n SLAVE\n}" }, { "identifier": "SpringUtils", "path": "nhXJH-common/src/main/java/com/nhXJH/common/utils/spring/SpringUtils.java", "snippet": "@Component\npublic final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {\n /** Spring应用上下文环境 */\n private static ConfigurableListableBeanFactory beanFactory;\n\n private static ApplicationContext applicationContext;\n\n @Override\n public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {\n SpringUtils.beanFactory = beanFactory;\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n SpringUtils.applicationContext = applicationContext;\n }\n\n /**\n * 获取对象\n *\n * @param name\n * @return Object 一个以所给名字注册的bean的实例\n * @throws org.springframework.beans.BeansException\n *\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getBean(String name) throws BeansException {\n return (T) beanFactory.getBean(name);\n }\n\n /**\n * 获取类型为requiredType的对象\n *\n * @param clz\n * @return\n * @throws org.springframework.beans.BeansException\n *\n */\n public static <T> T getBean(Class<T> clz) throws BeansException {\n T result = (T) beanFactory.getBean(clz);\n return result;\n }\n\n /**\n * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true\n *\n * @param name\n * @return boolean\n */\n public static boolean containsBean(String name) {\n return beanFactory.containsBean(name);\n }\n\n /**\n * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)\n *\n * @param name\n * @return boolean\n * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException\n *\n */\n public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {\n return beanFactory.isSingleton(name);\n }\n\n /**\n * @param name\n * @return Class 注册对象的类型\n * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException\n *\n */\n public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {\n return beanFactory.getType(name);\n }\n\n /**\n * 如果给定的bean名字在bean定义中有别名,则返回这些别名\n *\n * @param name\n * @return\n * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException\n *\n */\n public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {\n return beanFactory.getAliases(name);\n }\n\n /**\n * 获取aop代理对象\n * \n * @param invoker\n * @return\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getAopProxy(T invoker) {\n return (T) AopContext.currentProxy();\n }\n\n /**\n * 获取当前的环境配置,无配置返回null\n *\n * @return 当前的环境配置\n */\n public static String[] getActiveProfiles() {\n return applicationContext.getEnvironment().getActiveProfiles();\n }\n\n /**\n * 获取当前的环境配置,当有多个环境配置时,只获取第一个\n *\n * @return 当前的环境配置\n */\n public static String getActiveProfile() {\n final String[] activeProfiles = getActiveProfiles();\n return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;\n }\n}" }, { "identifier": "DruidProperties", "path": "nhXJH-framework/src/main/java/com/nhXJH/framework/config/properties/DruidProperties.java", "snippet": "@Configuration\npublic class DruidProperties {\n @Value(\"${spring.datasource.druid.initialSize}\")\n private int initialSize;\n\n @Value(\"${spring.datasource.druid.minIdle}\")\n private int minIdle;\n\n @Value(\"${spring.datasource.druid.maxActive}\")\n private int maxActive;\n\n @Value(\"${spring.datasource.druid.maxWait}\")\n private int maxWait;\n\n @Value(\"${spring.datasource.druid.timeBetweenEvictionRunsMillis}\")\n private int timeBetweenEvictionRunsMillis;\n\n @Value(\"${spring.datasource.druid.minEvictableIdleTimeMillis}\")\n private int minEvictableIdleTimeMillis;\n\n @Value(\"${spring.datasource.druid.maxEvictableIdleTimeMillis}\")\n private int maxEvictableIdleTimeMillis;\n\n @Value(\"${spring.datasource.druid.validationQuery}\")\n private String validationQuery;\n\n @Value(\"${spring.datasource.druid.testWhileIdle}\")\n private boolean testWhileIdle;\n\n @Value(\"${spring.datasource.druid.testOnBorrow}\")\n private boolean testOnBorrow;\n\n @Value(\"${spring.datasource.druid.testOnReturn}\")\n private boolean testOnReturn;\n\n public DruidDataSource dataSource(DruidDataSource datasource) {\n /** 配置初始化大小、最小、最大 */\n datasource.setInitialSize(initialSize);\n datasource.setMaxActive(maxActive);\n datasource.setMinIdle(minIdle);\n\n /** 配置获取连接等待超时的时间 */\n datasource.setMaxWait(maxWait);\n\n /** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */\n datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);\n\n /** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */\n datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);\n datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);\n\n /**\n * 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。\n */\n datasource.setValidationQuery(validationQuery);\n /** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */\n datasource.setTestWhileIdle(testWhileIdle);\n /** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */\n datasource.setTestOnBorrow(testOnBorrow);\n /** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */\n datasource.setTestOnReturn(testOnReturn);\n return datasource;\n }\n}" }, { "identifier": "DynamicDataSource", "path": "nhXJH-framework/src/main/java/com/nhXJH/framework/datasource/DynamicDataSource.java", "snippet": "public class DynamicDataSource extends AbstractRoutingDataSource {\n public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {\n super.setDefaultTargetDataSource(defaultTargetDataSource);\n super.setTargetDataSources(targetDataSources);\n super.afterPropertiesSet();\n }\n\n @Override\n protected Object determineCurrentLookupKey() {\n return DynamicDataSourceContextHolder.getDataSourceType();\n }\n}" } ]
import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.sql.DataSource; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; import com.alibaba.druid.util.Utils; import com.nhXJH.common.enums.DataSourceType; import com.nhXJH.common.utils.spring.SpringUtils; import com.nhXJH.framework.config.properties.DruidProperties; import com.nhXJH.framework.datasource.DynamicDataSource;
2,312
package com.nhXJH.framework.config; /** * druid 配置多数据源 * * @author nhXJH */ @Configuration public class DruidConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") public DataSource slaveDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean(name = "dynamicDataSource") @Primary public DynamicDataSource dataSource(DataSource masterDataSource) { Map<Object, Object> targetDataSources = new HashMap<>();
package com.nhXJH.framework.config; /** * druid 配置多数据源 * * @author nhXJH */ @Configuration public class DruidConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") public DataSource slaveDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean(name = "dynamicDataSource") @Primary public DynamicDataSource dataSource(DataSource masterDataSource) { Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
0
2023-10-14 04:57:42+00:00
4k
aleksandarsusnjar/paniql
commandline/src/test/java/net/susnjar/paniql/commandline/PaniqlMainTest.java
[ { "identifier": "CoreResourceDrivenTest", "path": "core/src/test/java/net/susnjar/paniql/CoreResourceDrivenTest.java", "snippet": "public abstract class CoreResourceDrivenTest extends ResourceDrivenTest {\n @Override\n public String getResourcePath() {\n return ResourceDrivenTest.getResourcePath(CoreResourceDrivenTest.class);\n }\n\n\n\n}" }, { "identifier": "Environment", "path": "core/src/main/java/net/susnjar/paniql/Environment.java", "snippet": "public class Environment {\n private static final String SCHEMA_SEPARATOR = System.lineSeparator() + System.lineSeparator();\n\n private final TypeDefinitionRegistry typeRegistry;\n\n private final HashMap<String, OutputTypeModel> outputTypes = new HashMap<>();\n\n private final ObjectTypeModel queryType;\n private final ObjectTypeModel mutationType;\n private final ObjectTypeModel subscriptionType;\n\n public Environment(final File... schemaFiles) throws IOException {\n this(Arrays.asList(schemaFiles).stream().map(File::toPath).collect(Collectors.toList()));\n }\n\n public Environment(final Path... schemaPaths) throws IOException {\n this(Arrays.asList(schemaPaths));\n }\n\n public Environment(final Collection<Path> schemaPaths) throws IOException {\n this(parsePathSchemas(schemaPaths));\n }\n\n public Environment(final String... schemas) {\n this(parseTextSchemas(Arrays.asList(schemas)));\n }\n\n public Environment(final TypeDefinitionRegistry typeRegistry) {\n this.typeRegistry = typeRegistry;\n\n ScalarModel.registerStandardTypes(this);\n registerCustomTypes();\n\n processTypeExtensions();\n initializeDirectRelations();\n establishIndirectRelations();\n\n discoverFields();\n relateFields();\n applyTypeCardinalityDefaults();\n applyFieldCardinalityDefaults();\n applyTypePricingDefaults();\n applyFieldPricingDefaults();\n processJoins();\n\n this.queryType = getOutputType(\"Query\");\n this.mutationType = getOutputType(\"Mutation\");\n this.subscriptionType = getOutputType(\"Subscription\");\n }\n\n public Request request(final String graphQLRequest) {\n Parser parser = new Parser();\n final Document document = parser.parseDocument(graphQLRequest);\n return request(document);\n }\n\n public Request request(final Document document) {\n return new Request(document, this);\n }\n\n public Invoice invoice(final String document) {\n return request(document).invoice();\n }\n\n public Invoice invoice(final Document document) {\n return request(document).invoice();\n }\n\n private void registerCustomTypes() {\n for (final TypeDefinition typeDef: typeRegistry.getTypes(TypeDefinition.class)) {\n OutputTypeModel typeModel = null;\n if (typeDef instanceof InterfaceTypeDefinition) {\n final InterfaceTypeDefinition actual = (InterfaceTypeDefinition)typeDef;\n typeModel = new InterfaceModel(this, actual);\n } else if (typeDef instanceof SDLExtensionDefinition) {\n // we'll handle this separately and expect to find the type to extend first.\n continue;\n } else if (typeDef instanceof EnumTypeDefinition) {\n final EnumTypeDefinition actual = (EnumTypeDefinition)typeDef;\n typeModel = new EnumTypeModel(this, actual);\n } else if (typeDef instanceof ScalarTypeDefinition) {\n final ScalarTypeDefinition actual = (ScalarTypeDefinition)typeDef;\n typeModel = new ScalarModel(this, actual);\n } else if (typeDef instanceof UnionTypeDefinition) {\n final UnionTypeDefinition actual = (UnionTypeDefinition)typeDef;\n typeModel = new UnionModel(this, actual);\n } else if (typeDef instanceof ObjectTypeDefinition) {\n final ObjectTypeDefinition actual = (ObjectTypeDefinition)typeDef;\n typeModel = new ObjectTypeModel(this, actual);\n }\n\n if (typeModel != null) {\n registerType(typeModel);\n }\n }\n }\n\n public void registerType(final OutputTypeModel typeModel) {\n outputTypes.put(typeModel.getSimpleName(), typeModel);\n }\n\n private void processTypeExtensions() {\n for (final TypeDefinition t: typeRegistry.getTypes(TypeDefinition.class)) {\n if (t instanceof EnumTypeExtensionDefinition) {\n final EnumTypeExtensionDefinition extension = (EnumTypeExtensionDefinition)t;\n final EnumTypeModel extendedType = (EnumTypeModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof ScalarTypeExtensionDefinition) {\n final ScalarTypeExtensionDefinition extension = (ScalarTypeExtensionDefinition)t;\n final ScalarModel extendedType = (ScalarModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof UnionTypeExtensionDefinition) {\n final UnionTypeExtensionDefinition extension = (UnionTypeExtensionDefinition)t;\n final UnionModel extendedType = (UnionModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof ObjectTypeExtensionDefinition) {\n final ObjectTypeExtensionDefinition extension = (ObjectTypeExtensionDefinition)t;\n final ObjectTypeModel extendedType = (ObjectTypeModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n } else if (t instanceof InterfaceTypeExtensionDefinition) {\n final InterfaceTypeExtensionDefinition extension = (InterfaceTypeExtensionDefinition)t;\n final InterfaceModel extendedType = (InterfaceModel) outputTypes.get(extension.getName());\n extendedType.applyExtension(extension);\n }\n }\n }\n\n private void initializeDirectRelations() {\n outputTypes.forEach((name, type) -> type.processDirectRelations());\n }\n\n private void establishIndirectRelations() {\n outputTypes.forEach((name, type) -> type.processIndirectRelations());\n }\n\n private void discoverFields() {\n outputTypes.forEach((name, type) -> type.discoverFields());\n }\n\n private void relateFields() {\n outputTypes.forEach((name, type) -> type.relateFields());\n }\n\n private void applyTypeCardinalityDefaults() {\n outputTypes.forEach((name, type) -> type.applyTypeCardinalityDefaults());\n }\n\n private void applyFieldCardinalityDefaults() {\n outputTypes.forEach((name, type) -> type.applyFieldCardinalityDefaults());\n }\n\n private void applyTypePricingDefaults() {\n outputTypes.forEach((name, type) -> type.applyTypePricingDefaults());\n }\n\n private void applyFieldPricingDefaults() {\n outputTypes.forEach((name, type) -> type.applyFieldPricingDefaults());\n }\n\n private void processJoins() {\n outputTypes.forEach((name, type) -> type.processJoins());\n }\n\n public ObjectTypeModel getQueryType() {\n return queryType;\n }\n\n public ObjectTypeModel getMutationType() {\n return mutationType;\n }\n\n public ObjectTypeModel getSubscriptionType() {\n return subscriptionType;\n }\n\n public <T extends OutputTypeModel<?, ?>> T getOutputType(String name) {\n return (T)this.outputTypes.get(name);\n }\n\n public static String getPaniqlSchema() {\n try {\n final String packagePath = Environment.class.getPackageName().replaceAll(\"\\\\.\", \"/\");\n final String resourcePath = packagePath + \"/PaniqlSchema.graphqls\";\n try (\n final InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);\n final Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);\n final BufferedReader bufferedReader = new BufferedReader(reader);\n ) {\n return bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));\n }\n } catch (IOException x) {\n throw new RuntimeException(\"Unexpected I/O error while reading Paniql schema.\");\n }\n }\n\n private static TypeDefinitionRegistry parseTextSchemas(final Collection<String> schemas) {\n final String paniqlSchema = getPaniqlSchema();\n int schemaSize = paniqlSchema.length();\n for (final String schema: schemas) {\n schemaSize += SCHEMA_SEPARATOR.length() + schema.length();\n }\n final StringBuilder schemaBuilder = new StringBuilder(schemaSize);\n schemaBuilder.append(paniqlSchema);\n for (final String schema: schemas) {\n schemaBuilder.append(SCHEMA_SEPARATOR);\n schemaBuilder.append(schema);\n }\n SchemaParser parser = new SchemaParser();\n return parser.parse(schemaBuilder.toString());\n }\n\n private static TypeDefinitionRegistry parsePathSchemas(Collection<Path> schemaPaths) throws IOException {\n final String paniqlSchema = getPaniqlSchema();\n final StringBuilder schemaBuilder = new StringBuilder(65536);\n schemaBuilder.append(paniqlSchema);\n for (final Path path: schemaPaths) {\n schemaBuilder.append(SCHEMA_SEPARATOR);\n schemaBuilder.append(Files.readString(path));\n }\n SchemaParser parser = new SchemaParser();\n return parser.parse(schemaBuilder.toString());\n }\n\n}" } ]
import com.google.common.io.CharStreams; import graphql.schema.idl.TypeDefinitionRegistry; import io.github.classgraph.Resource; import net.susnjar.paniql.CoreResourceDrivenTest; import net.susnjar.paniql.Environment; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collection;
2,199
package net.susnjar.paniql.commandline; public class PaniqlMainTest extends CoreResourceDrivenTest { private TypeDefinitionRegistry typeReg;
package net.susnjar.paniql.commandline; public class PaniqlMainTest extends CoreResourceDrivenTest { private TypeDefinitionRegistry typeReg;
private Environment environment;
1
2023-10-10 01:58:56+00:00
4k
quan100/quan
quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/base/controller/BaseConfigController.java
[ { "identifier": "PageResult", "path": "quan-common-utils/quan-base-common/src/main/java/cn/javaquan/common/base/message/PageResult.java", "snippet": "@Data\npublic class PageResult<T> implements Serializable {\n private static final long serialVersionUID = -6090269741449990770L;\n\n // 分页参数\n /**\n * 总数\n */\n private long total;\n\n /**\n * 总页数\n */\n private int pages;\n\n /**\n * 页码,从1开始\n */\n private Integer pageNum;\n\n /**\n * 页面大小\n */\n private Integer pageSize;\n\n /**\n * 查询数据列表\n */\n private List<T> records = Collections.emptyList();\n\n}" }, { "identifier": "BaseConfigAddCommand", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/base/BaseConfigAddCommand.java", "snippet": "@Data\npublic class BaseConfigAddCommand implements Serializable {\n\n private static final long serialVersionUID = -137770378920503836L;\n\n /**\n *\n */\n private Integer id;\n\n /**\n * 服务器地址\n */\n private String host;\n\n /**\n * 服务端口\n */\n private Integer port;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 协议\n */\n private String protocol;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n}" }, { "identifier": "BaseConfigQuery", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/base/BaseConfigQuery.java", "snippet": "@Data\npublic class BaseConfigQuery extends BasePage implements Serializable {\n\n private static final long serialVersionUID = 742833405930788595L;\n\n /**\n *\n */\n private Integer id;\n\n /**\n * 服务器地址\n */\n private String host;\n\n /**\n * 服务端口\n */\n private Integer port;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 协议\n */\n private String protocol;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n}" }, { "identifier": "BaseConfigUpdateCommand", "path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/base/BaseConfigUpdateCommand.java", "snippet": "@Data\npublic class BaseConfigUpdateCommand implements Serializable {\n\n private static final long serialVersionUID = -137770378920503836L;\n\n /**\n *\n */\n private Integer id;\n\n /**\n * 服务器地址\n */\n private String host;\n\n /**\n * 服务端口\n */\n private Integer port;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 协议\n */\n private String protocol;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n}" }, { "identifier": "Result", "path": "quan-common-utils/quan-base-common/src/main/java/cn/javaquan/common/base/message/Result.java", "snippet": "@Data\npublic class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 485088578586623310L;\n\n /**\n * 标记 JSON字符串中 {@link #uniformFormat} 参数的键值\n */\n public static final String UNIFORM_FORMAT_KEY = \"uniformFormat\";\n\n private Integer code;\n\n private String type;\n\n private String message;\n\n private T data;\n\n /**\n * 标记参数为统一的格式。\n * 在统一参数处理器中,会对所有响应参数进行检查,若响应参数非统一的格式,则将响应参数转换为 {@link Result} 格式并返回。\n * <p>\n * 为了避免当前参数被重复转换,应该设置该参数的值为 {@code true}\n */\n private boolean uniformFormat = true;\n\n public Result(Integer code, String type, String message, T data) {\n this.code = code;\n this.type = type;\n this.message = message;\n this.data = data;\n }\n\n public Result() {\n }\n\n /* 成功结果静态类 **/\n public static <T> Result<T> success() {\n return success(null, null);\n }\n\n public static <T> Result<T> success(T data) {\n return success(null, data);\n }\n\n public static <T> Result<T> success(String msg, T data) {\n return instance(ResultType.MSG_SUCCESS, null, msg, data);\n }\n\n /* 失败结果静态类 **/\n public static <T> Result<T> fail(String msg) {\n return instance(ResultType.MSG_ERROR, null, msg, null);\n }\n\n public static <T> Result<T> fail(int code, String msg) {\n return instance(code, null, msg, null);\n }\n\n public static <T> Result<T> fail(int code, String msg, T data) {\n return instance(code, null, msg, data);\n }\n\n private static <T> Result<T> instance(Integer code, String type, String msg, T data) {\n return new Result<>(code, type, msg, data);\n }\n\n /**\n * 要求业务处理成功\n *\n * @return\n */\n public boolean isSuccess() {\n return ResultType.MSG_SUCCESS.equals(this.code);\n }\n\n /**\n * 要求业务处理成功,且数据不为空\n *\n * @return\n */\n public boolean isData() {\n return isSuccess() && null != data;\n }\n\n public String toJSONString() {\n return JSON.toJSONString(this);\n }\n}" }, { "identifier": "BaseConfigAssembler", "path": "quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/base/convert/BaseConfigAssembler.java", "snippet": "@Mapper(imports = {ID.class, LocalDateUtils.class})\npublic interface BaseConfigAssembler {\n\n BaseConfigAssembler INSTANCE = Mappers.getMapper(BaseConfigAssembler.class);\n\n /**\n * 转换为查询参数\n *\n * @param query\n * @return\n */\n BaseConfigPO toQueryPO(BaseConfigQuery query);\n\n /**\n * 转换为更新参数\n * <p>\n * 更新自动配置更新时间。\n * 更新时不处理删除状态,删除状态交由删除功能处理。\n *\n * @param cmd\n * @return\n */\n @Mapping(target = \"updateTime\", expression = \"java(LocalDateUtils.now())\")\n BaseConfigPO toUpdatePO(BaseConfigUpdateCommand cmd);\n\n /**\n * 转换为新增参数\n * <p>\n * 新增时删除状态默认为正常。\n *\n * @param cmd\n * @return\n */\n @Mapping(target = \"updateTime\", expression = \"java(LocalDateUtils.now())\")\n @Mapping(target = \"createTime\", expression = \"java(LocalDateUtils.now())\")\n BaseConfigPO toAddPO(BaseConfigAddCommand cmd);\n\n /**\n * 转换为新增参数\n *\n * @param cmds\n * @return\n */\n List<BaseConfigPO> toAddPOS(List<BaseConfigAddCommand> cmds);\n}" }, { "identifier": "BaseConfigPO", "path": "quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/base/entity/BaseConfigPO.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"base_config\")\npublic class BaseConfigPO extends Model<BaseConfigPO> {\n private static final long serialVersionUID = 1L;\n\n /**\n *\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * 服务器地址\n */\n private String host;\n\n /**\n * 服务端口\n */\n private Integer port;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 协议\n */\n private String protocol;\n\n /**\n *\n */\n private Date createTime;\n\n /**\n *\n */\n private Date updateTime;\n\n}" }, { "identifier": "BaseConfigRepository", "path": "quan-app/quan-app-core/src/main/java/cn/javaquan/app/core/base/repository/BaseConfigRepository.java", "snippet": "public interface BaseConfigRepository extends IService<BaseConfigPO> {\n\n /**\n * 分页查询\n * <p>\n * 当有排序参数 sort 时,优先根据sort 升序,然后根据创建时间降序\n *\n * @param po\n * @param basePage\n * @return\n */\n PageResult<BaseConfigPO> page(BaseConfigPO po, BasePage basePage);\n\n}" } ]
import cn.javaquan.common.base.message.PageResult; import cn.javaquan.app.common.module.base.BaseConfigAddCommand; import cn.javaquan.app.common.module.base.BaseConfigQuery; import cn.javaquan.app.common.module.base.BaseConfigUpdateCommand; import cn.javaquan.common.base.message.Result; import cn.javaquan.app.core.base.convert.BaseConfigAssembler; import cn.javaquan.app.core.base.entity.BaseConfigPO; import cn.javaquan.app.core.base.repository.BaseConfigRepository; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.util.List;
2,571
package cn.javaquan.app.core.base.controller; /** * 系统通用配置 * * @author JavaQuan * @version 1.0.0 * @date 2023-04-04 10:38:39 */ @RequiredArgsConstructor @RestController @RequestMapping("/core/base/config/") public class BaseConfigController { private final BaseConfigRepository baseConfigRepository; /** * 查询列表 * * @param query * @return */ @GetMapping("page") public Result<PageResult> page(BaseConfigQuery query) {
package cn.javaquan.app.core.base.controller; /** * 系统通用配置 * * @author JavaQuan * @version 1.0.0 * @date 2023-04-04 10:38:39 */ @RequiredArgsConstructor @RestController @RequestMapping("/core/base/config/") public class BaseConfigController { private final BaseConfigRepository baseConfigRepository; /** * 查询列表 * * @param query * @return */ @GetMapping("page") public Result<PageResult> page(BaseConfigQuery query) {
BaseConfigPO po = BaseConfigAssembler.INSTANCE.toQueryPO(query);
5
2023-10-08 06:48:41+00:00
4k
Ghost-chu/DoDoSRV
src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/subcommand/SubCommand_Help.java
[ { "identifier": "DoDoSRV", "path": "src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java", "snippet": "public final class DoDoSRV extends JavaPlugin {\n\n private DodoBot bot;\n private DatabaseManager databaseManager;\n private UserBindManager userBindManager;\n private TextManager textManager;\n private SimpleCommandManager commandManager;\n private DoDoListener doDoListener;\n private DodoManager dodoManager;\n private static Cache<String, String> MESSAGE_ID_TO_ECHO = CacheBuilder.newBuilder()\n .expireAfterWrite(24, TimeUnit.HOURS)\n .maximumSize(15000)\n .build();\n\n\n @Override\n public void onEnable() {\n // Plugin startup logic\n saveDefaultConfig();\n saveDefTranslations();\n this.textManager = new TextManager(this, new File(getDataFolder(), \"messages.yml\"));\n this.databaseManager = initDatabase();\n this.userBindManager = new UserBindManager(this, databaseManager);\n try {\n initDoDoBot();\n } catch (Exception e) {\n Bukkit.getPluginManager().disablePlugin(this);\n throw new RuntimeException(e);\n }\n this.dodoManager = new DodoManager(this);\n this.commandManager = new SimpleCommandManager(this);\n getCommand(\"dodosrv\").setExecutor(this.commandManager);\n getCommand(\"dodosrv\").setTabCompleter(this.commandManager);\n }\n\n private void postInit() {\n //initListeners();\n }\n\n private void initListeners() {\n Bukkit.getPluginManager().registerEvents(new BukkitListener(this), this);\n this.doDoListener = new DoDoListener(this);\n bot.addEventListener(doDoListener);\n }\n\n private DatabaseManager initDatabase() {\n return new DatabaseManager(this);\n }\n\n private void initDoDoBot() {\n String backupClientId = System.getProperty(\"dodosrv.client-id\");\n if(backupClientId == null) backupClientId = \"0\";\n int clientId = getConfig().getInt(\"client-id\", Integer.parseInt(backupClientId) );\n this.bot = new DodoBot(clientId, getConfig().getString(\"bot-token\", System.getProperty(\"dodosrv.bot-token\")));\n initListeners();\n this.bot.runAfter(this::postInit);\n this.bot.start();\n }\n\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n\n public CompletableFuture<String> sendMessageToDefChannel(Message message) {\n return CompletableFuture.supplyAsync(() -> {\n Channel channel = bot().getClient().fetchChannel(getIslandId(), getChatChannel());\n if (!(channel instanceof TextChannel)) {\n return null;\n }\n TextChannel textChannel = (TextChannel) channel;\n String msgId = textChannel.send(message);\n if(message instanceof TextMessage){\n TextMessage msg = (TextMessage) message;\n MESSAGE_ID_TO_ECHO.put(msgId, msg.getContent());\n }\n return msgId;\n });\n }\n\n public CompletableFuture<String> sendMessageToDefChannel(String string) {\n if (!JsonUtil.isJson(string)) {\n return sendMessageToDefChannel(new TextMessage(string));\n } else {\n return sendCardMessageToDefChannel(string);\n }\n }\n\n public CompletableFuture<String> sendCardMessageToDefChannel(String json) {\n return CompletableFuture.supplyAsync(() -> {\n JsonObject finalJson = JsonUtil.readObject(json);\n Channel channel = bot().getClient().fetchChannel(getIslandId(), getChatChannel());\n if (!(channel instanceof TextChannel)) {\n return null;\n }\n TextChannel textChannel = (TextChannel) channel;\n Field gatewayField;\n try {\n gatewayField = ChannelImpl.class.getDeclaredField(\"gateway\");\n gatewayField.setAccessible(true);\n Gateway gateway = (Gateway) gatewayField.get(channel);\n Route route = API.V2.Channel.messageSend().param(\"channelId\", channel.getId()).param(\"messageType\", MessageType.CARD.getCode()).param(\"messageBody\", finalJson);\n return gateway.executeRequest(route).getAsJsonObject().get(\"messageId\").getAsString();\n } catch (NoSuchFieldException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n });\n\n }\n\n\n public String getIslandId() {\n return getConfig().getString(\"dodo.island-id\");\n }\n\n public String getChatChannel() {\n return getConfig().getString(\"dodo.chat-channel\");\n }\n\n private void saveDefTranslations() {\n File file = new File(getDataFolder(), \"messages.yml\");\n if (!file.exists()) {\n saveResource(\"messages.yml\", false);\n }\n }\n\n public DodoBot bot() {\n return bot;\n }\n\n public TextManager text() {\n return textManager;\n }\n\n public DatabaseManager database() {\n return databaseManager;\n }\n\n public UserBindManager userBind() {\n return userBindManager;\n }\n\n public CommandManager commandManager() {\n return commandManager;\n }\n\n public DodoManager dodoManager() {\n return dodoManager;\n }\n\n public Cache<String,String> echoCache(){\n return MESSAGE_ID_TO_ECHO;\n }\n\n}" }, { "identifier": "CommandContainer", "path": "src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandContainer.java", "snippet": "@Data\n@Builder\npublic class CommandContainer {\n @NotNull\n private CommandHandler<?> executor;\n\n private boolean hidden; // Hide from help, tabcomplete\n /*\n E.g you can use the command when having quickshop.removeall.self or quickshop.removeall.others permission\n */\n @Singular\n private List<String> selectivePermissions;\n @Singular\n private List<String> permissions; // E.g quickshop.unlimited\n @NotNull\n private String prefix; // E.g /qs <prefix>\n @Nullable\n private String description; // Will show in the /qs help\n\n private boolean disabled; //Set command is disabled or not.\n @Nullable\n private Supplier<Boolean> disabledSupplier; //Set command is disabled or not.\n @Nullable\n private String disablePlaceholder; //Set the text shown if command disabled\n @Nullable\n private Function<@Nullable CommandSender, @NotNull String> disableCallback; //Set the callback that should return a text to shown\n\n private Class<?> executorType;\n\n @NotNull\n public Class<?> getExecutorType() {\n if (executorType == null) {\n bakeExecutorType();\n }\n return executorType;\n }\n\n public void bakeExecutorType() {\n for (Method declaredMethod : getExecutor().getClass().getMethods()) {\n if (\"onCommand\".equals(declaredMethod.getName()) || \"onTabComplete\".equals(declaredMethod.getName())) {\n if (declaredMethod.getParameterCount() != 3 || declaredMethod.isSynthetic() || declaredMethod.isBridge()) {\n continue;\n }\n executorType = declaredMethod.getParameterTypes()[0];\n return;\n }\n }\n executorType = Object.class;\n }\n\n public final @NotNull String getDisableText(@NotNull CommandSender sender) {\n if (this.getDisableCallback() != null) {\n return this.getDisableCallback().apply(sender);\n } else if (StringUtils.isNotEmpty(this.getDisablePlaceholder())) {\n return this.getDisablePlaceholder();\n } else {\n return \"此命令已被禁用\";\n }\n }\n}" }, { "identifier": "CommandHandler", "path": "src/main/java/com/ghostchu/plugins/dodosrv/command/bukkit/CommandHandler.java", "snippet": "public interface CommandHandler<T extends CommandSender> {\n /**\n * Calling while command executed by specified sender\n *\n * @param sender The command sender but will automatically convert to specified instance\n * @param commandLabel The command prefix (/dodosrv = dodosrv)\n * @param cmdArg The arguments (/dodosrv link Ghost_chu [TAB] will receive Ghost_chu)\n */\n void onCommand(T sender, @NotNull String commandLabel, @NotNull String[] cmdArg);\n\n /**\n * Calling while sender trying to tab-complete\n *\n * @param sender The command sender but will automatically convert to specified instance\n * @param commandLabel The command prefix (/dodosrv = dodosrv)\n * @param cmdArg The arguments (/dodosrv link Ghost_chu [TAB] will receive Ghost_chu)\n * @return Candidate list\n */\n @Nullable\n default List<String> onTabComplete(@NotNull T sender, @NotNull String commandLabel, @NotNull String[] cmdArg) {\n return Collections.emptyList();\n }\n}" } ]
import com.ghostchu.plugins.dodosrv.DoDoSRV; import com.ghostchu.plugins.dodosrv.command.bukkit.CommandContainer; import com.ghostchu.plugins.dodosrv.command.bukkit.CommandHandler; import lombok.AllArgsConstructor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import java.util.List;
2,167
package com.ghostchu.plugins.dodosrv.command.bukkit.subcommand; @AllArgsConstructor public class SubCommand_Help implements CommandHandler<CommandSender> {
package com.ghostchu.plugins.dodosrv.command.bukkit.subcommand; @AllArgsConstructor public class SubCommand_Help implements CommandHandler<CommandSender> {
private final DoDoSRV plugin;
0
2023-10-11 16:16:54+00:00
4k
Hartie95/AnimeGamesLua
GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/SceneMeta.java
[ { "identifier": "SceneBlock", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/block/SceneBlock.java", "snippet": "@ToString\n@Getter\npublic class SceneBlock {\n private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneBlock.class.getName());\n\n private PositionImpl max;\n private PositionImpl min;\n\n private Map<Integer, SceneGroupInfo> groupInfo;\n //private RTree<SceneGroupInfo, Geometry> sceneGroupIndex;\n\n // internal only\n private transient boolean loaded; // Not an actual variable in the scripts either\n private transient SceneMeta meta; // Not an actual variable in the scripts either\n private transient ActivityMeta activityMeta; // Not an actual variable in the scripts either\n private int sceneId;\n private int activityId;\n private int id;\n\n public static SceneBlock of(SceneMeta sceneMeta, @Nullable ActivityMeta activityMeta, int blockId, GIScriptLoader scriptLoader) {\n val block = new SceneBlock(sceneMeta.getSceneId(), activityMeta != null ? activityMeta.getActivityId() : 0, blockId, sceneMeta, activityMeta);\n block.load(scriptLoader);\n return block;\n }\n private SceneBlock(int sceneId, int activityId, int blockId, SceneMeta meta, ActivityMeta activityMeta) {\n this.id = blockId;\n this.sceneId = sceneId;\n this.activityId = activityId;\n this.meta = meta;\n this.activityMeta = activityMeta;\n }\n\n public void setLoaded(boolean loaded) {\n this.loaded = loaded;\n }\n\n public SceneBlock load(GIScriptLoader scriptLoader) {\n if (this.loaded) {\n return this;\n }\n this.setLoaded(true);\n\n val scriptType = activityId == 0 ? ScriptSource.SCENE : ScriptSource.ACTIVITY;\n val typeId = activityId == 0 ? sceneId : activityId;\n val sceneBlockParams = new SceneBlockScriptLoadParams(scriptType, typeId, id);\n if( !scriptLoader.loadData(sceneBlockParams, (cs -> {\n // Set groups\n this.groupInfo = cs.getGlobalVariableList(\"groups\", SceneGroupInfo.class).stream()\n .collect(Collectors.toMap(x -> x.getId(), y -> y, (a, b) -> a));\n\n this.groupInfo.values().forEach(g -> {\n g.blockId = this.id;\n g.sceneMeta = meta;\n g.activityId = activityId;\n });\n //this.sceneGroupIndex = SceneIndexManager.buildIndex(3, this.groupInfo.values(), g -> g.getPos().toPoint());\n }))){\n return null;\n }\n if(activityMeta!=null) {\n activityMeta.getGroupsInfos().putAll(this.groupInfo);\n } else {\n meta.getGroupsInfos().putAll(this.groupInfo);\n }\n\n logger.debug(() -> \"Successfully loaded block \" + this.id + \" in scene \"+sceneId+\".\");\n return this;\n }\n\n public Rectangle toRectangle() {\n return Rectangle.create(this.min.toXZDoubleArray(), this.max.toXZDoubleArray());\n }\n}" }, { "identifier": "SceneGroupInfo", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/block/SceneGroupInfo.java", "snippet": "@Getter\npublic class SceneGroupInfo {\n private int id;\n private int refresh_id;\n private int area;\n @Nullable\n private PositionImpl pos;\n @Nullable\n private SceneReplaceable is_replaceable;\n private final boolean dynamic_load = false;\n @Nullable\n private SceneBusiness business;\n @Nullable\n private GroupLifecycle life_cycle = GroupLifecycle.FULL_TIME__CYCLE;\n private int activity_revise_level_grow_id;\n private int rely_start_world_level_limit_activity_id; // SceneScriptConfig LuaConfigMgr\n private int vision_type;\n private boolean across_block = false;\n private boolean unload_when_disconnect = false;\n private boolean ignore_world_level_revise = false;\n private boolean force_unload_nodelay = false;\n private boolean force_clean_sub_entity = false;\n private boolean is_load_by_vision_type = false;\n private int load_strategy;\n private Set<String> forbid_monster_die; //todo find enum values\n private List<Integer> related_level_tag_series_list;\n private List<Integer> group_tag_list;\n private List<Integer> weathers;\n\n // internal variables\n transient int blockId;\n transient int activityId;\n transient SceneMeta sceneMeta;\n\n public int getBusinessType() {\n return this.business == null ? 0 : this.business.getType();\n }\n\n public boolean isReplaceable() {\n return this.is_replaceable != null && this.is_replaceable.isValue();\n }\n}" }, { "identifier": "SceneGroup", "path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/scene/group/SceneGroup.java", "snippet": "@SuppressWarnings(\"FieldMayBeFinal\")\n@ToString\n@Getter\npublic class SceneGroup {\n private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneGroup.class.getName());\n\n // from group script\n @Nullable\n private Map<Integer, SceneMonster> monsters; // <ConfigId, Monster>\n @Nullable\n private Map<Integer, SceneNPC> npcs; // <ConfigId, Npc>\n @Nullable\n private Map<Integer, SceneGadget> gadgets; // <ConfigId, Gadgets>\n @Nullable\n private Map<String, SceneTrigger> triggers; // <TriggerName, Trigger>\n @Nullable\n private Map<Integer, SceneRegion> regions; // <ConfigId, Region>\n @Nullable\n private Map<Integer, ScenePoint> points; // <ConfigId, ScenePoint>\n @Nullable\n private List<SceneVar> variables;\n\n @Nullable\n private SceneInitConfig init_config;\n @Nullable\n private List<SceneSuite> suites;\n\n private List<SceneMonsterPool> monster_pools;\n private List<List<Integer>> sight_groups;\n\n @Nullable\n private SceneGarbage garbages;\n\n\n // internal\n private transient SceneGroupInfo groupInfo;\n private transient SceneMeta sceneMeta;\n private transient boolean loaded; // Not an actual variable in the scripts either\n private transient LuaScript script;\n\n public static SceneGroup of(SceneGroupInfo groupInfo) {\n var group = new SceneGroup(groupInfo);\n return group;\n }\n\n protected SceneGroup(SceneGroupInfo groupInfo) {\n this.groupInfo = groupInfo;\n this.sceneMeta = groupInfo.getSceneMeta();\n }\n\n public boolean hasGarbages() {\n return this.garbages != null && !garbages.isEmpty();\n }\n\n @Nullable\n public List<SceneGadget> getGarbageGadgets() {\n return this.garbages == null ? null : this.garbages.getGadgets();\n }\n\n\n public SceneSuite getSuiteByIndex(int index) {\n if (index < 1 || index > suites.size()) {\n return null;\n }\n return this.suites.get(index - 1);\n }\n\n public synchronized SceneGroup load(GIScriptLoader scriptLoader) {\n if (this.loaded) {\n return this;\n }\n // Set flag here so if there is no script, we don't call this function over and over again.\n this.loaded = true;\n val sceneId = sceneMeta.getSceneId();\n val groupId = groupInfo.getId();\n val blockId = groupInfo.getBlockId();\n val activityId = groupInfo.getActivityId();\n\n val scriptType = activityId == 0 ? ScriptSource.SCENE : ScriptSource.ACTIVITY;\n val typeId = activityId == 0 ? sceneId : activityId;\n val groupParams = new SceneGroupScriptLoadParams(scriptType, typeId, groupId);\n if (!scriptLoader.loadData(groupParams, cs -> {\n this.script = cs;\n // Set\n this.monsters = cs.getGlobalVariableList(\"monsters\", SceneMonster.class).stream()\n .collect(Collectors.toMap(x -> x.config_id, y -> y, (a, b) -> a));\n this.monsters.values().forEach(m -> {\n m.groupId = groupId;\n m.blockId = blockId;\n m.sceneMeta = sceneMeta;\n });\n\n this.npcs = cs.getGlobalVariableList(\"npcs\", SceneNPC.class).stream()\n .collect(Collectors.toMap(x -> x.config_id, y -> y, (a, b) -> a));\n this.npcs.values().forEach(m -> {\n m.groupId = groupId;\n m.blockId = blockId;\n m.sceneMeta = sceneMeta;\n });\n\n this.gadgets = cs.getGlobalVariableList(\"gadgets\", SceneGadget.class).stream()\n .collect(Collectors.toMap(x -> x.config_id, y -> y, (a, b) -> a));\n this.gadgets.values().forEach(m -> {\n m.groupId = groupId;\n m.blockId = blockId;\n m.sceneMeta = sceneMeta;\n });\n\n this.triggers = cs.getGlobalVariableList(\"triggers\", SceneTrigger.class).stream()\n .collect(Collectors.toMap(SceneTrigger::getName, y -> y, (a, b) -> a));\n this.triggers.values().forEach(t -> {\n t.setGroupId(groupId);\n t.setBlockId(blockId);\n t.setSceneMeta(sceneMeta);\n });\n\n this.suites = cs.getGlobalVariableList(\"suites\", SceneSuite.class);\n this.regions = cs.getGlobalVariableList(\"regions\", SceneRegion.class).stream()\n .collect(Collectors.toMap(x -> x.config_id, y -> y, (a, b) -> a));\n this.regions.values().forEach(m -> {\n m.groupId = groupId;\n m.blockId = blockId;\n m.sceneMeta = sceneMeta;\n });\n\n this.init_config = cs.getGlobalVariable(\"init_config\", SceneInitConfig.class);\n\n // Garbages // TODO: fix properly later\n /*Object garbagesValue = this.bindings.get(\"garbages\");\n if (garbagesValue instanceof LuaValue garbagesTable) {\n this.garbages = new SceneGarbage();\n if (garbagesTable.checktable().get(\"gadgets\") != LuaValue.NIL) {\n this.garbages.gadgets = ScriptLoader.getSerializer().toList(SceneGadget.class, garbagesTable.checktable().get(\"gadgets\").checktable());\n this.garbages.gadgets.forEach(m -> m.group = this);\n }\n }*/\n\n // Add variables to suite\n this.variables = cs.getGlobalVariableList(\"variables\", SceneVar.class);\n\n this.monster_pools = cs.getGlobalVariableList(\"monster_pools\", SceneMonsterPool.class);\n //this.sight_groups = cs.getGlobalVariableList(\"sight_groups\", List<Integer>.class);\n\n // Add monsters and gadgets to suite\n this.suites.forEach(i -> i.init(this));\n })) {\n return null;\n }\n\n logger.debug(() -> \"Successfully loaded group \" + groupId + \" in scene \" + sceneId + \".\");\n return this;\n }\n\n public int findInitSuiteIndex(int exclude_index) { //TODO: Investigate end index\n if (init_config == null) return 1;\n if (init_config.getIo_type() == 1) return init_config.getSuite(); //IO TYPE FLOW\n if (init_config.isRand_suite()) {\n if (suites.size() == 1) {\n return init_config.getSuite();\n } else {\n List<Integer> randSuiteList = new ArrayList<>();\n for (int i = 0; i < suites.size(); i++) {\n if (i == exclude_index) continue;\n\n var suite = suites.get(i);\n for (int j = 0; j < suite.getRand_weight(); j++) randSuiteList.add(Integer.valueOf(i + 1));\n }\n return randSuiteList.get(new Random().nextInt(randSuiteList.size()));\n }\n }\n return init_config.getSuite();\n }\n\n public Optional<SceneBossChest> searchBossChestInGroup() {\n return this.gadgets.values().stream().map(g -> g.getBoss_chest()).filter(Objects::nonNull)\n .filter(bossChest -> bossChest.getMonster_config_id() > 0)\n .findFirst();\n }\n\n /*public List<SceneGroup> getReplaceableGroups(Collection<SceneGroup> loadedGroups) {\n return this.is_replaceable == null ? List.of() :\n Optional.ofNullable(GameData.getGroupReplacements().get(this.id)).stream()\n .map(GroupReplacementData::getReplace_groups)\n .flatMap(List::stream)\n .map(replacementId -> loadedGroups.stream().filter(g -> g.id == replacementId).findFirst())\n .filter(Optional::isPresent).map(Optional::get)\n .filter(replacementGroup -> replacementGroup.is_replaceable != null)\n .filter(replacementGroup -> (replacementGroup.is_replaceable.isValue()\n && replacementGroup.is_replaceable.getVersion() <= this.is_replaceable.getVersion())\n || replacementGroup.is_replaceable.isNew_bin_only())\n .toList();\n }*/\n}" } ]
import io.github.oshai.kotlinlogging.KLogger; import io.github.oshai.kotlinlogging.KotlinLogging; import lombok.Getter; import lombok.ToString; import lombok.val; import org.anime_game_servers.gi_lua.models.loader.SceneDummyPointScriptLoadParams; import org.anime_game_servers.gi_lua.models.loader.SceneMetaScriptLoadParams; import org.anime_game_servers.gi_lua.models.scene.block.SceneBlock; import org.anime_game_servers.gi_lua.models.scene.block.SceneGroupInfo; import org.anime_game_servers.gi_lua.models.scene.group.SceneGroup; import org.anime_game_servers.gi_lua.models.loader.GIScriptLoader; import org.anime_game_servers.lua.engine.LuaScript; import javax.annotation.Nullable; import java.util.HashMap; import java.util.List; import java.util.Map;
3,382
package org.anime_game_servers.gi_lua.models.scene; @ToString @Getter public class SceneMeta { private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneMeta.class.getName()); private int sceneId; private SceneConfig config; private List<Integer> blockIds; private Map<Integer, ActivityMeta> activities = new HashMap<>();
package org.anime_game_servers.gi_lua.models.scene; @ToString @Getter public class SceneMeta { private static KLogger logger = KotlinLogging.INSTANCE.logger(SceneMeta.class.getName()); private int sceneId; private SceneConfig config; private List<Integer> blockIds; private Map<Integer, ActivityMeta> activities = new HashMap<>();
private Map<Integer, SceneBlock> blocks;
0
2023-10-07 16:45:54+00:00
4k
PDC2023/project
src/main/java/pdc/project/entity/Ghost.java
[ { "identifier": "Universe", "path": "src/main/java/pdc/project/Universe.java", "snippet": "public final class Universe {\r\n\r\n public Player player = new Player(this, 0, 0);\r\n private int score = 0;\r\n public final Main main;\r\n\r\n public Set<Entity> entities = new HashSet<>();\r\n public List<Entity> entitiesToAdd = new ArrayList<>();\r\n public List<Entity> entitiesToRemove = new ArrayList<>();\r\n\r\n public SavePoint lastSavePoint;\r\n\r\n /**\r\n * Constructs a new game universe with the specified main application instance.\r\n *\r\n * @param main The main application instance associated with this universe.\r\n */\r\n public Universe(Main main) {\r\n this.main = main;\r\n entities.add(player);\r\n lastSavePoint = new SavePoint(0, this, 0, 0);\r\n entities.add(lastSavePoint);\r\n }\r\n\r\n public boolean spacePressed() {\r\n return pressedKeys.contains(KeyEvent.VK_SPACE);\r\n }\r\n\r\n /**\r\n * Gets a list of entities that are colliding with the specified entity.\r\n *\r\n * @param entity The entity for which collision detection is performed.\r\n * @return A list of entities that are colliding with the specified entity.\r\n */\r\n public List<Entity> getCollisionEntities(Entity entity) {\r\n var collisionEntities = new ArrayList<Entity>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n if (Collision.checkCollision(entity, otherEntity)) {\r\n collisionEntities.add(otherEntity);\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public List<CollisionRecord> getCollisionRecords(Entity entity) {\r\n var collisionEntities = new ArrayList<CollisionRecord>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n var result = Collision.getCollision(entity, otherEntity);\r\n if (result.getState() != CollisionState.NONE) {\r\n collisionEntities.add(new CollisionRecord(otherEntity, result));\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public void addScore(int score) {\r\n this.score += score;\r\n }\r\n\r\n public int getCollectedCoins() {\r\n return score;\r\n }\r\n\r\n\r\n /**\r\n * Fixes overlapping entities and returns a list of collision records.\r\n *\r\n * @param entity The entity for which collision resolution is performed.\r\n * @return A list of collision records indicating resolved collisions.\r\n */\r\n public List<CollisionRecord> fixOverlappingAndGetCollisionEntities(Entity entity) {\r\n var collisionEntities = new ArrayList<CollisionRecord>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n var result = Collision.getCollision(entity, otherEntity);\r\n if (result.getState() != CollisionState.NONE) {\r\n collisionEntities.add(new CollisionRecord(otherEntity, result));\r\n }\r\n if (entity instanceof MoveableEntity && !(otherEntity instanceof NoPhysicalCollisionEntity)) {\r\n if (result.getState() == CollisionState.OVERLAPPING) {\r\n var direction = result.getDirection();\r\n var otherBox = otherEntity.getCollisionBox();\r\n var entityBox = entity.getCollisionBox();\r\n var moveableEntity = (MoveableEntity) entity;\r\n\r\n int x;\r\n int y;\r\n switch (direction) {\r\n case DOWN:\r\n var otherTopY = otherEntity.getY() - otherBox.getHeight() / 2;\r\n y = otherTopY - entityBox.getHeight() / 2;\r\n moveableEntity.setY(y);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityY() > 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityY(0);\r\n }\r\n break;\r\n case UP:\r\n var otherBottomY = otherEntity.getY() + otherBox.getHeight() / 2;\r\n y = otherBottomY + entityBox.getHeight() / 2;\r\n moveableEntity.setY(y);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityY() < 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityY(0);\r\n }\r\n break;\r\n case LEFT:\r\n var otherRightX = otherEntity.getX() + otherBox.getWidth() / 2;\r\n x = otherRightX + entityBox.getWidth() / 2;\r\n moveableEntity.setX(x);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityX() < 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityX(0);\r\n }\r\n break;\r\n case RIGHT:\r\n var otherLeftX = otherEntity.getX() - otherBox.getWidth() / 2;\r\n x = otherLeftX - entityBox.getWidth() / 2;\r\n moveableEntity.setX(x);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityX() > 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityX(0);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public Set<Integer> pressedKeys = new HashSet<>();\r\n\r\n public boolean upPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_UP) || pressedKeys.contains(KeyEvent.VK_W);\r\n }\r\n\r\n public boolean leftPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_LEFT) || pressedKeys.contains(KeyEvent.VK_A);\r\n }\r\n\r\n public boolean rightPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_RIGHT) || pressedKeys.contains(KeyEvent.VK_D);\r\n }\r\n\r\n public boolean downPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_DOWN) || pressedKeys.contains(KeyEvent.VK_S);\r\n }\r\n\r\n public void goingToSavePoint() {\r\n var effect = new SavePointResumeEffect(this, player.getX(), player.getY());\r\n effect.facingLeft = player.facingLeft;\r\n entitiesToAdd.add(effect);\r\n entitiesToRemove.add(player);\r\n main.gameScreen.pauseForReturningToSavePoint();\r\n SoundEffect.play(SoundEffect.death);\r\n Timer timer = new Timer(500, e -> {\r\n effect.die();\r\n entitiesToAdd.add(player);\r\n main.gameScreen.resumeForReturningToSavePoint();\r\n player.setVelocityX(0);\r\n player.setVelocityY(0);\r\n player.setX(lastSavePoint.getX());\r\n player.setY(lastSavePoint.getY());\r\n });\r\n timer.setRepeats(false);\r\n timer.start();\r\n }\r\n\r\n public void win() {\r\n main.switchToWinScreen();\r\n }\r\n\r\n private void checkPlayerOutOfBound() {\r\n if (this.player.getY() > 1024) {\r\n this.player.goingToSavePoint();\r\n }\r\n }\r\n\r\n public void preTick() {\r\n this.entities.addAll(this.entitiesToAdd);\r\n this.entitiesToRemove.forEach(this.entities::remove);\r\n this.entitiesToAdd.clear();\r\n this.entitiesToRemove.clear();\r\n }\r\n\r\n public void nextLevel() {\r\n main.switchToLevel1();\r\n }\r\n\r\n public void tick() {\r\n var deaths = new ArrayList<Entity>();\r\n for (Entity entity : entities) {\r\n if (entity.dead()) {\r\n deaths.add(entity);\r\n continue;\r\n }\r\n entity.tick();\r\n }\r\n deaths.forEach(entities::remove);\r\n checkPlayerOutOfBound();\r\n }\r\n\r\n}\r" }, { "identifier": "Utils", "path": "src/main/java/pdc/project/Utils.java", "snippet": "public final class Utils {\r\n\r\n /**\r\n * Loads an image from the specified resource path.\r\n *\r\n * @param path The path to the image resource.\r\n * @return The loaded image.\r\n */\r\n public static Image loadImage(String path) {\r\n return new ImageIcon(Objects.requireNonNull(Utils.class.getResource(path))).getImage();\r\n }\r\n\r\n /**\r\n * Loads an image from the specified resource path and scales it by the given ratio.\r\n *\r\n * @param path The path to the image resource.\r\n * @param ratio The scaling ratio.\r\n * @return The loaded and scaled image.\r\n */\r\n public static Image loadImage(String path, double ratio) {\r\n return scaleImageByRatio(loadImage(path), ratio);\r\n }\r\n\r\n /**\r\n * Scales an image to the specified width and height.\r\n *\r\n * @param image The image to be scaled.\r\n * @param width The target width.\r\n * @param height The target height.\r\n * @return The scaled image.\r\n */\r\n public static Image scaleImage(Image image, int width, int height) {\r\n return image.getScaledInstance(width, height, Image.SCALE_DEFAULT);\r\n }\r\n\r\n /**\r\n * Scales an image by the specified ratio.\r\n *\r\n * @param image The image to be scaled.\r\n * @param ratio The scaling ratio.\r\n * @return The scaled image.\r\n */\r\n public static Image scaleImageByRatio(Image image, double ratio) {\r\n int newWidth = (int) (image.getWidth(null) * ratio);\r\n int newHeight = (int) (image.getHeight(null) * ratio);\r\n return scaleImage(image, newWidth, newHeight);\r\n }\r\n\r\n /**\r\n * Draws an image on a {@link Graphics2D} context with the center of the image positioned at (x, y).\r\n *\r\n * @param g2d The {@link Graphics2D} context used for drawing.\r\n * @param image The image to be drawn.\r\n * @param x The x-coordinate of the center of the image.\r\n * @param y The y-coordinate of the center of the image.\r\n */\r\n public static void drawImage(Graphics2D g2d, Image image, int x, int y) {\r\n g2d.drawImage(image, (int) x - image.getWidth(null) / 2, (int) y - image.getHeight(null) / 2, null);\r\n }\r\n\r\n /**\r\n * Draws an image flipped horizontally on a {@link Graphics2D} context with the center of the image positioned at (x, y).\r\n *\r\n * @param g2d The {@link Graphics2D} context used for drawing.\r\n * @param image The image to be drawn.\r\n * @param x The x-coordinate of the center of the image.\r\n * @param y The y-coordinate of the center of the image.\r\n */\r\n public static void drawImageFlipX(Graphics2D g2d, Image image, int x, int y) {\r\n g2d.drawImage(image, (int) x + image.getWidth(null) / 2, (int) y - image.getHeight(null) / 2, -image.getWidth(null), image.getHeight(null), null);\r\n }\r\n}\r" } ]
import pdc.project.Universe; import pdc.project.Utils;
2,574
package pdc.project.entity; public class Ghost extends AbstractMovingEntity implements Enemy { private final static double SIZE_RATIO = 1.0; private final static double SPEED = 1; private final int xEnd; private final int xStart;
package pdc.project.entity; public class Ghost extends AbstractMovingEntity implements Enemy { private final static double SIZE_RATIO = 1.0; private final static double SPEED = 1; private final int xEnd; private final int xStart;
public Ghost(int xStart, int xEnd, Universe universe, int y) {
0
2023-10-09 03:01:39+00:00
4k
jmaes12345/lhasa-kata
examples/java1/src/main/java/org/katas/Assess.java
[ { "identifier": "catToOutputDir", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static String catToOutputDir(String category) {\n\tswitch (category) {\n\t\tcase \"I\":\n\t\t\treturn CAT1_DIR;\n\t\tcase \"II\":\n\t\t\treturn CAT2_DIR;\n\t\tcase \"III\":\n\t\t\treturn CAT3_DIR;\n\t\tcase \"Unclassified\":\n\t\tdefault:\n\t\t\treturn UNCLASSIFIED_DIR;\n\t}\n}" }, { "identifier": "countFiles", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static int countFiles(String dirName) {\n\treturn countFiles(dirName, null);\n}" }, { "identifier": "foundInFiles", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static boolean foundInFiles(File[] files, String filename) {\n\tif (files == null || files.length == 0) {\n\t\treturn false;\n\t}\n\treturn Arrays.stream(files).anyMatch(file -> file.getName().equals(filename));\n}" }, { "identifier": "getTestCases", "path": "examples/java1/src/main/java/org/katas/AssessUtils.java", "snippet": "public static List<List<String>> getTestCases(String inputLocation) {\n\tvar inputDir = new File(inputLocation);\n\tif (!inputDir.exists()) {\n\t\t//inputDir.mkdirs();\n\t\tthrow new IllegalStateException(\"Input directory does not exist: \" + inputDir);\n\t}\n\tvar files = inputDir.listFiles((dir, name) -> name.toLowerCase().endsWith(\".svg\"));\n\tif (files == null || files.length == 0) {\n\t\tthrow new IllegalStateException(\"Input directory is empty: \" + inputDir);\n\t}\n\n\tList<List<String>> testCases = Arrays.stream(files)\n\t\t\t.map(file -> {\n\t\t\t\tString filename = file.getName();\n\t\t\t\tvar chunks = filename.split(\"-\");\n\t\t\t\tString cat = chunks[chunks.length - 1].split(\"\\\\.\")[0].trim();\n\t\t\t\treturn List.of(filename, cat);\n\t\t\t}).toList();\n\n\tif (testCases.isEmpty()) {\n\t\tthrow new IllegalStateException(\"Input directory is empty: \" + inputDir);\n\t}\n\n\treturn testCases;\n}" }, { "identifier": "OUTPUT_DIRS_ALL", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final List<String> OUTPUT_DIRS_ALL = List.of(CAT1_DIR, CAT2_DIR, CAT3_DIR, UNCLASSIFIED_DIR);" }, { "identifier": "CAT1_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT1_DIR = OUTPUT_DIR + \"/\" + \"Cat1\";" }, { "identifier": "CAT2_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT2_DIR = OUTPUT_DIR + \"/\" + \"Cat2\";" }, { "identifier": "CAT3_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String CAT3_DIR = OUTPUT_DIR + \"/\" + \"Cat3\";" }, { "identifier": "INPUT_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String INPUT_DIR = ROOT_DIR + \"/\" + \"input\";" }, { "identifier": "ROOT_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String ROOT_DIR = \"C:/kata-svg\";" }, { "identifier": "UNCLASSIFIED_DIR", "path": "examples/java1/src/main/java/org/katas/SvgLocations.java", "snippet": "public static final String UNCLASSIFIED_DIR = OUTPUT_DIR + \"/\" + \"Unclassified\";" } ]
import static org.katas.AssessUtils.catToOutputDir; import static org.katas.AssessUtils.countFiles; import static org.katas.AssessUtils.foundInFiles; import static org.katas.AssessUtils.getTestCases; import static org.katas.SvgLocations.OUTPUT_DIRS_ALL; import static org.katas.SvgLocations.CAT1_DIR; import static org.katas.SvgLocations.CAT2_DIR; import static org.katas.SvgLocations.CAT3_DIR; import static org.katas.SvgLocations.INPUT_DIR; import static org.katas.SvgLocations.ROOT_DIR; import static org.katas.SvgLocations.UNCLASSIFIED_DIR; import java.io.File;
1,797
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir); int foundCat2 = countFiles(CAT2_DIR, rootDir); int foundCat3 = countFiles(CAT3_DIR, rootDir); int foundUnclassified = countFiles(UNCLASSIFIED_DIR, rootDir); boolean allCorrect = expectedCat1 == foundCat1 && expectedCat2 == foundCat2 && expectedCat3 == foundCat3 && expectedUnclassified == foundUnclassified; String message = allCorrect ? "/*** Great news, you have the correct number of files in each bucket! ***/" : "/*** Close but no carcinogenic dried leaf roll... ***/"; System.out.printf(""" %s Cat1 expected %d, found %d Cat2 expected %d, found %d Cat3 expected %d, found %d Unclassified expected %d, found %d """, message, expectedCat1, foundCat1, expectedCat2, foundCat2, expectedCat3, foundCat3, expectedUnclassified, foundUnclassified); System.out.println("\nRunning detailed tests..."); testCases.forEach(tc -> detailTest(tc.get(0), tc.get(1))); } private static void detailTest(String svgFileName, String expectedCategory) { var outputDir = catToOutputDir(expectedCategory); var contents = new File(outputDir).listFiles((dir, name) -> name.toLowerCase().endsWith(".svg")); if (foundInFiles(contents, svgFileName)) { System.out.printf("SUCCESS: '%s' found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); } else { System.out.printf("FAILURE: '%s' not found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); }
package org.katas; public class Assess { public static void main(String[] args) { String rootDir = args.length > 0 ? args[0] : null; if ("help".equals(rootDir) || "h".equals(rootDir) || "--help".equals(rootDir)) { System.out.println(""" Run using Java 17 To run summary test using default folders (C:/kata-svg), pass no arguments. To run summary test using custom folder, pass absolute path as first argument: java -jar svg-1.0-SNAPSHOT.jar C:/Test/svgClassificationFiles To run detailed test using default folders (C:/kata-svg): java -jar svg-1.0-SNAPSHOT.jar " " detail To run detailed test using custom folders: java -jar svg-1.0-SNAPSHOT.jar "C:/Test/kata files" detail """); rootDir = null; } var workingDir = rootDir != null && !rootDir.isBlank() ? rootDir : ROOT_DIR; System.out.println("Using 'input' and 'output' folders in parent directory: " + workingDir); String detailLevel = args.length > 1 ? args[1] : null; var summaryOnly = "summary".equalsIgnoreCase(detailLevel) || "s".equalsIgnoreCase(detailLevel); var detailMessage = summaryOnly ? "Running summary test..." : "Running summary and detailed test..."; System.out.println(detailMessage); var inputLocation = INPUT_DIR; if (rootDir != null && !rootDir.isBlank()) { inputLocation = rootDir + "/" + inputLocation.substring(inputLocation.indexOf("input")); } System.out.println("Reading from 'input' directory: " + inputLocation); var testCases = getTestCases(inputLocation); int expectedCat1 = testCases.stream().filter(tc -> "I".equals(tc.get(1))).toList().size(); int expectedCat2 = testCases.stream().filter(tc -> "II".equals(tc.get(1))).toList().size(); int expectedCat3 = testCases.stream().filter(tc -> "III".equals(tc.get(1))).toList().size(); int expectedUnclassified = testCases.stream().filter(tc -> "unclassified".equals(tc.get(1))).toList().size(); int foundCat1 = countFiles(CAT1_DIR, rootDir); int foundCat2 = countFiles(CAT2_DIR, rootDir); int foundCat3 = countFiles(CAT3_DIR, rootDir); int foundUnclassified = countFiles(UNCLASSIFIED_DIR, rootDir); boolean allCorrect = expectedCat1 == foundCat1 && expectedCat2 == foundCat2 && expectedCat3 == foundCat3 && expectedUnclassified == foundUnclassified; String message = allCorrect ? "/*** Great news, you have the correct number of files in each bucket! ***/" : "/*** Close but no carcinogenic dried leaf roll... ***/"; System.out.printf(""" %s Cat1 expected %d, found %d Cat2 expected %d, found %d Cat3 expected %d, found %d Unclassified expected %d, found %d """, message, expectedCat1, foundCat1, expectedCat2, foundCat2, expectedCat3, foundCat3, expectedUnclassified, foundUnclassified); System.out.println("\nRunning detailed tests..."); testCases.forEach(tc -> detailTest(tc.get(0), tc.get(1))); } private static void detailTest(String svgFileName, String expectedCategory) { var outputDir = catToOutputDir(expectedCategory); var contents = new File(outputDir).listFiles((dir, name) -> name.toLowerCase().endsWith(".svg")); if (foundInFiles(contents, svgFileName)) { System.out.printf("SUCCESS: '%s' found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); } else { System.out.printf("FAILURE: '%s' not found in correct category: %s, dir: '%s'%n", svgFileName, expectedCategory, outputDir); }
var wrongDirsFileFoundIn = OUTPUT_DIRS_ALL.stream()
4
2023-10-07 21:45:39+00:00
4k
qmjy/mapbox-offline-server
src/main/java/io/github/qmjy/mapbox/controller/MapServerFontsController.java
[ { "identifier": "AppConfig", "path": "src/main/java/io/github/qmjy/mapbox/config/AppConfig.java", "snippet": "@Component\n@ConfigurationProperties\npublic class AppConfig {\n\n public static final String FILE_EXTENSION_NAME_MBTILES = \".mbtiles\";\n public static final String FILE_EXTENSION_NAME_TPK = \".tpk\";\n public static final String FILE_EXTENSION_NAME_PBF = \".pbf\";\n public static final String FILE_EXTENSION_NAME_JSON = \".json\";\n public static final String FILE_EXTENSION_NAME_GEOJSON = \".geojson\";\n public static final String FILE_EXTENSION_NAME_PNG = \".png\";\n\n public static final MediaType APPLICATION_X_PROTOBUF_VALUE = MediaType.valueOf(\"application/x-protobuf\");\n\n @Value(\"${spring.datasource.driver-class-name}\")\n private String driverClassName;\n\n /**\n * 数据文件存放路径\n */\n @Value(\"${data-path}\")\n private String dataPath = \"\";\n\n\n public String getDriverClassName() {\n return driverClassName;\n }\n\n public String getDataPath() {\n return dataPath;\n }\n}" }, { "identifier": "FontsFileModel", "path": "src/main/java/io/github/qmjy/mapbox/model/FontsFileModel.java", "snippet": "public class FontsFileModel {\n private final File folder;\n\n public FontsFileModel(File fontFolder) {\n this.folder = fontFolder;\n }\n\n public File getFolder() {\n return folder;\n }\n}" }, { "identifier": "MapServerDataCenter", "path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java", "snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n private static final Map<String, TilesFileModel> tilesMap = new HashMap<>();\n\n\n private static final Map<String, Map<Long, TPKZoomLevel>> tpkMap = new HashMap<>();\n private static final Map<String, TPKFile> tpkFileMap = new HashMap<>();\n\n /**\n * 字体文件模型\n */\n private static final Map<String, FontsFileModel> fontsMap = new HashMap<>();\n\n /**\n * 行政区划数据。key:行政级别、value:区划对象列表\n */\n @Getter\n private static final Map<Integer, List<SimpleFeature>> administrativeDivisionLevel = new HashMap<>();\n\n /**\n * 行政区划数据。key:区划ID、value:区划对象\n */\n @Getter\n private static final Map<Integer, SimpleFeature> administrativeDivision = new HashMap<>();\n\n /**\n * 行政区划层级树\n */\n @Getter\n private static AdministrativeDivisionTmp simpleAdminDivision;\n\n /**\n * 初始化数据源\n *\n * @param className 驱动名称\n * @param file 待链接的数据库文件\n */\n public static void initJdbcTemplate(String className, File file) {\n TilesFileModel dbFileModel = new TilesFileModel(file, className);\n tilesMap.put(file.getName(), dbFileModel);\n }\n\n /**\n * 初始化TPK文件\n *\n * @param tpk tpk地图数据文件\n */\n public static void initTpk(File tpk) {\n Map<Long, TPKZoomLevel> zoomLevelMap = new HashMap<>();\n TPKFile tpkFile = new TPKFile(tpk, zoomLevelMap);\n tpkMap.put(tpk.getName(), zoomLevelMap);\n tpkFileMap.put(tpk.getName(), tpkFile);\n }\n\n\n /**\n * 初始化字体库文件\n *\n * @param fontFolder 字体文件目录\n */\n public static void initFontsFile(File fontFolder) {\n fontsMap.put(fontFolder.getName(), new FontsFileModel(fontFolder));\n }\n\n /**\n * geojson格式的加载行政区划边界数据。\n *\n * @param boundary 行政区划边界\n */\n public static void initBoundaryFile(File boundary) {\n try {\n GeoJSONReader reader = new GeoJSONReader(new FileInputStream(boundary));\n SimpleFeatureIterator features = reader.getFeatures().features();\n while (features.hasNext()) {\n SimpleFeature feature = features.next();\n\n administrativeDivision.put((int) feature.getAttribute(\"osm_id\"), feature);\n\n int adminLevel = feature.getAttribute(\"admin_level\") == null ? -1 : (int) feature.getAttribute(\"admin_level\");\n if (administrativeDivisionLevel.containsKey(adminLevel)) {\n List<SimpleFeature> simpleFeatures = administrativeDivisionLevel.get(adminLevel);\n simpleFeatures.add(feature);\n } else {\n ArrayList<SimpleFeature> value = new ArrayList<>();\n value.add(feature);\n administrativeDivisionLevel.put(adminLevel, value);\n }\n }\n features.close();\n packageModel();\n } catch (IOException e) {\n logger.error(\"Read OSM file failed:\" + boundary.getAbsolutePath());\n }\n }\n\n private static void packageModel() {\n administrativeDivision.values().forEach(feature -> {\n if (simpleAdminDivision == null) {\n simpleAdminDivision = initRootNode(feature);\n } else {\n Object parentsObj = feature.getAttribute(\"parents\");\n if (parentsObj != null) {\n String[] parents = parentsObj.toString().split(\",\");\n\n AdministrativeDivisionTmp tempNode = new AdministrativeDivisionTmp(feature, Integer.parseInt(parents[0]));\n\n for (int i = 0; i < parents.length; i++) {\n int parentId = Integer.parseInt(parents[i]);\n Optional<AdministrativeDivisionTmp> nodeOpt = findNode(simpleAdminDivision, parentId);\n if (nodeOpt.isPresent()) {\n AdministrativeDivisionTmp child = nodeOpt.get();\n //如果父节点已经在早期全路径时构造过了,则不需要再追加此单节点。\n if (!contains(child, (int) feature.getAttribute(\"osm_id\"))) {\n child.getChildren().add(tempNode);\n }\n break;\n } else {\n AdministrativeDivisionTmp tmp = new AdministrativeDivisionTmp(administrativeDivision.get(parentId), Integer.parseInt(parents[i + 1]));\n tmp.getChildren().add(tempNode);\n tempNode = tmp;\n }\n }\n }\n }\n });\n }\n\n private static boolean contains(AdministrativeDivisionTmp child, int parentId) {\n for (AdministrativeDivisionTmp item : child.getChildren()) {\n if (item.getId() == parentId) {\n return true;\n }\n }\n return false;\n }\n\n\n private static AdministrativeDivisionTmp initRootNode(SimpleFeature feature) {\n Object parents = feature.getAttribute(\"parents\");\n if (parents == null) {\n return new AdministrativeDivisionTmp(feature, -1);\n } else {\n String[] split = parents.toString().split(\",\");\n List<AdministrativeDivisionTmp> children = new ArrayList<>();\n AdministrativeDivisionTmp tmp = null;\n for (int i = 0; i < split.length; i++) {\n int osmId = Integer.parseInt(split[i]);\n if (i + 1 > split.length - 1) {\n tmp = new AdministrativeDivisionTmp(administrativeDivision.get(osmId), -1);\n tmp.setChildren(children);\n } else {\n tmp = new AdministrativeDivisionTmp(administrativeDivision.get(osmId), Integer.parseInt(split[i + 1]));\n tmp.setChildren(children);\n children = new ArrayList<>();\n children.add(tmp);\n }\n }\n return tmp;\n }\n }\n\n private static Optional<AdministrativeDivisionTmp> findNode(AdministrativeDivisionTmp tmp, int parentId) {\n if (tmp.getId() == parentId) {\n return Optional.of(tmp);\n }\n List<AdministrativeDivisionTmp> children = tmp.getChildren();\n for (AdministrativeDivisionTmp item : children) {\n if (item.getId() == parentId) {\n return Optional.of(item);\n } else {\n Optional<AdministrativeDivisionTmp> childOpt = findNode(item, parentId);\n if (childOpt.isPresent()) {\n return childOpt;\n }\n }\n }\n return Optional.empty();\n }\n\n\n /**\n * 通过文件名获取数据源\n *\n * @param fileName 数据库文件名称\n * @return 数据库数据源\n */\n public Optional<JdbcTemplate> getDataSource(String fileName) {\n if (StringUtils.hasLength(fileName)) {\n TilesFileModel model = tilesMap.get(fileName);\n return Optional.of(model.getJdbcTemplate());\n } else {\n return Optional.empty();\n }\n }\n\n\n /**\n * 返回瓦片数据库文件的元数据\n *\n * @param fileName 瓦片数据库文件名\n * @return 瓦片元数据\n */\n public Map<String, String> getTileMetaData(String fileName) {\n if (StringUtils.hasLength(fileName)) {\n TilesFileModel model = tilesMap.get(fileName);\n return model.getMetaDataMap();\n } else {\n return new HashMap<>();\n }\n }\n\n public MetaData getTpkMetaData(String fileName) {\n MetaData metaData = new MetaData();\n if (StringUtils.hasLength(fileName)) {\n TPKFile tpkFile = tpkFileMap.get(fileName);\n metaData.setBounds(tpkFile.getBounds().toString());\n metaData.setCrs(tpkFile.getBounds().getCoordinateReferenceSystem().getName().toString());\n metaData.setFormat(tpkFile.getImageFormat());\n metaData.setMaxzoom(tpkFile.getMaxZoomLevel());\n metaData.setMinzoom(tpkFile.getMinZoomLevel());\n }\n return metaData;\n }\n\n /**\n * 获取字符文件目录\n *\n * @param fontName 字体文件名\n * @return 字体文件目录\n */\n public Optional<FontsFileModel> getFontFolder(String fontName) {\n if (StringUtils.hasLength(fontName)) {\n FontsFileModel fontsFileModel = fontsMap.get(fontName);\n return Optional.of(fontsFileModel);\n } else {\n return Optional.empty();\n }\n }\n}" } ]
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Optional; import io.github.qmjy.mapbox.config.AppConfig; import io.github.qmjy.mapbox.model.FontsFileModel; import io.github.qmjy.mapbox.MapServerDataCenter; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.*;
2,808
/* * Copyright (c) 2023 QMJY. * * 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 io.github.qmjy.mapbox.controller; /** * 支持的字体访问API。 */ @RestController @RequestMapping("/api/fonts") @Tag(name = "Mapbox字体服务管理", description = "Mapbox离线服务接口能力") public class MapServerFontsController { private final Logger logger = LoggerFactory.getLogger(MapServerFontsController.class); @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired
/* * Copyright (c) 2023 QMJY. * * 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 io.github.qmjy.mapbox.controller; /** * 支持的字体访问API。 */ @RestController @RequestMapping("/api/fonts") @Tag(name = "Mapbox字体服务管理", description = "Mapbox离线服务接口能力") public class MapServerFontsController { private final Logger logger = LoggerFactory.getLogger(MapServerFontsController.class); @Autowired private MapServerDataCenter mapServerDataCenter; @Autowired
private AppConfig appConfig;
0
2023-10-09 03:18:52+00:00
4k
codegrits/CodeGRITS
src/main/java/trackers/EyeTracker.java
[ { "identifier": "RelativePathGetter", "path": "src/main/java/utils/RelativePathGetter.java", "snippet": "public class RelativePathGetter {\n /**\n * Get the relative path of a file compared to the project path. If the project path is not a prefix of the file path, the absolute path of the file is returned.\n *\n * @param absolutePath The absolute path of the file.\n * @param projectPath The absolute path of the project.\n * @return The relative path of the file compared to the project path.\n */\n public static String getRelativePath(String absolutePath, String projectPath) {\n if (absolutePath.length() > projectPath.length() && absolutePath.startsWith(projectPath)) {\n return absolutePath.substring(projectPath.length());\n }\n return absolutePath;\n }\n}" }, { "identifier": "XMLWriter", "path": "src/main/java/utils/XMLWriter.java", "snippet": "public class XMLWriter {\n /**\n * Write the formatted XML document to the XML file.\n *\n * @param document The XML document.\n * @param filePath The path of the XML file.\n */\n public static void writeToXML(Document document, String filePath) throws TransformerException {\n TransformerFactory transformerFactory = TransformerFactory.newInstance();\n Transformer transformer = transformerFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n DOMSource source = new DOMSource(document);\n StreamResult result = new StreamResult(new File(filePath));\n transformer.transform(source, result);\n }\n}" } ]
import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.event.VisibleAreaListener; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.w3c.dom.Document; import org.w3c.dom.Element; import utils.RelativePathGetter; import utils.XMLWriter; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.function.Consumer;
2,298
} /** * The listener for the visible area used for filtering the eye tracking data. */ VisibleAreaListener visibleAreaListener = e -> visibleArea = e.getNewRectangle(); /** * This method starts the eye tracking. * * @param project The project. * @throws IOException The exception. */ public void startTracking(Project project) throws IOException { isTracking = true; psiDocumentManager = PsiDocumentManager.getInstance(project); editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); visibleArea = editor.getScrollingModel().getVisibleArea(); } VirtualFile[] virtualFiles = FileEditorManager.getInstance(project).getSelectedFiles(); if (virtualFiles.length > 0) { filePath = virtualFiles[0].getPath(); } if (deviceIndex == 0) { setting.setAttribute("eye_tracker", "Mouse"); } else { setting.setAttribute("eye_tracker", "Tobii Pro Fusion"); } setting.setAttribute("sample_frequency", String.valueOf(sampleFrequency)); track(); } /** * This method stops the eye tracking. * * @throws TransformerException The exception. */ public void stopTracking() throws TransformerException { isTracking = false; pythonOutputThread.interrupt(); pythonProcess.destroy(); XMLWriter.writeToXML(eyeTracking, dataOutputPath + "/eye_tracking.xml"); } /** * This method pauses the eye tracking. The {@code isTracking} variable will be set to {@code false}. */ public void pauseTracking() { isTracking = false; } /** * This method resumes the eye tracking. The {@code isTracking} variable will be set to {@code true}. */ public void resumeTracking() { isTracking = true; } /** * This method processes the raw data message from the eye tracker. It will filter the data, map the data to the specific source code element, and perform the upward traversal in the AST. * * @param message The raw data. */ public void processRawData(String message) { if (!isTracking) return; Element gaze = getRawGazeElement(message); gazes.appendChild(gaze); String leftInfo = message.split("; ")[1]; String leftGazePointX = leftInfo.split(", ")[0]; String leftGazePointY = leftInfo.split(", ")[1]; String rightInfo = message.split("; ")[2]; String rightGazePointX = rightInfo.split(", ")[0]; String rightGazePointY = rightInfo.split(", ")[1]; if (leftGazePointX.equals("nan") || leftGazePointY.equals("nan") || rightGazePointX.equals("nan") || rightGazePointY.equals("nan")) { gaze.setAttribute("remark", "Fail | Invalid Gaze Point"); return; } if (editor == null) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int eyeX = (int) ((Double.parseDouble(leftGazePointX) + Double.parseDouble(rightGazePointX)) / 2 * screenWidth); int eyeY = (int) ((Double.parseDouble(leftGazePointY) + Double.parseDouble(rightGazePointY)) / 2 * screenHeight); int editorX, editorY; try { editorX = editor.getContentComponent().getLocationOnScreen().x; editorY = editor.getContentComponent().getLocationOnScreen().y; } catch (IllegalComponentStateException e) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int relativeX = eyeX - editorX; int relativeY = eyeY - editorY; if ((relativeX - visibleArea.x) < 0 || (relativeY - visibleArea.y) < 0 || (relativeX - visibleArea.x) > visibleArea.width || (relativeY - visibleArea.y) > visibleArea.height) { gaze.setAttribute("remark", "Fail | Out of Text Editor"); return; } Point relativePoint = new Point(relativeX, relativeY); EventQueue.invokeLater(new Thread(() -> { PsiFile psiFile = psiDocumentManager.getPsiFile(editor.getDocument()); LogicalPosition logicalPosition = editor.xyToLogicalPosition(relativePoint); if (psiFile != null) { int offset = editor.logicalPositionToOffset(logicalPosition); PsiElement psiElement = psiFile.findElementAt(offset); Element location = eyeTracking.createElement("location"); location.setAttribute("x", String.valueOf(eyeX)); location.setAttribute("y", String.valueOf(eyeY)); location.setAttribute("line", String.valueOf(logicalPosition.line)); location.setAttribute("column", String.valueOf(logicalPosition.column));
package trackers; /** * This class is the eye tracker. */ public class EyeTracker implements Disposable { String dataOutputPath = ""; /** * This variable indicates the sample frequency of the eye tracker. */ double sampleFrequency; PsiDocumentManager psiDocumentManager; public Editor editor; /** * This variable is the XML document for storing the eye tracking data. */ Document eyeTracking = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element root = eyeTracking.createElement("eye_tracking"); Element setting = eyeTracking.createElement("setting"); Element gazes = eyeTracking.createElement("gazes"); /** * This variable indicates whether the tracking is started. */ boolean isTracking = false; double screenWidth, screenHeight; String projectPath = "", filePath = ""; PsiElement lastElement = null; Rectangle visibleArea = null; Process pythonProcess; Thread pythonOutputThread; String pythonInterpreter = ""; String pythonScriptTobii; String pythonScriptMouse; int deviceIndex = 0; /** * This variable indicates whether the real-time data is transmitting. */ private static boolean isRealTimeDataTransmitting = false; /** * This variable is the handler for eye tracking data. */ private Consumer<Element> eyeTrackerDataHandler; /** * This is the default constructor. */ public EyeTracker() throws ParserConfigurationException { eyeTracking.appendChild(root); root.appendChild(setting); root.appendChild(gazes); Dimension size = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = size.getWidth(); screenHeight = size.getHeight(); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() { @Override public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) { editor = source.getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); } filePath = file.getPath(); visibleArea = editor.getScrollingModel().getVisibleArea(); } @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { editor = event.getManager().getSelectedTextEditor() != null ? event.getManager().getSelectedTextEditor() : editor; if (event.getNewFile() != null) { if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); } filePath = event.getNewFile().getPath(); visibleArea = editor.getScrollingModel().getVisibleArea(); } } }); } /** * This is the constructor for the eye tracker. * * @param pythonInterpreter The path of the Python interpreter. * @param sampleFrequency The sample frequency of the eye tracker. * @param isUsingMouse Whether the mouse is used as the eye tracker. */ public EyeTracker(String pythonInterpreter, double sampleFrequency, boolean isUsingMouse) throws ParserConfigurationException { // designed specifically for the real-time data API this(); // call default constructor if (isUsingMouse) { deviceIndex = 0; } else { deviceIndex = 1; } this.pythonInterpreter = pythonInterpreter; this.sampleFrequency = sampleFrequency; setPythonScriptMouse(); setPythonScriptTobii(); } /** * The listener for the visible area used for filtering the eye tracking data. */ VisibleAreaListener visibleAreaListener = e -> visibleArea = e.getNewRectangle(); /** * This method starts the eye tracking. * * @param project The project. * @throws IOException The exception. */ public void startTracking(Project project) throws IOException { isTracking = true; psiDocumentManager = PsiDocumentManager.getInstance(project); editor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (editor != null) { editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener); visibleArea = editor.getScrollingModel().getVisibleArea(); } VirtualFile[] virtualFiles = FileEditorManager.getInstance(project).getSelectedFiles(); if (virtualFiles.length > 0) { filePath = virtualFiles[0].getPath(); } if (deviceIndex == 0) { setting.setAttribute("eye_tracker", "Mouse"); } else { setting.setAttribute("eye_tracker", "Tobii Pro Fusion"); } setting.setAttribute("sample_frequency", String.valueOf(sampleFrequency)); track(); } /** * This method stops the eye tracking. * * @throws TransformerException The exception. */ public void stopTracking() throws TransformerException { isTracking = false; pythonOutputThread.interrupt(); pythonProcess.destroy(); XMLWriter.writeToXML(eyeTracking, dataOutputPath + "/eye_tracking.xml"); } /** * This method pauses the eye tracking. The {@code isTracking} variable will be set to {@code false}. */ public void pauseTracking() { isTracking = false; } /** * This method resumes the eye tracking. The {@code isTracking} variable will be set to {@code true}. */ public void resumeTracking() { isTracking = true; } /** * This method processes the raw data message from the eye tracker. It will filter the data, map the data to the specific source code element, and perform the upward traversal in the AST. * * @param message The raw data. */ public void processRawData(String message) { if (!isTracking) return; Element gaze = getRawGazeElement(message); gazes.appendChild(gaze); String leftInfo = message.split("; ")[1]; String leftGazePointX = leftInfo.split(", ")[0]; String leftGazePointY = leftInfo.split(", ")[1]; String rightInfo = message.split("; ")[2]; String rightGazePointX = rightInfo.split(", ")[0]; String rightGazePointY = rightInfo.split(", ")[1]; if (leftGazePointX.equals("nan") || leftGazePointY.equals("nan") || rightGazePointX.equals("nan") || rightGazePointY.equals("nan")) { gaze.setAttribute("remark", "Fail | Invalid Gaze Point"); return; } if (editor == null) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int eyeX = (int) ((Double.parseDouble(leftGazePointX) + Double.parseDouble(rightGazePointX)) / 2 * screenWidth); int eyeY = (int) ((Double.parseDouble(leftGazePointY) + Double.parseDouble(rightGazePointY)) / 2 * screenHeight); int editorX, editorY; try { editorX = editor.getContentComponent().getLocationOnScreen().x; editorY = editor.getContentComponent().getLocationOnScreen().y; } catch (IllegalComponentStateException e) { gaze.setAttribute("remark", "Fail | No Editor"); return; } int relativeX = eyeX - editorX; int relativeY = eyeY - editorY; if ((relativeX - visibleArea.x) < 0 || (relativeY - visibleArea.y) < 0 || (relativeX - visibleArea.x) > visibleArea.width || (relativeY - visibleArea.y) > visibleArea.height) { gaze.setAttribute("remark", "Fail | Out of Text Editor"); return; } Point relativePoint = new Point(relativeX, relativeY); EventQueue.invokeLater(new Thread(() -> { PsiFile psiFile = psiDocumentManager.getPsiFile(editor.getDocument()); LogicalPosition logicalPosition = editor.xyToLogicalPosition(relativePoint); if (psiFile != null) { int offset = editor.logicalPositionToOffset(logicalPosition); PsiElement psiElement = psiFile.findElementAt(offset); Element location = eyeTracking.createElement("location"); location.setAttribute("x", String.valueOf(eyeX)); location.setAttribute("y", String.valueOf(eyeY)); location.setAttribute("line", String.valueOf(logicalPosition.line)); location.setAttribute("column", String.valueOf(logicalPosition.column));
location.setAttribute("path", RelativePathGetter.getRelativePath(filePath, projectPath));
0
2023-10-12 15:40:39+00:00
4k
soya-miyoshi/amazon-s3-encryption-client-cli
src/test/java/com/github/soyamiyoshi/FileTransferTest.java
[ { "identifier": "CKmsKeyBasedClient", "path": "src/main/java/com/github/soyamiyoshi/client/kmskeybased/CKmsKeyBasedClient.java", "snippet": "public class CKmsKeyBasedClient extends AAutoClosableClient {\n\n protected String mKmsKeyID;\n\n public CKmsKeyBasedClient(final String kmsKeyId) {\n if (kmsKeyId == null) {\n throw new IllegalArgumentException(\"kmsKeyId must not be null\");\n }\n this.mKmsKeyID = kmsKeyId;\n super.setV3AsyncClient();\n }\n\n @Override\n protected S3AsyncClient createS3AsyncClient() {\n return S3AsyncEncryptionClient.builder()\n .kmsKeyId(this.mKmsKeyID)\n .build();\n }\n\n public void blockingUpload(\n final String bucketName,\n final String objectKey,\n final Path localFilePath) {\n\n AsyncRequestBody asyncRequestBody = null;\n try {\n asyncRequestBody = AsyncRequestBody.fromFile(localFilePath);\n } catch (UncheckedIOException e) {\n System.err.println(\"Error creating asyncRequestBody\");\n System.exit(1);\n }\n CompletableFuture<PutObjectResponse> futurePut =\n this.mV3AsyncClient.putObject(builder -> builder\n .bucket(bucketName)\n .key(objectKey)\n .build(), asyncRequestBody);\n futurePut.join();\n }\n\n public void blockingDownload(\n final String bucketName,\n final String objectKey) {\n\n CompletableFuture<GetObjectResponse> futureGet =\n mV3AsyncClient.getObject(builder -> builder\n .bucket(bucketName)\n .key(objectKey)\n .build(), AsyncResponseTransformer.toFile(Path.of(objectKey)));\n futureGet.join();\n }\n\n}" }, { "identifier": "CDelayedAuthenticationDownloader", "path": "src/main/java/com/github/soyamiyoshi/client/rawkeybased/download/CDelayedAuthenticationDownloader.java", "snippet": "public class CDelayedAuthenticationDownloader extends CBlockingDownloader {\n\n public CDelayedAuthenticationDownloader(CPrivateKeyProvider keyProvider) {\n super(keyProvider);\n }\n\n @Override\n protected S3AsyncClient createS3AsyncClient() {\n return S3AsyncEncryptionClient.builder()\n .rsaKeyPair(new PartialRsaKeyPair(super.mPrivateKeyProvider.getKey(), null))\n .enableDelayedAuthenticationMode(true)\n .build();\n }\n}" }, { "identifier": "CBlockingUploader", "path": "src/main/java/com/github/soyamiyoshi/client/rawkeybased/upload/CBlockingUploader.java", "snippet": "public class CBlockingUploader extends APubKeyBasedClient {\n\n public CBlockingUploader(CPublicKeyProvider keyProvider) {\n super(keyProvider);\n }\n\n // Invoked by the KeyBasedClient constructor to initialize mV3AsyncClient.\n @Override\n protected S3AsyncClient createS3AsyncClient() {\n return S3AsyncEncryptionClient.builder()\n .rsaKeyPair(new PartialRsaKeyPair(null, mPublicKeyProvider.getKey()))\n .build();\n }\n\n @Override\n public void upload(\n final String bucketName,\n final String objectKey,\n final Path localFilePath) {\n AsyncRequestBody asyncRequestBody = null;\n\n try {\n asyncRequestBody = AsyncRequestBody.fromFile(localFilePath);\n } catch (UncheckedIOException e) {\n System.err.println(\"Error creating asyncRequestBody\");\n System.exit(1);\n }\n CompletableFuture<PutObjectResponse> futurePut =\n this.mV3AsyncClient.putObject(builder -> builder\n .bucket(bucketName)\n .key(objectKey)\n .build(), asyncRequestBody);\n futurePut.join();\n }\n}" }, { "identifier": "CPrivateKeyProvider", "path": "src/main/java/com/github/soyamiyoshi/util/keyprovider/CPrivateKeyProvider.java", "snippet": "public class CPrivateKeyProvider implements IKeyProvider {\n\n private String privateKeyPath;\n\n public CPrivateKeyProvider(final String privateKeyPath) {\n this.privateKeyPath = privateKeyPath;\n }\n\n @Override\n public PrivateKey getKey() {\n try {\n byte[] decodedBytes =\n getPemContentBytes(this.privateKeyPath, \"-----BEGIN PRIVATE KEY-----\",\n \"-----END PRIVATE KEY-----\");\n PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodedBytes);\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePrivate(spec);\n } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {\n System.err.println(\"Error loading private key: \" + e.getMessage());\n return null;\n }\n }\n}" }, { "identifier": "CPublicKeyProvider", "path": "src/main/java/com/github/soyamiyoshi/util/keyprovider/CPublicKeyProvider.java", "snippet": "public class CPublicKeyProvider implements IKeyProvider {\n\n private String publicKeyPath;\n\n public CPublicKeyProvider(final String publicKeyString) {\n this.publicKeyPath = publicKeyString;\n }\n\n @Override\n public PublicKey getKey() {\n try {\n byte[] decodedBytes =\n getPemContentBytes(this.publicKeyPath, \"-----BEGIN PUBLIC KEY-----\",\n \"-----END PUBLIC KEY-----\");\n X509EncodedKeySpec spec = new X509EncodedKeySpec(decodedBytes);\n KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n return keyFactory.generatePublic(spec);\n } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {\n System.err.println(\"Error loading public key: \" + e.getMessage());\n System.exit(1);\n return null;\n }\n }\n\n}" }, { "identifier": "getEnvOrExit", "path": "src/test/java/com/github/soyamiyoshi/testutils/EnvLoader.java", "snippet": "public static String getEnvOrExit(String envVarName) {\n String value = System.getenv(envVarName);\n if (value == null || value.trim().isEmpty()) {\n System.err.println(\"Environment variable \" + envVarName + \" is not set.\");\n assert false;\n }\n return value;\n}" } ]
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import com.github.soyamiyoshi.client.kmskeybased.CKmsKeyBasedClient; import com.github.soyamiyoshi.client.rawkeybased.download.CDelayedAuthenticationDownloader; import com.github.soyamiyoshi.client.rawkeybased.upload.CBlockingUploader; import com.github.soyamiyoshi.util.keyprovider.CPrivateKeyProvider; import com.github.soyamiyoshi.util.keyprovider.CPublicKeyProvider; import static com.github.soyamiyoshi.testutils.EnvLoader.getEnvOrExit; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey;
2,006
package com.github.soyamiyoshi; public class FileTransferTest { private static String TEST_BUCKET_NAME; private static String TEST_OBJECT_KEY; private static Path TEST_LOCAL_FILE_PATH; private static KeyPair keyPair; @BeforeAll static void setUp() { TEST_BUCKET_NAME = getEnvOrExit("BUCKET_NAME"); TEST_OBJECT_KEY = getEnvOrExit("OBJECT_KEY"); TEST_LOCAL_FILE_PATH = Paths.get(getEnvOrExit("LOCAL_FILE_PATH")); try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // signal that test failed to initialize assert false; } } class CMockPublicKeyProvider extends CPublicKeyProvider { public CMockPublicKeyProvider() { super(null); } @Override public PublicKey getKey() { return FileTransferTest.keyPair.getPublic(); } } class CMockPrivateKeyProvider extends CPrivateKeyProvider { public CMockPrivateKeyProvider() { super(null); } @Override public PrivateKey getKey() { return FileTransferTest.keyPair.getPrivate(); } } @Test public void testFileTransfer() throws Exception { // Initialize the clients try (CBlockingUploader uploader = new CBlockingUploader((CPublicKeyProvider) new CMockPublicKeyProvider())) { uploader.upload(TEST_BUCKET_NAME, TEST_OBJECT_KEY, TEST_LOCAL_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } ; try (CDelayedAuthenticationDownloader downloader = new CDelayedAuthenticationDownloader(new CMockPrivateKeyProvider())) { downloader.download(TEST_BUCKET_NAME, TEST_OBJECT_KEY); } catch (Exception e) { e.printStackTrace(); } ; // Compare the contents byte[] originalContent = Files.readAllBytes(TEST_LOCAL_FILE_PATH); byte[] downloadedContent = Files.readAllBytes(Paths.get(TEST_OBJECT_KEY)); assertArrayEquals(originalContent, downloadedContent, "The contents of the uploaded and downloaded files should be the same."); } @Test public void testFileTransferKms() throws Exception {
package com.github.soyamiyoshi; public class FileTransferTest { private static String TEST_BUCKET_NAME; private static String TEST_OBJECT_KEY; private static Path TEST_LOCAL_FILE_PATH; private static KeyPair keyPair; @BeforeAll static void setUp() { TEST_BUCKET_NAME = getEnvOrExit("BUCKET_NAME"); TEST_OBJECT_KEY = getEnvOrExit("OBJECT_KEY"); TEST_LOCAL_FILE_PATH = Paths.get(getEnvOrExit("LOCAL_FILE_PATH")); try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); // signal that test failed to initialize assert false; } } class CMockPublicKeyProvider extends CPublicKeyProvider { public CMockPublicKeyProvider() { super(null); } @Override public PublicKey getKey() { return FileTransferTest.keyPair.getPublic(); } } class CMockPrivateKeyProvider extends CPrivateKeyProvider { public CMockPrivateKeyProvider() { super(null); } @Override public PrivateKey getKey() { return FileTransferTest.keyPair.getPrivate(); } } @Test public void testFileTransfer() throws Exception { // Initialize the clients try (CBlockingUploader uploader = new CBlockingUploader((CPublicKeyProvider) new CMockPublicKeyProvider())) { uploader.upload(TEST_BUCKET_NAME, TEST_OBJECT_KEY, TEST_LOCAL_FILE_PATH); } catch (Exception e) { e.printStackTrace(); } ; try (CDelayedAuthenticationDownloader downloader = new CDelayedAuthenticationDownloader(new CMockPrivateKeyProvider())) { downloader.download(TEST_BUCKET_NAME, TEST_OBJECT_KEY); } catch (Exception e) { e.printStackTrace(); } ; // Compare the contents byte[] originalContent = Files.readAllBytes(TEST_LOCAL_FILE_PATH); byte[] downloadedContent = Files.readAllBytes(Paths.get(TEST_OBJECT_KEY)); assertArrayEquals(originalContent, downloadedContent, "The contents of the uploaded and downloaded files should be the same."); } @Test public void testFileTransferKms() throws Exception {
try (CKmsKeyBasedClient client = new CKmsKeyBasedClient(getEnvOrExit("KMS_KEY_ID"))) {
0
2023-10-11 06:30:54+00:00
4k
Aywen1/reciteeasily
src/fr/nicolas/main/frames/AFrameEnd.java
[ { "identifier": "ATools", "path": "src/fr/nicolas/main/ATools.java", "snippet": "public class ATools {\n\n\tpublic static String[] matiereList = { \"Histoire\", \"Géographie\", \"Emc\", \"Phys-Chim\", \"Svt\", \"Maths\",\n\t\t\t\"Anglais\", \"Espagnol\" };\n\tpublic static ArrayList<String> elements;\n\tpublic static int nombrePartiesTotal;\n\tpublic static int nombrePartiesNow;\n\tprivate static ArrayList<ArrayList<String>> listFalseItems = new ArrayList<ArrayList<String>>();\n\tprivate static String categoryNow;\n\tprivate static int nombreRestart;\n\tpublic static String nameFiche;\n\tpublic static AFrameMenuNavig menuNavig;\n\n\tpublic static String clearText(String text) {\n\t\treturn (text.replace(\"[T]\", \"\").replace(\"[D]\", \"\").replace(\"[M]\", \"\").replace(\"[DA]\", \"\").replace(\"[P]\", \"\")\n\t\t\t\t.replace(\"[E]\", \"\").replace(\"[L]\", \"\").replace(\"[C]\", \"\").replace(\"[I]\", \"\"));\n\t}\n\n\tpublic static ArrayList<String> readFile(String matiere, String nameFiche) {\n\t\tString line;\n\t\tArrayList<String> newElements = new ArrayList<String>();\n\t\ttry {\n\t\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\t\tnew FileReader(\"ReciteEasily/Fiches/\" + matiere + \"/\" + nameFiche + \"/\" + nameFiche + \".txt\"));\n\t\t\ttry {\n\t\t\t\twhile ((line = bufferedReader.readLine()) != null) {\n\t\t\t\t\tnewElements.add(line);\n\t\t\t\t}\n\t\t\t\tbufferedReader.close();\n\t\t\t} catch (IOException e) {\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t}\n\n\t\treturn newElements;\n\t}\n\n\tpublic static void nextFrame(Point loc) {\n\t\tnextFrameSuite(loc);\n\t}\n\n\tpublic static void nextFrame(Point loc, ArrayList<String> falseItems) {\n\t\tlistFalseItems.add(falseItems);\n\n\t\tnextFrameSuite(loc);\n\t}\n\n\tprivate static void nextFrameSuite(Point loc) {\n\t\tif (elements.size() > 0) {\n\n\t\t\tint i = 0;\n\n\t\t\tnombrePartiesNow = 0;\n\t\t\twhile (elements.get(i) != null) {\n\t\t\t\tif (elements.get(i).startsWith(\"[C]\") || elements.get(i).startsWith(\"[L]\")\n\t\t\t\t\t\t|| elements.get(i).startsWith(\"[I]\")) {\n\t\t\t\t\tnombrePartiesNow++;\n\t\t\t\t}\n\t\t\t\tif (i == elements.size() - 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[C]\")) {\n\t\t\t\tArrayList<String> items = new ArrayList<String>();\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\n\t\t\t\ti = 0;\n\t\t\t\twhile (elements.get(i) != null) {\n\t\t\t\t\tif (elements.get(i).startsWith(\"[C]\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (elements.get(i).startsWith(\"[L]\")) {\n\t\t\t\t\t\titems.add(clearText(elements.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\tif (i == elements.size() - 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tcategoryNow = name;\n\n\t\t\t\tnew AFrameCategory(loc, name, items);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[L]\")) {\n\t\t\t\tArrayList<String> items = new ArrayList<String>();\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\n\t\t\t\twhile (elements.size() > 0) {\n\t\t\t\t\tif (elements.get(0).startsWith(\"[E]\")) {\n\t\t\t\t\t\titems.add(clearText(elements.get(0)));\n\t\t\t\t\t\telements.remove(0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnew AFrameListe(loc, name, categoryNow, items);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[I]\")) {\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\t\t\t\tnew AFrameImage(loc, name);\n\t\t\t}\n\n\t\t} else {\n\t\t\tif (listFalseItems.size() > 0) {\n\t\t\t\tString name = listFalseItems.get(0).get(0);\n\t\t\t\tlistFalseItems.get(0).remove(0);\n\t\t\t\tString category = listFalseItems.get(0).get(0);\n\t\t\t\tlistFalseItems.get(0).remove(0);\n\t\t\t\tnew AFrameListe(loc, \"[x] \" + name, category, listFalseItems.get(0));\n\t\t\t\tlistFalseItems.remove(0);\n\t\t\t\tnombreRestart++;\n\t\t\t} else {\n\t\t\t\tnew AFrameEnd(loc, nombreRestart);\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "ABackground", "path": "src/fr/nicolas/main/components/ABackground.java", "snippet": "public class ABackground extends JPanel {\n\n\tprivate Image bg;\n\tprivate boolean color = false;\n\n\tpublic enum ABgType {\n\t\tNewFiche, Summary, Color, End\n\t}\n\n\tpublic ABackground() {\n\t\tthis.setLayout(null);\n\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgDefault.png\")).getImage();\n\t}\n\n\tpublic ABackground(ABgType type) {\n\t\tthis.setLayout(null);\n\t\tif (type == ABgType.NewFiche) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgNewFiche.png\")).getImage();\n\t\t} else if (type == ABgType.Summary) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgSummary.png\")).getImage();\n\t\t} else if (type == ABgType.Color) {\n\t\t\tcolor = true;\n\t\t} else if (type == ABgType.End) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/imgEnd.png\")).getImage();\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tif (!color) {\n\t\t\tg.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\t} else {\n\t\t\tg.setColor(new Color(22, 22, 22));\n\t\t\tg.fillRect(0, 0, this.getWidth(), this.getHeight());\n\t\t\tg.setColor(Color.WHITE);\n\t\t\tg.drawLine(0, 0, 0, this.getHeight());\n\t\t}\n\t}\n\n}" }, { "identifier": "AButtonImg", "path": "src/fr/nicolas/main/components/AButtonImg.java", "snippet": "public class AButtonImg extends JButton {\n\n\tprivate Image img;\n\n\tpublic AButtonImg(String name) {\n\t\tthis.setFocusPainted(false);\n\t\tthis.setBorderPainted(false);\n\t\tthis.setContentAreaFilled(false);\n\n\t\tchangeType(name);\n\t}\n\n\tpublic AButtonImg(String path, String name) {\n\t\tthis.setFocusPainted(false);\n\t\tthis.setBorderPainted(false);\n\t\tthis.setContentAreaFilled(false);\n\n\t\ttry {\n\t\t\timg = ImageIO.read(new File(path + \"/\" + name));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tsetSize(new Dimension(img.getWidth(null), img.getHeight(null)));\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);\n\t}\n\n\tpublic void changeType(String name) {\n\t\timg = new ImageIcon(getClass().getResource(\"/img/button\" + name + \".png\")).getImage();\n\n\t\trepaint();\n\t}\n\n\tpublic Image getImg() {\n\t\treturn img;\n\t}\n\n}" }, { "identifier": "ALabel", "path": "src/fr/nicolas/main/components/ALabel.java", "snippet": "public class ALabel extends JLabel {\n\n\tpublic enum ALabelType {\n\t\tBold, Italic\n\t}\n\n\tpublic ALabel(String text, int size) {\n\t\tsuper(text);\n\t\tsetForeground(Color.WHITE);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, size));\n\t}\n\n\tpublic ALabel(String text, int size, ALabelType type) {\n\t\tsuper(text);\n\t\tsetForeground(Color.WHITE);\n\t\tif (type == ALabelType.Bold) {\n\t\t\tsetFont(new Font(\"Calibri\", Font.BOLD, size));\n\t\t} else if (type == ALabelType.Italic) {\n\t\t\tsetFont(new Font(\"Calibri\", Font.ITALIC, size));\n\t\t}\n\t}\n\n\tpublic void setText(String text, int size) {\n\t\tsetText(text);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, size));\n\t}\n\n}" }, { "identifier": "ABgType", "path": "src/fr/nicolas/main/components/ABackground.java", "snippet": "public enum ABgType {\n\tNewFiche, Summary, Color, End\n}" }, { "identifier": "APanelTop", "path": "src/fr/nicolas/main/panel/APanelTop.java", "snippet": "public class APanelTop extends JPanel {\n\n\tprivate ALabel labelTitle = new ALabel(\"ReciteEasily\", 50);\n\tprivate ALabel labelVersion = new ALabel(\"v\" + Main.version, 20);\n\n\tpublic APanelTop() {\n\t\tinit();\n\t}\n\n\tpublic APanelTop(String text) {\n\t\tlabelTitle.setText(text, 35);\n\t\tlabelVersion.setText(\"\");\n\n\t\tinit();\n\t}\n\n\tprivate void init() {\n\t\tthis.setLayout(null);\n\n\t\tadd(labelTitle);\n\t\tadd(labelVersion);\n\n\t\tlabelTitle.setBounds(35, 20, 1000, 40);\n\t\tlabelVersion.setBounds(280, 40, 1000, 40);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\n\t}\n}" } ]
import java.awt.BorderLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import fr.nicolas.main.ATools; import fr.nicolas.main.components.ABackground; import fr.nicolas.main.components.AButtonImg; import fr.nicolas.main.components.ALabel; import fr.nicolas.main.components.ABackground.ABgType; import fr.nicolas.main.panel.APanelTop;
2,374
package fr.nicolas.main.frames; public class AFrameEnd extends JFrame { private JPanel base = new JPanel();
package fr.nicolas.main.frames; public class AFrameEnd extends JFrame { private JPanel base = new JPanel();
private APanelTop panelTop;
5
2023-10-13 13:17:51+00:00
4k
rgrosa/comes-e-bebes
src/main/java/br/com/project/domain/service/imp/AcquisitionServiceImpl.java
[ { "identifier": "AcquisitionEntity", "path": "src/main/java/br/com/project/domain/entity/AcquisitionEntity.java", "snippet": "@Entity\n@Table(name = \"ACQUISITION\")\npublic class AcquisitionEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"CLIENT_ID\")\n private Long clientId;\n @Column(name = \"PRICE\")\n private Double price;\n @Column(name = \"DESCRIPTION\")\n private String description;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\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 Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\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 LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n\n public Long getClientId() {\n return clientId;\n }\n\n public void setClientId(Long clientId) {\n this.clientId = clientId;\n }\n}" }, { "identifier": "AdditionalItemRelEntity", "path": "src/main/java/br/com/project/domain/entity/AdditionalItemRelEntity.java", "snippet": "@Entity\n@Table(name = \"ADDITIONAL_ITEM_REL\")\npublic class AdditionalItemRelEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"ADDITIONAL_ITEM_ID\")\n private Long additionalItemId;\n @Column(name = \"ITEM_ACQUISITION_REL_ID\")\n private Long itemAcquisitionRelId;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\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 Long getAdditionalItemId() {\n return additionalItemId;\n }\n\n public void setAdditionalItemId(Long additionalItemId) {\n this.additionalItemId = additionalItemId;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n\n public Long getItemAcquisitionRelId() {\n return itemAcquisitionRelId;\n }\n\n public void setItemAcquisitionRelId(Long itemAcquisitionRelId) {\n this.itemAcquisitionRelId = itemAcquisitionRelId;\n }\n}" }, { "identifier": "ItemAcquisitionRelEntity", "path": "src/main/java/br/com/project/domain/entity/ItemAcquisitionRelEntity.java", "snippet": "@Entity\n@Table(name = \"ITEM_ACQUISITION_REL\")\npublic class ItemAcquisitionRelEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"ITEM_ID\")\n private Long itemId;\n @Column(name = \"ACQUISITION_ID\")\n private Long acquisitionId;\n @Column(name = \"DESCRIPTION\")\n private String description;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\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 Long getItemId() {\n return itemId;\n }\n\n public void setItemId(Long itemId) {\n this.itemId = itemId;\n }\n\n public Long getAcquisitionId() {\n return acquisitionId;\n }\n\n public void setAcquisitionId(Long acquisitionId) {\n this.acquisitionId = acquisitionId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n}" }, { "identifier": "ItemEntity", "path": "src/main/java/br/com/project/domain/entity/ItemEntity.java", "snippet": "@Entity\n@Table(name = \"ITEM\")\npublic class ItemEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"ITEM_NAME\")\n private String itemName;\n @Column(name = \"DESCRIPTION\")\n private String description;\n @Column(name = \"PRICE\")\n private Double price;\n @Column(name = \"ITEM_IMAGE\")\n private String itemImage;\n @Column(name = \"STATUS\")\n private boolean status;\n @Column(name = \"RESTAURANT_ID\")\n private Long restaurantId;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\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 getItemName() {\n return itemName;\n }\n\n public void setItemName(String itemName) {\n this.itemName = itemName;\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 Double getPrice() {\n return price;\n }\n\n public void setPrice(Double price) {\n this.price = price;\n }\n\n public boolean isStatus() {\n return status;\n }\n\n public void setStatus(boolean status) {\n this.status = status;\n }\n\n public Long getRestaurantId() {\n return restaurantId;\n }\n\n public void setRestaurantId(Long restaurantId) {\n this.restaurantId = restaurantId;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n\n public String getItemImage() {\n return itemImage;\n }\n\n public void setItemImage(String itemImage) {\n this.itemImage = itemImage;\n }\n}" }, { "identifier": "AcquisitionService", "path": "src/main/java/br/com/project/domain/service/AcquisitionService.java", "snippet": "public interface AcquisitionService {\n\n\n ItemAcquisitionReturnDTO postAcquisition(AcquisitionDTO acquisitionDTO);\n\n List<ItemAcquisitionReturnDTO> getAcquisitionHistory(Long userId);\n}" } ]
import br.com.project.domain.dto.*; import br.com.project.domain.entity.AcquisitionEntity; import br.com.project.domain.entity.AdditionalItemRelEntity; import br.com.project.domain.entity.ItemAcquisitionRelEntity; import br.com.project.domain.entity.ItemEntity; import br.com.project.domain.repository.*; import br.com.project.domain.service.AcquisitionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List;
2,293
package br.com.project.domain.service.imp; @Service public class AcquisitionServiceImpl implements AcquisitionService { @Autowired ItemRepository itemRepository; @Autowired AdditionalItemRepository additionalItemRepository; @Autowired AcquisitionRepository acquisitionRepository; @Autowired ItemAcquisitionRelRepository itemAcquisitionRelRepository; @Autowired AdditionalItemRelRepository additionalItemRelRepository; @Override public ItemAcquisitionReturnDTO postAcquisition(AcquisitionDTO acquisition) { Double totalPrice = 0.0;
package br.com.project.domain.service.imp; @Service public class AcquisitionServiceImpl implements AcquisitionService { @Autowired ItemRepository itemRepository; @Autowired AdditionalItemRepository additionalItemRepository; @Autowired AcquisitionRepository acquisitionRepository; @Autowired ItemAcquisitionRelRepository itemAcquisitionRelRepository; @Autowired AdditionalItemRelRepository additionalItemRelRepository; @Override public ItemAcquisitionReturnDTO postAcquisition(AcquisitionDTO acquisition) { Double totalPrice = 0.0;
AcquisitionEntity acquisitionEntity = new AcquisitionEntity();
0
2023-10-10 23:22:15+00:00
4k
Stachelbeere1248/zombies-utils
src/main/java/com/github/stachelbeere1248/zombiesutils/handlers/ChatHandler.java
[ { "identifier": "Difficulty", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/game/Difficulty.java", "snippet": "public enum Difficulty {\n NORMAL, HARD, RIP\n}" }, { "identifier": "GameMode", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/game/GameMode.java", "snippet": "public class GameMode {\n private final Map map;\n private Difficulty difficulty;\n\n public GameMode(@NotNull Map map) {\n this.map = map;\n this.difficulty = Difficulty.NORMAL;\n }\n\n public GameMode(@NotNull Map map, @NotNull Difficulty difficulty) {\n this.map = map;\n this.difficulty = difficulty;\n }\n\n public Map getMap() {\n return map;\n }\n\n public Difficulty getDifficulty() {\n return difficulty;\n }\n\n public void changeDifficulty(@NotNull Difficulty difficulty) {\n switch (map) {\n case DEAD_END:\n case BAD_BLOOD:\n this.difficulty = difficulty;\n break;\n case ALIEN_ARCADIUM:\n throw new RuntimeException(\"Achievement Get: Alien Arcadium Hard/RIP\" + Map.ALIEN_ARCADIUM);\n }\n }\n\n public boolean is(Map map, Difficulty difficulty) {\n return this.getDifficulty() == difficulty && this.getMap() == map;\n }\n}" }, { "identifier": "Timer", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/timer/Timer.java", "snippet": "public class Timer {\n\n public static Timer instance;\n private final GameMode gameMode;\n private final String serverNumber;\n private final GameFile gameFile;\n public Category category;\n private long savedTotalWorldTime;\n private int passedRoundsTickSum = 0;\n private boolean pbTracking = false;\n private int round;\n private boolean r1Corrected = false;\n\n /**\n * @param serverNumber The game's server the timer should be bound to.\n * @param map The map the timer should be started for.\n * @param round If available, round to begin splitting.\n */\n public Timer(@NotNull String serverNumber, @NotNull Map map, byte round) throws TimerException.ServerNumberException {\n this.savedTotalWorldTime = getCurrentTotalWorldTime();\n if (!serverNumber.trim().isEmpty()) this.serverNumber = serverNumber.trim();\n else throw new Timer.TimerException.ServerNumberException();\n\n this.category = new Category();\n this.gameFile = new GameFile(serverNumber.trim(), map);\n\n this.gameMode = new GameMode(map);\n this.round = round;\n if (ZombiesUtilsConfig.isSlaToggled()) SLA.instance = new SLA(map);\n\n MinecraftForge.EVENT_BUS.register(new Round1Correction());\n }\n\n public static Optional<Timer> getInstance() {\n return Optional.ofNullable(instance);\n }\n\n /**\n * Call to invalidate {@link #instance} to trigger the garbage collector\n */\n public static void dropInstances() {\n instance = null;\n }\n\n /**\n * The main splitting function.\n * Cancels on the second occurring sound-effect, important for {@link RecordManager} to not override values incorrectly.\n *\n * @param passedRound The round that has been passed.\n */\n public void split(byte passedRound) {\n final int gameTime = gameTime();\n final short roundTime = (short) (gameTime - passedRoundsTickSum);\n\n if ((round == passedRound) || (passedRound == 0) || (roundTime < 100)) {\n ZombiesUtils.getInstance().getLogger().debug(\"SPLIT CANCELLED\");\n return;\n }\n\n try {\n record(passedRound, roundTime, gameTime);\n } catch (Exception e) {\n ZombiesUtils.getInstance().getLogger().error(ExceptionUtils.getStackTrace(e));\n Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(\"Error saving splits\"));\n }\n\n passedRoundsTickSum = gameTime;\n round = passedRound;\n }\n\n public void correctRn() {\n if (r1Corrected) return;\n savedTotalWorldTime = getCurrentTotalWorldTime() - 200L;\n r1Corrected = true;\n }\n\n private void record(byte passedRound, short roundTime, int gameTime) {\n if (passedRound == (byte) 1) pbTracking = true;\n\n try {\n RecordManager.compareSegment(passedRound, roundTime, category);\n if (pbTracking) RecordManager.compareBest(passedRound, gameTime, category);\n\n gameFile.setSegment(passedRound, roundTime);\n } catch (IndexOutOfBoundsException exception) {\n Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(\n String.format(\"Split not recorded. (invalid round parsed from scoreboard: %s)\", passedRound)\n ));\n }\n }\n\n private long getCurrentTotalWorldTime() {\n if (Minecraft.getMinecraft() == null) return 0;\n if (Minecraft.getMinecraft().theWorld == null) return 0;\n return Minecraft.getMinecraft().theWorld.getTotalWorldTime();\n }\n\n public int gameTime() {\n return (int) (getCurrentTotalWorldTime() - savedTotalWorldTime);\n }\n\n public short roundTime() {\n return (short) (gameTime() - passedRoundsTickSum);\n }\n\n /**\n * @param serverNumber Servernumber to be compared\n * @return false, if and only if input exists and is unequal to {@link #serverNumber}\n */\n public boolean equalsServerOrNull(String serverNumber) {\n return (serverNumber == null || serverNumber.equals(this.serverNumber) || serverNumber.isEmpty());\n }\n\n public void setCategory(Category category) {\n this.category = category;\n }\n\n public byte getRound() {\n return (byte) (round + 1);\n }\n\n public GameMode getGameMode() {\n return gameMode;\n }\n\n public static abstract class TimerException extends Exception {\n\n public static class MapException extends TimerException {\n }\n\n public static class ServerNumberException extends TimerException {\n }\n }\n}" }, { "identifier": "LanguageSupport", "path": "src/main/java/com/github/stachelbeere1248/zombiesutils/utils/LanguageSupport.java", "snippet": "@SuppressWarnings(\"SpellCheckingInspection\")\npublic class LanguageSupport {\n private static final String[] LANGUAGEs = {\n \"EN\",\n \"FR\",\n \"DE\"\n };\n\n public static boolean isLoss(@NotNull String input) {\n final String[] words = {\n \"§cGame Over!\",\n \"§cPartie terminée!\",\n \"§cDas Spiel ist vorbei!\"\n };\n return Arrays.asList(words).contains(input);\n }\n\n public static boolean isWin(@NotNull String input) {\n final String[] words = {\n \"§aYou Win!\",\n \"§aVous avez gagné!\",\n \"§aDu gewinnst!\"\n };\n return Arrays.asList(words).contains(input);\n }\n\n public static boolean containsHard(@NotNull String input) {\n final String[] words = {\n \"Hard Difficulty\",\n \"Difficulté Hard\",\n \"Hard Schwierigkeitsgrad\",\n \"困难\",\n \"困難\"\n };\n return Arrays.stream(words).anyMatch(input::contains);\n }\n\n public static boolean containsRIP(@NotNull String input) {\n final String[] words = {\n \"RIP Difficulty\",\n \"Difficulté RIP\",\n \"RIP Schwierigkeitsgrad\",\n \"安息\"\n };\n return Arrays.stream(words).anyMatch(input::contains);\n }\n\n public static @NotNull Pattern roundPattern(@NotNull String language) {\n switch (language) {\n case \"EN\":\n return Pattern.compile(\"Round ([0-9]{1,3})\");\n case \"FR\":\n return Pattern.compile(\"Manche ([0-9]{1,3})\");\n case \"DE\":\n return Pattern.compile(\"Runde ([0-9]{1,3})\");\n default:\n throw new IllegalStateException(\"Unexpected value: \" + language);\n }\n }\n\n public static @NotNull Pattern mapPattern(@NotNull String language) {\n switch (language) {\n case \"EN\":\n return Pattern.compile(\"Map:.*(Dead End|Bad Blood|Alien Arcadium)\");\n case \"FR\":\n return Pattern.compile(\"Carte:.*(Dead End|Bad Blood|Alien Arcadium)\");\n case \"DE\":\n return Pattern.compile(\"Karte:.*(Dead End|Bad Blood|Alien Arcadium)\");\n default:\n throw new IllegalStateException(\"Unexpected value: \" + language);\n }\n }\n\n public static String[] getLanguages() {\n return LANGUAGEs;\n }\n}" } ]
import com.github.stachelbeere1248.zombiesutils.game.Difficulty; import com.github.stachelbeere1248.zombiesutils.game.GameMode; import com.github.stachelbeere1248.zombiesutils.timer.Timer; import com.github.stachelbeere1248.zombiesutils.utils.LanguageSupport; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.jetbrains.annotations.NotNull; import java.util.regex.Pattern;
2,342
package com.github.stachelbeere1248.zombiesutils.handlers; public class ChatHandler { private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("§[0-9A-FK-ORZ]", Pattern.CASE_INSENSITIVE); public ChatHandler() { } @SubscribeEvent public void difficultyChange(@NotNull ClientChatReceivedEvent event) { if (!Timer.getInstance().isPresent()) return; String message = STRIP_COLOR_PATTERN.matcher(event.message.getUnformattedText()).replaceAll("").trim(); GameMode gameMode = Timer.getInstance().get().getGameMode(); if (message.contains(":")) return;
package com.github.stachelbeere1248.zombiesutils.handlers; public class ChatHandler { private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("§[0-9A-FK-ORZ]", Pattern.CASE_INSENSITIVE); public ChatHandler() { } @SubscribeEvent public void difficultyChange(@NotNull ClientChatReceivedEvent event) { if (!Timer.getInstance().isPresent()) return; String message = STRIP_COLOR_PATTERN.matcher(event.message.getUnformattedText()).replaceAll("").trim(); GameMode gameMode = Timer.getInstance().get().getGameMode(); if (message.contains(":")) return;
if (LanguageSupport.containsHard(message)) {
3
2023-10-11 01:30:28+00:00
4k
gustavofg1pontes/Tickets-API
application/src/main/java/br/com/ifsp/tickets/api/app/guest/create/DefaultCreateGuestUseCase.java
[ { "identifier": "Event", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/entity/Event.java", "snippet": "@Getter\n@Setter\npublic class Event extends AggregateRoot<EventID> {\n private String name;\n private LocalDateTime dateTime;\n private Integer maxTickets;\n private Integer soldTickets;\n\n public Event(EventID eventID, String name, LocalDateTime dateTime, Integer maxQuantGuests, Integer soldTickets) {\n super(eventID);\n this.name = name;\n this.dateTime = dateTime;\n this.maxTickets = maxQuantGuests;\n this.soldTickets = soldTickets;\n }\n\n public static Event with(EventID eventID, String name, LocalDateTime dateTime, Integer maxQuantGuests, Integer soldTickets) {\n return new Event(eventID, name, dateTime, maxQuantGuests, soldTickets);\n }\n\n public void update(String name, LocalDateTime localDateTime, Integer maxQuantGuests, Integer soldTickets) {\n this.name = name;\n this.dateTime = localDateTime;\n this.maxTickets = maxQuantGuests;\n this.soldTickets = soldTickets;\n }\n\n public void addTicketSold() {\n this.soldTickets++;\n }\n\n public void removeTicketSold() {\n this.soldTickets--;\n }\n\n @Override\n public void validate(ValidationHandler handler) {\n new EventValidator(this, handler).validate();\n }\n}" }, { "identifier": "EventID", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/entity/EventID.java", "snippet": "public class EventID extends Identifier<UUID> {\n\n private final UUID uuid;\n\n public EventID(final UUID uuid) {\n this.uuid = uuid;\n }\n\n public static EventID from(final String anId) {\n if (anId == null || anId.isBlank()) return null;\n return new EventID(UUIDUtils.getFromString(anId));\n }\n\n public static EventID unique() {\n return EventID.from(UUIDUtils.uuid());\n }\n\n @Override\n public UUID getValue() {\n return this.uuid;\n }\n}" }, { "identifier": "EventGateway", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/gateway/EventGateway.java", "snippet": "public interface EventGateway {\n Event create(final Event aEvent);\n\n Optional<Event> findById(final EventID EventID);\n\n boolean existsById(final EventID EventID);\n\n Pagination<Event> findAll(final SearchQuery searchQuery);\n\n Event update(final Event Event);\n\n void deleteById(final EventID EventID);\n}" }, { "identifier": "Guest", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/guest/entity/Guest.java", "snippet": "@Getter\npublic class Guest extends AggregateRoot<GuestID> {\n\n private String name;\n private EventID eventId;\n private Integer age;\n private Integer enterId;\n private String document;\n private boolean blocked;\n private String phoneNumber;\n private String email;\n private Profile profile;\n private boolean entered;\n private boolean left;\n\n public Guest(GuestID guestID, String name, EventID eventId, Integer enterId, Integer age, String document, boolean blocked, boolean entered, boolean left, String phoneNumber, String email, Profile profile) {\n super(guestID);\n this.name = name;\n this.eventId = eventId;\n this.enterId = enterId;\n this.age = age;\n this.document = document;\n this.blocked = blocked;\n this.phoneNumber = phoneNumber;\n this.email = email;\n this.profile = profile;\n this.entered = entered;\n this.left = left;\n }\n\n public static Guest with(GuestID guestID, EventID eventId, Integer enterId, String name, Integer age, String document, boolean blocked, boolean entered, boolean left, String phoneNumber, String email, Profile profile) {\n return new Guest(guestID, name, eventId, enterId, age, document, blocked, entered, left, phoneNumber, email, profile);\n }\n\n public void update(String name, Integer age, String document, String phoneNumber, String email, Profile profile) {\n this.name = name;\n this.age = age;\n this.document = document;\n this.phoneNumber = phoneNumber;\n this.email = email;\n this.profile = profile;\n }\n\n public void toggleBlocked(){\n this.blocked = !this.blocked;\n }\n public void toggleEnter(){\n this.entered = !this.entered;\n }\n public void toggleLeft(){\n this.left = !this.left;\n }\n\n @Override\n public void validate(ValidationHandler handler) {\n new GuestValidator(this, handler).validate();\n }\n\n public Profile getProfile() {\n return profile;\n }\n}" }, { "identifier": "GuestID", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/guest/entity/GuestID.java", "snippet": "public class GuestID extends Identifier<UUID> {\n private final UUID uuid;\n\n public GuestID(final UUID uuid){\n this.uuid = uuid;\n }\n\n public static GuestID from(final String anId) {\n if (anId == null || anId.isBlank()) return null;\n return new GuestID(UUIDUtils.getFromString(anId));\n }\n\n public static GuestID unique() {\n return GuestID.from(UUIDUtils.uuid());\n }\n\n @Override\n public UUID getValue() {\n return this.uuid;\n }\n}" }, { "identifier": "Profile", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/guest/entity/profile/Profile.java", "snippet": "public enum Profile {\n STUDENT(0),\n EMPLOYEE(1),\n EX_STUDENT(2),\n EXTERNAL_PUBLIC(3);\n\n private Integer id;\n\n Profile(Integer id){\n this.id = id;\n }\n\n public Integer getId() {\n return id;\n }\n\n public static Profile get(final Integer id) {\n for(Profile e : values()){\n if(e.id.equals(id)){\n return e;\n }\n }\n throw NotFoundException.with(new Error(\"unable to find enum\"));\n }}" }, { "identifier": "GuestGateway", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/guest/gateway/GuestGateway.java", "snippet": "public interface GuestGateway {\n Guest create(final Guest aGuest);\n\n Optional<Guest> findById(final GuestID aGuestID);\n Optional<Guest> findByEventIdAndName(EventID eventID, String name);\n\n boolean existsById(final GuestID aGuestID);\n\n Pagination<Guest> findAll(final SearchQuery searchQuery);\n\n Guest update(final Guest aGuest);\n\n void deleteById(final GuestID aGuestID);\n void deleteAllByEvent(final EventID eventID);\n void deleteByEventIdAndName(UUID eventId, String name);\n\n Set<Guest> findAllByEventId(final EventID eventID);\n\n}" }, { "identifier": "InternalErrorException", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/shared/exceptions/InternalErrorException.java", "snippet": "public class InternalErrorException extends NoStacktraceException {\n\n protected InternalErrorException(final String aMessage, final Throwable t) {\n super(aMessage, t);\n }\n\n public static InternalErrorException with(final String message, final Throwable t) {\n return new InternalErrorException(message, t);\n }\n}" }, { "identifier": "NotFoundException", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/shared/exceptions/NotFoundException.java", "snippet": "public class NotFoundException extends DomainException {\n\n protected NotFoundException(final String aMessage, final List<Error> anErrors) {\n super(aMessage, anErrors);\n }\n\n public static NotFoundException with(\n final Class<? extends AggregateRoot<?>> anAggregate,\n final Identifier id\n ) {\n final var anError = \"%s with ID %s was not found\".formatted(\n anAggregate.getSimpleName(),\n id.getValue()\n );\n return new NotFoundException(anError, Collections.emptyList());\n }\n\n public static NotFoundException with(\n final Class<? extends ValueObject> aValueObject,\n final String id\n ) {\n final var anError = \"%s with ID %s was not found\".formatted(\n aValueObject.getSimpleName(),\n id\n );\n return new NotFoundException(anError, Collections.emptyList());\n }\n\n public static NotFoundException with(final Error error) {\n return new NotFoundException(error.message(), List.of(error));\n }\n}" }, { "identifier": "NotificationException", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/shared/exceptions/NotificationException.java", "snippet": "public class NotificationException extends DomainException {\n\n public NotificationException(final String aMessage, final Notification notification) {\n super(aMessage, notification.getErrors());\n }\n}" }, { "identifier": "Notification", "path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/shared/validation/handler/Notification.java", "snippet": "public class Notification implements ValidationHandler {\n private final List<Error> errors;\n\n private Notification(final List<Error> errors) {\n this.errors = errors;\n }\n\n public static Notification create() {\n return new Notification(new ArrayList<>());\n }\n\n public static Notification create(final Throwable t) {\n return create(new Error(t.getMessage()));\n }\n\n public static Notification create(final Error anError) {\n return new Notification(new ArrayList<>()).append(anError);\n }\n\n @Override\n public Notification append(final Error anError) {\n this.errors.add(anError);\n return this;\n }\n\n @Override\n public Notification append(final ValidationHandler anHandler) {\n this.errors.addAll(anHandler.getErrors());\n return this;\n }\n\n @Override\n public <T> T validate(final Validation<T> aValidation) {\n try {\n return aValidation.validate();\n } catch (final DomainException ex) {\n this.errors.addAll(ex.getErrors());\n } catch (final Throwable t) {\n this.errors.add(new Error(t.getMessage()));\n }\n return null;\n }\n\n @Override\n public List<Error> getErrors() {\n return this.errors;\n }\n}" } ]
import br.com.ifsp.tickets.api.domain.event.entity.Event; import br.com.ifsp.tickets.api.domain.event.entity.EventID; import br.com.ifsp.tickets.api.domain.event.gateway.EventGateway; import br.com.ifsp.tickets.api.domain.guest.entity.Guest; import br.com.ifsp.tickets.api.domain.guest.entity.GuestID; import br.com.ifsp.tickets.api.domain.guest.entity.profile.Profile; import br.com.ifsp.tickets.api.domain.guest.gateway.GuestGateway; import br.com.ifsp.tickets.api.domain.shared.exceptions.InternalErrorException; import br.com.ifsp.tickets.api.domain.shared.exceptions.NotFoundException; import br.com.ifsp.tickets.api.domain.shared.exceptions.NotificationException; import br.com.ifsp.tickets.api.domain.shared.validation.handler.Notification; import java.util.function.Supplier;
2,577
package br.com.ifsp.tickets.api.app.guest.create; public class DefaultCreateGuestUseCase extends CreateGuestUseCase { private final GuestGateway guestGateway;
package br.com.ifsp.tickets.api.app.guest.create; public class DefaultCreateGuestUseCase extends CreateGuestUseCase { private final GuestGateway guestGateway;
private final EventGateway eventGateway;
2
2023-10-11 00:05:05+00:00
4k
DrMango14/Create-Design-n-Decor
src/main/java/com/mangomilk/design_decor/base/DecorBuilderTransformer.java
[ { "identifier": "CreateMMBuilding", "path": "src/main/java/com/mangomilk/design_decor/CreateMMBuilding.java", "snippet": "@Mod(CreateMMBuilding.MOD_ID)\npublic class CreateMMBuilding\n{\n\n public static final String MOD_ID = \"design_decor\";\n public static final String NAME = \"Create: Design n' Decor\";\n public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(CreateMMBuilding.MOD_ID).creativeModeTab(()-> MmbCreativeModeTab.BUILDING);\n public static final Logger LOGGER = LogUtils.getLogger();\n\n public CreateMMBuilding()\n {\n IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();\n\n REGISTRATE.registerEventListeners(eventBus);\n\n\n //\n\n MmbBlocks.register();\n MmbBlocks.DecoTags.init();\n MmbItems.register();\n DecoSoundEvents.register(eventBus);\n MmbBlockEntities.register();\n MmbSpriteShifts.init();\n DecoPartialModels.init();\n\n\n //\n\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n LOGGER.info(\":3\");\n }\n\n public static ResourceLocation asResource(String path) {\n return new ResourceLocation(MOD_ID, path);\n }\n}" }, { "identifier": "OrnateGrateBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/OrnateGrateBlock.java", "snippet": "@SuppressWarnings({\"unused\",\"deprecation\"})\n@ParametersAreNonnullByDefault\n@MethodsReturnNonnullByDefault\npublic class OrnateGrateBlock extends GlassBlock implements SimpleWaterloggedBlock, IWrenchable {\n public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED;\n\n public OrnateGrateBlock(Properties p_49795_) {\n super(p_49795_.isSuffocating(OrnateGrateBlock::never).noOcclusion().isViewBlocking(OrnateGrateBlock::allow));\n this.registerDefaultState(this.stateDefinition.any().setValue(WATERLOGGED, Boolean.FALSE));\n }\n\n @Override\n @Nullable\n public BlockState getStateForPlacement(BlockPlaceContext p_51454_) {\n FluidState fluidstate = p_51454_.getLevel().getFluidState(p_51454_.getClickedPos());\n boolean flag = fluidstate.getType() == Fluids.WATER;\n return Objects.requireNonNull(super.getStateForPlacement(p_51454_)).setValue(WATERLOGGED, flag);\n }\n\n @Override\n public BlockState updateShape(BlockState p_51461_, Direction p_51462_, BlockState p_51463_, LevelAccessor p_51464_, BlockPos p_51465_, BlockPos p_51466_) {\n if (p_51461_.getValue(WATERLOGGED)) {\n p_51464_.scheduleTick(p_51465_, Fluids.WATER, Fluids.WATER.getTickDelay(p_51464_));\n }\n\n return super.updateShape(p_51461_, p_51462_, p_51463_, p_51464_, p_51465_, p_51466_);\n }\n\n @Override\n protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> p_51468_) {\n p_51468_.add(WATERLOGGED);\n }\n\n @Override\n public FluidState getFluidState(BlockState p_51475_) {\n return p_51475_.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(p_51475_);\n }\n\n private static boolean never(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return false;\n }\n private static boolean allow(BlockState p_235436_0_, BlockGetter p_235436_1_, BlockPos p_235436_2_) {\n return true;\n }\n}" }, { "identifier": "ConnectedTintedGlassBlock", "path": "src/main/java/com/mangomilk/design_decor/blocks/glass/ConnectedTintedGlassBlock.java", "snippet": "public class ConnectedTintedGlassBlock extends TintedGlassBlock {\n public ConnectedTintedGlassBlock(Properties p_154822_) {\n super(p_154822_);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() instanceof ConnectedTintedGlassBlock || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState state, BlockAndTintGetter world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n}" }, { "identifier": "DecoTags", "path": "src/main/java/com/mangomilk/design_decor/registry/MmbBlocks.java", "snippet": "public static class DecoTags {\n public static <T> TagKey<T> optionalTag(IForgeRegistry<T> registry,\n ResourceLocation id) {\n return registry.tags()\n .createOptionalTagKey(id, Collections.emptySet());\n }\n public static <T> TagKey<T> CreateTag(IForgeRegistry<T> registry, String path) {\n return optionalTag(registry, new ResourceLocation(\"create\", path));\n }\n public static TagKey<Item> CreateItemTag(String path) {\n return CreateTag(ForgeRegistries.ITEMS, path);\n }\n public static TagKey<Block> CreateBlockTag(String path) {\n return CreateTag(ForgeRegistries.BLOCKS, path);\n }\n public static <T> TagKey<T> MCTag(IForgeRegistry<T> registry, String path) {\n return optionalTag(registry, new ResourceLocation(\"minecraft\", path));\n }\n public static TagKey<Item> MCItemTag(String path) {\n return MCTag(ForgeRegistries.ITEMS, path);\n }\n public static TagKey<Block> MCBlockTag(String path) {\n return MCTag(ForgeRegistries.BLOCKS, path);\n }\n public static void init() {\n }\n}" }, { "identifier": "CreateItemTag", "path": "src/main/java/com/mangomilk/design_decor/registry/MmbBlocks.java", "snippet": "public static TagKey<Item> CreateItemTag(String path) {\n return CreateTag(ForgeRegistries.ITEMS, path);\n}" } ]
import com.mangomilk.design_decor.CreateMMBuilding; import com.mangomilk.design_decor.blocks.OrnateGrateBlock; import com.mangomilk.design_decor.blocks.glass.ConnectedTintedGlassBlock; import com.simibubi.create.content.decoration.encasing.EncasedCTBehaviour; import com.simibubi.create.foundation.block.connected.CTSpriteShiftEntry; import com.simibubi.create.foundation.block.connected.ConnectedTextureBehaviour; import com.simibubi.create.foundation.block.connected.HorizontalCTBehaviour; import com.simibubi.create.foundation.data.AssetLookup; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.CreateRegistrate; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.builders.BlockBuilder; import com.tterrag.registrate.util.DataIngredient; import com.tterrag.registrate.util.entry.BlockEntry; import com.tterrag.registrate.util.nullness.NonNullUnaryOperator; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.BlockPos; import net.minecraft.tags.BlockTags; import net.minecraft.world.entity.EntityType; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.common.Tags; import java.util.function.Supplier; import static com.mangomilk.design_decor.registry.MmbBlocks.DecoTags.*; import static com.mangomilk.design_decor.registry.MmbBlocks.DecoTags.CreateItemTag; import static com.simibubi.create.foundation.data.CreateRegistrate.casingConnectivity; import static com.simibubi.create.foundation.data.CreateRegistrate.connectedTextures; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly;
2,988
package com.mangomilk.design_decor.base; public class DecorBuilderTransformer { public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get())) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected( Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), p.models() .cubeColumn(c.getName(), ct.get() .getOriginalResourceLocation(), ct2.get() .getOriginalResourceLocation()))) .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p))) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) { return p.isValidSpawn(DecorBuilderTransformer::never) .isRedstoneConductor(DecorBuilderTransformer::never) .isSuffocating(DecorBuilderTransformer::never) .isViewBlocking(DecorBuilderTransformer::never) .noOcclusion(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block("tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", "tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang("Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/tinted_framed_glass"))) .build() .register(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block(type + "_tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", type + "_tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang(name + " Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/" + type + "_tinted_framed_glass"))) .build() .register(); } public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) { CreateMMBuilding.REGISTRATE.block(id + "_castel_brick_stairs", p -> new StairBlock(block.defaultBlockState(), p)) .initialProperties(() -> block) .properties(p -> p.color(color)) .properties(p -> p.destroyTime(1.25f)) .transform(pickaxeOnly()) .tag(MCBlockTag("stairs"))
package com.mangomilk.design_decor.base; public class DecorBuilderTransformer { public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> connected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get())) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends Block> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> layeredConnected( Supplier<CTSpriteShiftEntry> ct, Supplier<CTSpriteShiftEntry> ct2) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), p.models() .cubeColumn(c.getName(), ct.get() .getOriginalResourceLocation(), ct2.get() .getOriginalResourceLocation()))) .onRegister(connectedTextures(() -> new HorizontalCTBehaviour(ct.get(), ct2.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } public static <B extends OrnateGrateBlock> NonNullUnaryOperator<BlockBuilder<B, CreateRegistrate>> ornateconnected( Supplier<CTSpriteShiftEntry> ct) { return b -> b.initialProperties(SharedProperties::stone) .blockstate((c, p) -> p.simpleBlock(c.get(), AssetLookup.standardModel(c, p))) .onRegister(connectedTextures(() -> new EncasedCTBehaviour(ct.get()))) .onRegister(casingConnectivity((block, cc) -> cc.makeCasing(block, ct.get()))); } private static BlockBehaviour.Properties glassProperties(BlockBehaviour.Properties p) { return p.isValidSpawn(DecorBuilderTransformer::never) .isRedstoneConductor(DecorBuilderTransformer::never) .isSuffocating(DecorBuilderTransformer::never) .isViewBlocking(DecorBuilderTransformer::never) .noOcclusion(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block("tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", "tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang("Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/tinted_framed_glass"))) .build() .register(); } public static BlockEntry<ConnectedTintedGlassBlock> tintedframedGlass(String type,String name, Supplier<ConnectedTextureBehaviour> behaviour) { return CreateMMBuilding.REGISTRATE.block(type + "_tinted_framed_glass", ConnectedTintedGlassBlock::new) .onRegister(connectedTextures(behaviour)) .addLayer(() -> RenderType::translucent) .initialProperties(() -> Blocks.TINTED_GLASS) .properties(DecorBuilderTransformer::glassProperties) .recipe((c, p) -> p.stonecutting(DataIngredient.tag(Tags.Items.GLASS_TINTED), c::get)) .blockstate((c, p) -> BlockStateGen.cubeAll(c, p, "palettes/", type + "_tinted_framed_glass")) .tag(Tags.Blocks.GLASS_TINTED, Tags.Blocks.GLASS, BlockTags.IMPERMEABLE) .lang(name + " Tinted Framed Glass") .item() .tag(Tags.Items.GLASS_TINTED, Tags.Items.GLASS) .model((c, p) -> p.cubeColumn(c.getName(), p.modLoc(palettesDir() + c.getName()), p.modLoc("block/palettes/" + type + "_tinted_framed_glass"))) .build() .register(); } public static BlockEntry<Block> CastelBricks(String id, String lang, MaterialColor color, Block block) { CreateMMBuilding.REGISTRATE.block(id + "_castel_brick_stairs", p -> new StairBlock(block.defaultBlockState(), p)) .initialProperties(() -> block) .properties(p -> p.color(color)) .properties(p -> p.destroyTime(1.25f)) .transform(pickaxeOnly()) .tag(MCBlockTag("stairs"))
.recipe((c, p) -> p.stonecutting(DataIngredient.tag(CreateItemTag("stone_types/" + id)), c::get, 1))
4
2023-10-14 21:51:49+00:00
4k
Konloch/InjectedCalculator
src/main/java/com/konloch/ic/InjectedCalculator.java
[ { "identifier": "Calculator", "path": "src/main/java/com/konloch/ic/calculator/Calculator.java", "snippet": "public abstract class Calculator\n{\n\tpublic abstract long add(long a, long b);\n\tpublic abstract long sub(long a, long b);\n\tpublic abstract long mul(long a, long b);\n\tpublic abstract long div(long a, long b);\n}" }, { "identifier": "CalculatorInjector", "path": "src/main/java/com/konloch/ic/calculator/injector/CalculatorInjector.java", "snippet": "public class CalculatorInjector implements CalculatorInjectorI\n{\n\t@Override\n\tpublic Calculator inject()\n\t{\n\t\t//create new calc instance based off of java ASM, implementing the functions as needed\n\t\tClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);\n\t\t\n\t\t//define class\n\t\tcw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, \"GeneratedCalculator\", null, \"com/konloch/ic/calculator/Calculator\", null);\n\t\t{\n\t\t\t//implement init method\n\t\t\tMethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"<init>\", \"()V\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.ALOAD, 0);\n\t\t\tmv.visitMethodInsn(Opcodes.INVOKESPECIAL, \"com/konloch/ic/calculator/Calculator\", \"<init>\", \"()V\", false);\n\t\t\tmv.visitInsn(Opcodes.RETURN);\n\t\t\tmv.visitMaxs(1, 1);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement add method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"add\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LADD);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement sub method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"sub\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LSUB);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement mul method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"mul\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LMUL);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t\t\n\t\t\t//implement div method\n\t\t\tmv = cw.visitMethod(Opcodes.ACC_PUBLIC, \"div\", \"(JJ)J\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 1);\n\t\t\tmv.visitVarInsn(Opcodes.LLOAD, 3);\n\t\t\tmv.visitInsn(Opcodes.LDIV);\n\t\t\tmv.visitInsn(Opcodes.LRETURN);\n\t\t\tmv.visitMaxs(3, 3);\n\t\t\tmv.visitEnd();\n\t\t}\n\t\tcw.visitEnd();\n\t\t\n\t\ttry\n\t\t{\n\t\t\tbyte[] bytecode = cw.toByteArray();\n\t\t\t\n\t\t\t//define a custom class loader to load the generated class\n\t\t\tInjectedClassLoader classLoader = new InjectedClassLoader();\n\t\t\t\n\t\t\tClass<?> generatedClass = classLoader.defineClass(\"GeneratedCalculator\", bytecode);\n\t\t\treturn (Calculator) generatedClass.newInstance();\n\t\t}\n\t\tcatch (InstantiationException | IllegalAccessException e)\n\t\t{\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "ExpressionEvaluator", "path": "src/main/java/com/konloch/ic/calculator/expression/ExpressionEvaluator.java", "snippet": "public class ExpressionEvaluator\n{\n\tprivate final Calculator calculator;\n\t\n\tpublic ExpressionEvaluator(Calculator calculator)\n\t{\n\t\tthis.calculator = calculator;\n\t}\n\t\n\tpublic long evaluateExpression(String expression)\n\t{\n\t\tStack<Long> operands = new Stack<>();\n\t\tStack<Character> operators = new Stack<>();\n\t\tchar[] chars = expression.toCharArray();\n\t\t\n\t\tStringBuilder numBuffer = new StringBuilder();\n\t\t\n\t\tfor (char c : chars)\n\t\t{\n\t\t\tif (Character.isDigit(c))\n\t\t\t\tnumBuffer.append(c);\n\t\t\telse if (c == '+' || c == '-' || c == '*' || c == '/')\n\t\t\t{\n\t\t\t\tif(numBuffer.length() > 0)\n\t\t\t\t{\n\t\t\t\t\toperands.push(Long.parseLong(numBuffer.toString()));\n\t\t\t\t\tnumBuffer = new StringBuilder();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\twhile (!operators.isEmpty() && hasPrecedence(c, operators.peek()))\n\t\t\t\t{\n\t\t\t\t\tevaluateStackTop(operands, operators);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\toperators.push(c);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(numBuffer.length() > 0)\n\t\t\toperands.push(Long.parseLong(numBuffer.toString()));\n\t\t\n\t\twhile (!operators.isEmpty())\n\t\t{\n\t\t\tevaluateStackTop(operands, operators);\n\t\t}\n\t\t\n\t\treturn operands.pop();\n\t}\n\t\n\tprivate void evaluateStackTop(Stack<Long> operands, Stack<Character> operators)\n\t{\n\t\tchar operator = operators.pop();\n\t\tlong operand2 = operands.pop();\n\t\tlong operand1 = operands.pop();\n\t\toperands.push(evaluateOperation(operator, operand1, operand2));\n\t}\n\t\n\tprivate long evaluateOperation(char operator, long operand1, long operand2)\n\t{\n\t\tlong result = 0;\n\t\t\n\t\tswitch (operator)\n\t\t{\n\t\t\tcase '+':\n\t\t\t\tresult = calculator.add(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '-':\n\t\t\t\tresult = calculator.sub(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '*':\n\t\t\t\tresult = calculator.mul(operand1, operand2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase '/':\n\t\t\t\tresult = calculator.div(operand1, operand2);\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tprivate boolean hasPrecedence(char op1, char op2)\n\t{\n\t\treturn (op2 == '*' || op2 == '/') && (op1 == '+' || op1 == '-');\n\t}\n}" } ]
import com.konloch.ic.calculator.Calculator; import com.konloch.ic.calculator.injector.CalculatorInjector; import com.konloch.ic.calculator.expression.ExpressionEvaluator;
1,619
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator { private final ExpressionEvaluator evaluator; public InjectedCalculator(Calculator calculator) { this.evaluator = new ExpressionEvaluator(calculator); } public static void main(String[] args) {
package com.konloch.ic; /** * "But its also missing code, so it injects what its missing" * * @author Konloch * @since 10/15/2023 */ public class InjectedCalculator { private final ExpressionEvaluator evaluator; public InjectedCalculator(Calculator calculator) { this.evaluator = new ExpressionEvaluator(calculator); } public static void main(String[] args) {
InjectedCalculator calculator = new InjectedCalculator(new CalculatorInjector().inject());
1
2023-10-15 08:38:08+00:00
4k
DeeChael/dcg
src/main/java/net/deechael/dcg/source/structure/DyParameter.java
[ { "identifier": "DyType", "path": "src/main/java/net/deechael/dcg/source/type/DyType.java", "snippet": "public interface DyType extends DyExportable, Invoker {\n\n // Default provided JTypes\n DyType VOID = classType(void.class);\n DyType INT = classType(int.class);\n DyType BOOLEAN = classType(boolean.class);\n DyType DOUBLE = classType(double.class);\n DyType FLOAT = classType(float.class);\n DyType LONG = classType(long.class);\n DyType SHORT = classType(short.class);\n DyType BYTE = classType(byte.class);\n DyType CHAR = classType(char.class);\n DyType OBJECT = classType(Object.class);\n DyType STRING = classType(String.class);\n DyType CLASS = classType(Class.class);\n\n /**\n * Get type for normal class type\n *\n * @param clazz class type\n * @return type\n */\n @NotNull\n static DyType classType(@NotNull Class<?> clazz) {\n return new DyJvmType(clazz);\n }\n\n /**\n * Get type for a generic type </br>\n * Example: List<T>, Map<K, V> etc.\n *\n * @param clazz base type\n * @param types generic parameters\n * @return type\n */\n @NotNull\n static DyType genericClassType(@NotNull Class<?> clazz, @NotNull DyType... types) {\n return new DyJvmGenericType(clazz, types);\n }\n\n @NotNull\n static DyType unknownGenericType(@Nullable DyType extending) {\n return new UnknownGenericType(extending);\n }\n\n /**\n * To check if this type is primitive type\n *\n * @return if is primitive type\n */\n boolean isPrimitive();\n\n /**\n * Get the base type of this type </br>\n * Example: if this type is java.lang.String[][], this method will return java.lang.String\n *\n * @return base type of this type\n */\n @NotNull\n DyType getBaseType();\n\n /**\n * Generate compilable string\n *\n * @return compilable string\n */\n @NotNull\n String toTypeString();\n\n /**\n * To check if this type is array\n *\n * @return if this type self is an array\n */\n boolean isArray();\n\n @Override\n @NotNull\n default String toExportableString() {\n return this.toTypeString();\n }\n\n @Override\n @NotNull\n default String toInvokerString() {\n return this.toTypeString();\n }\n\n @Override\n default boolean isStaticExportable() {\n return false;\n }\n\n}" }, { "identifier": "JvmVariable", "path": "src/main/java/net/deechael/dcg/source/variable/JvmVariable.java", "snippet": "public interface JvmVariable extends Variable {\n\n @Override\n default String getName() {\n throw new RuntimeException(\"Jvm variable has no name\");\n }\n\n @Override\n @NotNull\n default DyStructure getDomain() {\n return DyUndefinedStructure.INSTANCE;\n }\n\n}" }, { "identifier": "ReferringVariable", "path": "src/main/java/net/deechael/dcg/source/variable/internal/ReferringVariable.java", "snippet": "public class ReferringVariable implements Variable {\n\n private final DyStructure structure;\n\n private final DyType type;\n private final String name;\n\n public ReferringVariable(DyStructure structure, DyType type, String name) {\n this.structure = structure;\n\n this.type = type;\n this.name = name;\n }\n\n @Override\n public @NotNull DyType getType() {\n if (this.type == null)\n throw new RuntimeException(\"This referring variable may be a multi-type available variable!\");\n return this.type;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public @NotNull DyStructure getDomain() {\n return this.structure;\n }\n\n @Override\n public String toVariableString() {\n return this.getName();\n }\n\n}" }, { "identifier": "StringCompiler", "path": "src/main/java/net/deechael/dcg/util/StringCompiler.java", "snippet": "public final class StringCompiler {\n\n public static String compileAnnotations(Map<DyType, Map<String, JvmVariable>> annotations) {\n StringBuilder builder = new StringBuilder();\n if (annotations.isEmpty())\n return \"\";\n for (Map.Entry<DyType, Map<String, JvmVariable>> entry : annotations.entrySet()) {\n builder.append(\"@\").append(entry.getKey().toTypeString());\n if (entry.getValue().isEmpty()) {\n builder.append(\"\\n\");\n continue;\n }\n builder.append(\"(\");\n builder.append(String.join(\", \", entry.getValue()\n .entrySet()\n .stream()\n .map(value -> new StringBuilder()\n .append(value.getKey())\n .append(\"=\")\n .append(value.getValue().toVariableString())\n )\n .map(StringBuilder::toString)\n .toList()\n .toArray(new String[0])));\n builder.append(\")\\n\");\n }\n return builder.append(\" \").toString();\n }\n\n public static String compileImports(Iterable<DyExportable> imports) {\n List<DyExportable> sortedExportables = new ArrayList<>();\n for (DyExportable exportable : imports)\n sortedExportables.add(exportable);\n sortedExportables.sort((o1, o2) -> {\n if (o1.isStaticExportable() && !o2.isStaticExportable())\n return 1;\n else if (!o1.isStaticExportable() && o2.isStaticExportable())\n return -1;\n return 0;\n });\n StringBuilder builder = new StringBuilder();\n for (DyExportable exportable : imports) {\n builder.append(\"import\")\n .append(\" \");\n if (exportable.isStaticExportable())\n builder.append(\"static\")\n .append(\" \");\n builder.append(exportable.toExportableString())\n .append(\";\")\n .append(\"\\n\");\n }\n return builder.toString();\n }\n\n public static String compileInvokations(Iterable<Invokation> invokations) {\n StringBuilder builder = new StringBuilder();\n Iterator<Invokation> iterator = invokations.iterator();\n for (Invokation invokation = iterator.next(); iterator.hasNext(); invokation = iterator.next()) {\n builder.append(invokation.toCompilableString())\n .append(\"\\n\");\n }\n return builder.toString();\n }\n\n public static String compileGenericables(DyGenericable genericable) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"<\");\n Iterator<GenericType> iterator = genericable.listGenerics().iterator();\n if (iterator.hasNext())\n for (GenericType type = iterator.next(); iterator.hasNext(); type = iterator.next()) {\n builder.append(type.toGenericTypeString());\n if (iterator.hasNext())\n builder.append(\",\")\n .append(\" \");\n }\n builder.append(\">\");\n return builder.toString();\n }\n\n public static String compileParameters(DyParameterable parameterable) {\n StringBuilder builder = new StringBuilder();\n Iterator<DyParameter> iterator = parameterable.listParameters().iterator();\n if (iterator.hasNext())\n for (DyParameter parameter = iterator.next(); iterator.hasNext(); parameter = iterator.next()) {\n builder.append(parameter.toCompilableString());\n if (iterator.hasNext())\n builder.append(\", \");\n }\n return builder.toString();\n }\n\n private StringCompiler() {\n }\n\n}" } ]
import net.deechael.dcg.source.type.DyType; import net.deechael.dcg.source.variable.JvmVariable; import net.deechael.dcg.source.variable.internal.ReferringVariable; import net.deechael.dcg.util.StringCompiler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map;
2,072
package net.deechael.dcg.source.structure; public class DyParameter extends ReferringVariable implements DyAnnotatable { protected final Map<DyType, Map<String, JvmVariable>> annotations = new HashMap<>(); public DyParameter(DyStructure structure, DyType type, String name) { super(structure, type, name); } @Override public void annotate(@NotNull DyType annotationType, @Nullable Map<String, JvmVariable> values) { this.annotations.put(annotationType, values != null ? values : new HashMap<>()); } @Override public @NotNull Map<DyType, Map<String, JvmVariable>> listAnnotations() { return this.annotations; } @Override public String toCompilableString() { StringBuilder builder = new StringBuilder(); if (!this.annotations.isEmpty())
package net.deechael.dcg.source.structure; public class DyParameter extends ReferringVariable implements DyAnnotatable { protected final Map<DyType, Map<String, JvmVariable>> annotations = new HashMap<>(); public DyParameter(DyStructure structure, DyType type, String name) { super(structure, type, name); } @Override public void annotate(@NotNull DyType annotationType, @Nullable Map<String, JvmVariable> values) { this.annotations.put(annotationType, values != null ? values : new HashMap<>()); } @Override public @NotNull Map<DyType, Map<String, JvmVariable>> listAnnotations() { return this.annotations; } @Override public String toCompilableString() { StringBuilder builder = new StringBuilder(); if (!this.annotations.isEmpty())
builder.append(StringCompiler.compileAnnotations(this.annotations))
3
2023-10-15 13:45:11+00:00
4k
giteecode/supermarket2Public
src/main/java/com/ruoyi/project/monitor/cache/CacheController.java
[ { "identifier": "BaseController", "path": "src/main/java/com/ruoyi/framework/web/controller/BaseController.java", "snippet": "public class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n \n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\n {\n @Override\n public void setAsText(String text)\n {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage()\n {\n PageUtils.startPage();\n }\n\n /**\n * 设置请求排序数据\n */\n protected void startOrderBy()\n {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))\n {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n PageHelper.orderBy(orderBy);\n }\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List<?> list)\n {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(0);\n rspData.setRows(list);\n rspData.setTotal(new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows)\n {\n return rows > 0 ? success() : error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result)\n {\n return result ? success() : error();\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success()\n {\n return AjaxResult.success();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error()\n {\n return AjaxResult.error();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message)\n {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回成功数据\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message)\n {\n return AjaxResult.error(message);\n }\n\n /**\n * 返回错误码消息\n */\n public AjaxResult error(Type type, String message)\n {\n return new AjaxResult(type, message);\n }\n\n /**\n * 页面跳转\n */\n public String redirect(String url)\n {\n return StringUtils.format(\"redirect:{}\", url);\n }\n\n /**\n * 获取用户缓存信息\n */\n public User getSysUser()\n {\n return ShiroUtils.getSysUser();\n }\n\n /**\n * 设置用户缓存信息\n */\n public void setSysUser(User user)\n {\n ShiroUtils.setSysUser(user);\n }\n\n /**\n * 获取登录用户id\n */\n public Long getUserId()\n {\n return getSysUser().getUserId();\n }\n\n /**\n * 获取登录用户名\n */\n public String getLoginName()\n {\n return getSysUser().getLoginName();\n }\n}" }, { "identifier": "AjaxResult", "path": "src/main/java/com/ruoyi/framework/web/domain/AjaxResult.java", "snippet": "public class AjaxResult extends HashMap<String, Object>\n{\n private static final long serialVersionUID = 1L;\n\n /** 状态码 */\n public static final String CODE_TAG = \"code\";\n\n /** 返回内容 */\n public static final String MSG_TAG = \"msg\";\n\n /** 数据对象 */\n public static final String DATA_TAG = \"data\";\n\n /**\n * 状态类型\n */\n public enum Type\n {\n /** 成功 */\n SUCCESS(0),\n /** 警告 */\n WARN(301),\n /** 错误 */\n ERROR(500);\n private final int value;\n\n Type(int value)\n {\n this.value = value;\n }\n\n public int value()\n {\n return this.value;\n }\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。\n */\n public AjaxResult()\n {\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n */\n public AjaxResult(Type type, String msg)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n * @param data 数据对象\n */\n public AjaxResult(Type type, String msg, Object data)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n if (StringUtils.isNotNull(data))\n {\n super.put(DATA_TAG, data);\n }\n }\n\n /**\n * 方便链式调用\n *\n * @param key 键\n * @param value 值\n * @return 数据对象\n */\n @Override\n public AjaxResult put(String key, Object value)\n {\n super.put(key, value);\n return this;\n }\n\n /**\n * 返回成功消息\n *\n * @return 成功消息\n */\n public static AjaxResult success()\n {\n return AjaxResult.success(\"操作成功\");\n }\n\n /**\n * 返回成功数据\n *\n * @return 成功消息\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @return 成功消息\n */\n public static AjaxResult success(String msg)\n {\n return AjaxResult.success(msg, null);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 成功消息\n */\n public static AjaxResult success(String msg, Object data)\n {\n return new AjaxResult(Type.SUCCESS, msg, data);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult warn(String msg)\n {\n return AjaxResult.warn(msg, null);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult warn(String msg, Object data)\n {\n return new AjaxResult(Type.WARN, msg, data);\n }\n\n /**\n * 返回错误消息\n *\n * @return\n */\n public static AjaxResult error()\n {\n return AjaxResult.error(\"操作失败\");\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult error(String msg)\n {\n return AjaxResult.error(msg, null);\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult error(String msg, Object data)\n {\n return new AjaxResult(Type.ERROR, msg, data);\n }\n}" }, { "identifier": "CacheService", "path": "src/main/java/com/ruoyi/framework/web/service/CacheService.java", "snippet": "@Service\npublic class CacheService\n{\n /**\n * 获取所有缓存名称\n * \n * @return 缓存列表\n */\n public String[] getCacheNames()\n {\n String[] cacheNames = CacheUtils.getCacheNames();\n return ArrayUtils.removeElement(cacheNames, Constants.SYS_AUTH_CACHE);\n }\n\n /**\n * 根据缓存名称获取所有键名\n * \n * @param cacheName 缓存名称\n * @return 键名列表\n */\n public Set<String> getCacheKeys(String cacheName)\n {\n return CacheUtils.getCache(cacheName).keys();\n }\n\n /**\n * 根据缓存名称和键名获取内容值\n * \n * @param cacheName 缓存名称\n * @param cacheKey 键名\n * @return 键值\n */\n public Object getCacheValue(String cacheName, String cacheKey)\n {\n return CacheUtils.get(cacheName, cacheKey);\n }\n\n /**\n * 根据名称删除缓存信息\n * \n * @param cacheName 缓存名称\n */\n public void clearCacheName(String cacheName)\n {\n CacheUtils.removeAll(cacheName);\n }\n\n /**\n * 根据名称和键名删除缓存信息\n * \n * @param cacheName 缓存名称\n * @param cacheKey 键名\n */\n public void clearCacheKey(String cacheName, String cacheKey)\n {\n CacheUtils.remove(cacheName, cacheKey);\n }\n\n /**\n * 清理所有缓存\n */\n public void clearAll()\n {\n String[] cacheNames = getCacheNames();\n for (String cacheName : cacheNames)\n {\n CacheUtils.removeAll(cacheName);\n }\n }\n}" } ]
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ruoyi.framework.web.controller.BaseController; import com.ruoyi.framework.web.domain.AjaxResult; import com.ruoyi.framework.web.service.CacheService;
2,718
package com.ruoyi.project.monitor.cache; /** * 缓存监控 * * @author ruoyi */ @Controller @RequestMapping("/monitor/cache")
package com.ruoyi.project.monitor.cache; /** * 缓存监控 * * @author ruoyi */ @Controller @RequestMapping("/monitor/cache")
public class CacheController extends BaseController
0
2023-10-14 02:27:47+00:00
4k
Yunzez/SubDependency_CodeLine_Analysis
java/Calculator-master/src/main/java/com/houarizegai/calculator/ui/CalculatorUI.java
[ { "identifier": "Theme", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/theme/properties/Theme.java", "snippet": "public class Theme {\n\n private String name;\n private String applicationBackground;\n private String textColor;\n private String btnEqualTextColor;\n private String operatorBackground;\n private String numbersBackground;\n private String btnEqualBackground;\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 getApplicationBackground() {\n return applicationBackground;\n }\n\n public void setApplicationBackground(String applicationBackground) {\n this.applicationBackground = applicationBackground;\n }\n\n public String getTextColor() {\n return textColor;\n }\n\n public void setTextColor(String textColor) {\n this.textColor = textColor;\n }\n\n public String getBtnEqualTextColor() {\n return btnEqualTextColor;\n }\n\n public void setBtnEqualTextColor(String btnEqualTextColor) {\n this.btnEqualTextColor = btnEqualTextColor;\n }\n\n public String getOperatorBackground() {\n return operatorBackground;\n }\n\n public void setOperatorBackground(String operatorBackground) {\n this.operatorBackground = operatorBackground;\n }\n\n public String getNumbersBackground() {\n return numbersBackground;\n }\n\n public void setNumbersBackground(String numbersBackground) {\n this.numbersBackground = numbersBackground;\n }\n\n public String getBtnEqualBackground() {\n return btnEqualBackground;\n }\n\n public void setBtnEqualBackground(String btnEqualBackground) {\n this.btnEqualBackground = btnEqualBackground;\n }\n}" }, { "identifier": "ThemeLoader", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/theme/ThemeLoader.java", "snippet": "public class ThemeLoader {\n\n private ThemeLoader() {\n throw new AssertionError(\"Constructor is not allowed\");\n }\n\n public static Map<String, Theme> loadThemes() {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n try {\n ThemeList themeList = mapper.readValue(new File(\"src/main/resources/application.yaml\"), ThemeList.class);\n return themeList.getThemesAsMap();\n } catch (IOException e) {\n return Collections.emptyMap();\n }\n }\n}" }, { "identifier": "hex2Color", "path": "java/Calculator-master/src/main/java/com/houarizegai/calculator/util/ColorUtil.java", "snippet": "public static Color hex2Color(String colorHex) {\n return Optional.ofNullable(colorHex)\n .map(hex -> new Color(\n Integer.valueOf(colorHex.substring(0, 2), 16),\n Integer.valueOf(colorHex.substring(2, 4), 16),\n Integer.valueOf(colorHex.substring(4, 6), 16)))\n .orElse(null);\n}" } ]
import com.houarizegai.calculator.theme.properties.Theme; import com.houarizegai.calculator.theme.ThemeLoader; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ItemEvent; import java.util.Map; import java.util.regex.Pattern; import java.awt.Color; import javax.swing.*; import static com.houarizegai.calculator.util.ColorUtil.hex2Color;
2,859
inputScreen.setText("0."); addToDisplay = true; } go = true; }); btn0 = createButton("0", columns[1], rows[5]); btn0.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("0"); } else { inputScreen.setText(inputScreen.getText() + "0"); } } else { inputScreen.setText("0"); addToDisplay = true; } go = true; }); btnEqual = createButton("=", columns[2], rows[5]); btnEqual.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '='; addToDisplay = false; } }); btnEqual.setSize(2 * BUTTON_WIDTH + 10, BUTTON_HEIGHT); btnRoot = createButton("√", columns[4], rows[1]); btnRoot.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.sqrt(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '√'; addToDisplay = false; } }); btnRoot.setVisible(false); btnPower = createButton("pow", columns[4], rows[2]); btnPower.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '^'; go = false; addToDisplay = false; } else { selectedOperator = '^'; } }); btnPower.setFont(new Font("Comic Sans MS", Font.PLAIN, 24)); btnPower.setVisible(false); btnLog = createButton("ln", columns[4], rows[3]); btnLog.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.log(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = 'l'; addToDisplay = false; } }); btnLog.setVisible(false); } private JComboBox<String> createComboBox(String[] items, int x, int y, String toolTip) { JComboBox<String> combo = new JComboBox<>(items); combo.setBounds(x, y, 140, 25); combo.setToolTipText(toolTip); combo.setCursor(new Cursor(Cursor.HAND_CURSOR)); window.add(combo); return combo; } private JButton createButton(String label, int x, int y) { JButton btn = new JButton(label); btn.setBounds(x, y, BUTTON_WIDTH, BUTTON_HEIGHT); btn.setFont(new Font("Comic Sans MS", Font.PLAIN, 28)); btn.setCursor(new Cursor(Cursor.HAND_CURSOR)); btn.setFocusable(false); window.add(btn); return btn; } private void applyTheme(Theme theme) {
package com.houarizegai.calculator.ui; public class CalculatorUI { private static final String FONT_NAME = "Comic Sans MS"; private static final String DOUBLE_OR_NUMBER_REGEX = "([-]?\\d+[.]\\d*)|(\\d+)|(-\\d+)"; private static final String APPLICATION_TITLE = "Calculator"; private static final int WINDOW_WIDTH = 410; private static final int WINDOW_HEIGHT = 600; private static final int BUTTON_WIDTH = 80; private static final int BUTTON_HEIGHT = 70; private static final int MARGIN_X = 20; private static final int MARGIN_Y = 60; private final JFrame window; private JComboBox<String> comboCalculatorType; private JComboBox<String> comboTheme; private JTextField inputScreen; private JButton btnC; private JButton btnBack; private JButton btnMod; private JButton btnDiv; private JButton btnMul; private JButton btnSub; private JButton btnAdd; private JButton btn0; private JButton btn1; private JButton btn2; private JButton btn3; private JButton btn4; private JButton btn5; private JButton btn6; private JButton btn7; private JButton btn8; private JButton btn9; private JButton btnPoint; private JButton btnEqual; private JButton btnRoot; private JButton btnPower; private JButton btnLog; private char selectedOperator = ' '; private boolean go = true; // For calculate with Opt != (=) private boolean addToDisplay = true; // Connect numbers in display private double typedValue = 0; private final Map<String, Theme> themesMap; public CalculatorUI() { themesMap = ThemeLoader.loadThemes(); window = new JFrame(APPLICATION_TITLE); window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); window.setLocationRelativeTo(null); int[] columns = {MARGIN_X, MARGIN_X + 90, MARGIN_X + 90 * 2, MARGIN_X + 90 * 3, MARGIN_X + 90 * 4}; int[] rows = {MARGIN_Y, MARGIN_Y + 100, MARGIN_Y + 100 + 80, MARGIN_Y + 100 + 80 * 2, MARGIN_Y + 100 + 80 * 3, MARGIN_Y + 100 + 80 * 4}; initInputScreen(columns, rows); initButtons(columns, rows); initCalculatorTypeSelector(); initThemeSelector(); window.setLayout(null); window.setResizable(false); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public double calculate(double firstNumber, double secondNumber, char operator) { switch (operator) { case '+': return firstNumber + secondNumber; case '-': return firstNumber - secondNumber; case '*': return firstNumber * secondNumber; case '/': return firstNumber / secondNumber; case '%': return firstNumber % secondNumber; case '^': return Math.pow(firstNumber, secondNumber); default: return secondNumber; } } private void initThemeSelector() { comboTheme = createComboBox(themesMap.keySet().toArray(new String[0]), 230, 30, "Theme"); comboTheme.addItemListener(event -> { if (event.getStateChange() != ItemEvent.SELECTED) return; String selectedTheme = (String) event.getItem(); applyTheme(themesMap.get(selectedTheme)); }); if (themesMap.entrySet().iterator().hasNext()) { applyTheme(themesMap.entrySet().iterator().next().getValue()); } } private void initInputScreen(int[] columns, int[] rows) { inputScreen = new JTextField("0"); inputScreen.setBounds(columns[0], rows[0], 350, 70); inputScreen.setEditable(false); inputScreen.setBackground(Color.WHITE); inputScreen.setFont(new Font(FONT_NAME, Font.PLAIN, 33)); window.add(inputScreen); } private void initCalculatorTypeSelector() { comboCalculatorType = createComboBox(new String[]{"Standard", "Scientific"}, 20, 30, "Calculator type"); comboCalculatorType.addItemListener(event -> { if (event.getStateChange() != ItemEvent.SELECTED) return; String selectedItem = (String) event.getItem(); switch (selectedItem) { case "Standard": window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); btnRoot.setVisible(false); btnPower.setVisible(false); btnLog.setVisible(false); break; case "Scientific": window.setSize(WINDOW_WIDTH + 80, WINDOW_HEIGHT); btnRoot.setVisible(true); btnPower.setVisible(true); btnLog.setVisible(true); break; } }); } private void initButtons(int[] columns, int[] rows) { btnC = createButton("C", columns[0], rows[1]); btnC.addActionListener(event -> { inputScreen.setText("0"); selectedOperator = ' '; typedValue = 0; }); btnBack = createButton("<-", columns[1], rows[1]); btnBack.addActionListener(event -> { String str = inputScreen.getText(); StringBuilder str2 = new StringBuilder(); for (int i = 0; i < (str.length() - 1); i++) { str2.append(str.charAt(i)); } if (str2.toString().equals("")) { inputScreen.setText("0"); } else { inputScreen.setText(str2.toString()); } }); btnMod = createButton("%", columns[2], rows[1]); btnMod.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText()) || !go) return; typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '%'; go = false; addToDisplay = false; }); btnDiv = createButton("/", columns[3], rows[1]); btnDiv.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '/'; go = false; addToDisplay = false; } else { selectedOperator = '/'; } }); btn7 = createButton("7", columns[0], rows[2]); btn7.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("7"); } else { inputScreen.setText(inputScreen.getText() + "7"); } } else { inputScreen.setText("7"); addToDisplay = true; } go = true; }); btn8 = createButton("8", columns[1], rows[2]); btn8.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("8"); } else { inputScreen.setText(inputScreen.getText() + "8"); } } else { inputScreen.setText("8"); addToDisplay = true; } go = true; }); btn9 = createButton("9", columns[2], rows[2]); btn9.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("9"); } else { inputScreen.setText(inputScreen.getText() + "9"); } } else { inputScreen.setText("9"); addToDisplay = true; } go = true; }); btnMul = createButton("*", columns[3], rows[2]); btnMul.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '*'; go = false; addToDisplay = false; } else { selectedOperator = '*'; } }); btn4 = createButton("4", columns[0], rows[3]); btn4.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("4"); } else { inputScreen.setText(inputScreen.getText() + "4"); } } else { inputScreen.setText("4"); addToDisplay = true; } go = true; }); btn5 = createButton("5", columns[1], rows[3]); btn5.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("5"); } else { inputScreen.setText(inputScreen.getText() + "5"); } } else { inputScreen.setText("5"); addToDisplay = true; } go = true; }); btn6 = createButton("6", columns[2], rows[3]); btn6.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("6"); } else { inputScreen.setText(inputScreen.getText() + "6"); } } else { inputScreen.setText("6"); addToDisplay = true; } go = true; }); btnSub = createButton("-", columns[3], rows[3]); btnSub.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '-'; go = false; addToDisplay = false; } else { selectedOperator = '-'; } }); btn1 = createButton("1", columns[0], rows[4]); btn1.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("1"); } else { inputScreen.setText(inputScreen.getText() + "1"); } } else { inputScreen.setText("1"); addToDisplay = true; } go = true; }); btn2 = createButton("2", columns[1], rows[4]); btn2.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("2"); } else { inputScreen.setText(inputScreen.getText() + "2"); } } else { inputScreen.setText("2"); addToDisplay = true; } go = true; }); btn3 = createButton("3", columns[2], rows[4]); btn3.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("3"); } else { inputScreen.setText(inputScreen.getText() + "3"); } } else { inputScreen.setText("3"); addToDisplay = true; } go = true; }); btnAdd = createButton("+", columns[3], rows[4]); btnAdd.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '+'; go = false; addToDisplay = false; } else { selectedOperator = '+'; } }); btnPoint = createButton(".", columns[0], rows[5]); btnPoint.addActionListener(event -> { if (addToDisplay) { if (!inputScreen.getText().contains(".")) { inputScreen.setText(inputScreen.getText() + "."); } } else { inputScreen.setText("0."); addToDisplay = true; } go = true; }); btn0 = createButton("0", columns[1], rows[5]); btn0.addActionListener(event -> { if (addToDisplay) { if (Pattern.matches("[0]*", inputScreen.getText())) { inputScreen.setText("0"); } else { inputScreen.setText(inputScreen.getText() + "0"); } } else { inputScreen.setText("0"); addToDisplay = true; } go = true; }); btnEqual = createButton("=", columns[2], rows[5]); btnEqual.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '='; addToDisplay = false; } }); btnEqual.setSize(2 * BUTTON_WIDTH + 10, BUTTON_HEIGHT); btnRoot = createButton("√", columns[4], rows[1]); btnRoot.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.sqrt(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '√'; addToDisplay = false; } }); btnRoot.setVisible(false); btnPower = createButton("pow", columns[4], rows[2]); btnPower.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = calculate(typedValue, Double.parseDouble(inputScreen.getText()), selectedOperator); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = '^'; go = false; addToDisplay = false; } else { selectedOperator = '^'; } }); btnPower.setFont(new Font("Comic Sans MS", Font.PLAIN, 24)); btnPower.setVisible(false); btnLog = createButton("ln", columns[4], rows[3]); btnLog.addActionListener(event -> { if (!Pattern.matches(DOUBLE_OR_NUMBER_REGEX, inputScreen.getText())) return; if (go) { typedValue = Math.log(Double.parseDouble(inputScreen.getText())); if (Pattern.matches("[-]?[\\d]+[.][0]*", String.valueOf(typedValue))) { inputScreen.setText(String.valueOf((int) typedValue)); } else { inputScreen.setText(String.valueOf(typedValue)); } selectedOperator = 'l'; addToDisplay = false; } }); btnLog.setVisible(false); } private JComboBox<String> createComboBox(String[] items, int x, int y, String toolTip) { JComboBox<String> combo = new JComboBox<>(items); combo.setBounds(x, y, 140, 25); combo.setToolTipText(toolTip); combo.setCursor(new Cursor(Cursor.HAND_CURSOR)); window.add(combo); return combo; } private JButton createButton(String label, int x, int y) { JButton btn = new JButton(label); btn.setBounds(x, y, BUTTON_WIDTH, BUTTON_HEIGHT); btn.setFont(new Font("Comic Sans MS", Font.PLAIN, 28)); btn.setCursor(new Cursor(Cursor.HAND_CURSOR)); btn.setFocusable(false); window.add(btn); return btn; } private void applyTheme(Theme theme) {
window.getContentPane().setBackground(hex2Color(theme.getApplicationBackground()));
2
2023-10-14 20:31:35+00:00
4k
notoriux/xshellmenu
xshellmenu-gui/src/main/java/it/xargon/xshellmenu/misc/XSGuiPlatform.java
[ { "identifier": "XShellMenuMainClass", "path": "xshellmenu-gui/src/main/java/it/xargon/xshellmenu/XShellMenuMainClass.java", "snippet": "public class XShellMenuMainClass {\n\tprivate static Object exitLock = new Object();\n\tprivate static volatile AtomicInteger exitCodeRef = null;\n\t\n\tprivate TrayIconManager menuManager = null;\n\tprivate boolean initialized = false;\n\t\n\tpublic static void main(String[] args) throws Exception {\n\t\tSwingUtilities.invokeLater(() -> {\n\t\t\tnew XShellMenuMainClass(args).startGui();\n\t\t});\n\t\t\n\t\tsynchronized (exitLock) {\n\t\t\twhile (exitCodeRef == null) {\n\t\t\t\texitLock.wait();\n\t\t\t}\n\t\t}\n\t\t\n\t\tSystem.exit(exitCodeRef.get());\n\t}\n\t\n\tpublic static void exitApplication(int exitCode) {\n\t\tsynchronized (exitLock) {\n\t\t\texitCodeRef = new AtomicInteger(exitCode);\n\t\t\texitLock.notify();\n\t\t}\n\t}\t\n\t\n\tprivate XShellMenuMainClass(String[] args) {\n\t\ttry {\n\t\t\tUIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n\t\t} catch (ClassNotFoundException | InstantiationException | IllegalAccessException\n\t\t\t\t| UnsupportedLookAndFeelException e) {\n\t\t\tResources.xsGuiPlatform.abortApplication(\"Unable to start XShellMenu: error while setting LookAndFeel\", e);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (!SystemTray.isSupported()) {\n\t\t\tResources.xsGuiPlatform.showErrorMessage(\"System tray area is not supported on this platform\", true);\n\t\t\texitApplication(1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (args.length < 2) {\n\t\t\tResources.xsGuiPlatform.showErrorMessage(\"Need a menu provider name and an initalization string\", true);\n\t\t\texitApplication(2);\n\t\t\treturn;\t\t\t\n\t\t}\n\n\t\tmenuManager = new TrayIconManager(args);\n\t\tinitialized = true;\n\t}\n\t\n\tprivate void startGui() {\n\t\tif (initialized) menuManager.go();\n\t}\n}" }, { "identifier": "XSPlatform", "path": "xshellmenu-api/src/main/java/it/xargon/xshellmenu/api/XSPlatform.java", "snippet": "public interface XSPlatform {\n\tpublic enum OperatingSystem { WINDOWS, MACOS, LINUX, SOLARIS, NONE }\n\t\n\tpublic OperatingSystem getOperatingSystem();\n\t\n\tpublic void abortApplication(String errorMessage, Exception ex);\n\t\n\tpublic void showErrorMessage(String errorMessage, boolean wait);\n\t\n\tpublic boolean isDarkModeSystemTheme();\n\t\t\n\tpublic <T> T getPlatformResource(XSPlatformResource<T> resourceIdentifier);\n}" }, { "identifier": "XSPlatformResource", "path": "xshellmenu-api/src/main/java/it/xargon/xshellmenu/api/XSPlatformResource.java", "snippet": "public final class XSPlatformResource<T> {\n\tpublic final static XSPlatformResource<Icon> GENERIC_ICON = resourceOf(Icon.class);\n\tpublic final static XSPlatformResource<Icon> APPLICATION_ICON = resourceOf(Icon.class);\n\tpublic final static XSPlatformResource<ScheduledExecutorService> TASK_SCHEDULER = resourceOf(ScheduledExecutorService.class);\n\tpublic final static XSPlatformResource<ExecutorService> ICONFETCHER_SCHEDULER = resourceOf(ExecutorService.class);\n\t\n\tprivate Class<T> resourceClass;\n\t\n\tprivate static <T> XSPlatformResource<T> resourceOf(Class<T> resourceClass) {\n\t\treturn new XSPlatformResource<>(resourceClass);\n\t}\n\t\n\tprivate XSPlatformResource(Class<T> resourceClass) {\n\t\tthis.resourceClass = Objects.requireNonNull(resourceClass);\n\t}\n\t\n\tpublic T cast(Object obj) {return resourceClass.cast(obj);}\n}" }, { "identifier": "Resources", "path": "xshellmenu-gui/src/main/java/it/xargon/xshellmenu/res/Resources.java", "snippet": "public class Resources {\n\tprivate Resources() {}\n\t\n\tpublic final static XSPlatform xsGuiPlatform;\n\t\n\tpublic final static BaseMultiResolutionImage appIconImage;\n\tpublic final static ImageIcon appIcon;\n\tpublic final static ImageIcon quitIcon;\n\tpublic final static ImageIcon genericIcon;\n\tpublic final static ImageIcon expandIcon;\n\t\n\tstatic {\n\t\txsGuiPlatform = new XSGuiPlatform();\n\t\t\n\t\ttry {\n\t\t\tString prefix = xsGuiPlatform.isDarkModeSystemTheme() ? \"dark\" : \"light\";\n\t\t\t\n\t\t\tImage[] allSizesAppIcon = new Image[] {\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-16.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-32.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-48.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-64.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-128.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-256.png\")),\n\t\t\t\t\tImageIO.read(Resources.class.getResource(prefix + \"-app-icon-512.png\"))\t\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\tappIconImage = new BaseMultiResolutionImage(0, allSizesAppIcon);\n\t\t\tappIcon = new ImageIcon(appIconImage);\n\t\t\t\n\t\t\tgenericIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"generic-icon.png\")));\n\t\t\texpandIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"expand-icon.png\")));\n\t\t\tquitIcon = new ImageIcon(ImageIO.read(Resources.class.getResource(\"quit-icon.png\")));\n\t\t} catch (IOException ex) {\n\t\t\tthrow new IllegalStateException(\"Unable to initialize resources\", ex);\n\t\t}\n\t}\n}" } ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import it.xargon.xshellmenu.XShellMenuMainClass; import it.xargon.xshellmenu.api.XSPlatform; import it.xargon.xshellmenu.api.XSPlatformResource; import it.xargon.xshellmenu.res.Resources;
2,270
package it.xargon.xshellmenu.misc; public class XSGuiPlatform implements XSPlatform { private static final String REGQUERY_UTIL = "reg query "; private static final String REGDWORD_TOKEN = "REG_DWORD"; private static final String DARK_THEME_CMD = REGQUERY_UTIL + "\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"" + " /v SystemUsesLightTheme"; private static class StreamReader extends Thread { private InputStream is; private StringWriter sw; StreamReader(InputStream is) { this.is = is; sw = new StringWriter(); } public void run() { try { int c; while ((c = is.read()) != -1) sw.write(c); } catch (IOException e) { ; } } String getResult() { return sw.toString(); } } private ScheduledExecutorService internalTaskScheduler; private ExecutorService iconFetcherScheduler; public XSGuiPlatform() { internalTaskScheduler = Executors.newSingleThreadScheduledExecutor(); iconFetcherScheduler = Executors.newWorkStealingPool(); } @Override public OperatingSystem getOperatingSystem() { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { return OperatingSystem.WINDOWS; } else if (os.indexOf("mac") >= 0) { return OperatingSystem.MACOS; } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { return OperatingSystem.LINUX; } else if (os.indexOf("sunos") >= 0) { return OperatingSystem.SOLARIS; } else { return OperatingSystem.NONE; } } @Override public void abortApplication(String errorMessage, Exception ex) { ex.printStackTrace(); String abortMessage = errorMessage + "\n\n" + ex.getClass().getName() + ": " + ex.getMessage(); showErrorMessage(abortMessage, true); XShellMenuMainClass.exitApplication(255); } @Override public void showErrorMessage(String errorMessage, boolean wait) { Runnable showTask = () -> { JOptionPane.showMessageDialog( null, errorMessage, "XShellMenu", JOptionPane.ERROR_MESSAGE); }; if (wait) { if (SwingUtilities.isEventDispatchThread()) { showTask.run(); } else { try { SwingUtilities.invokeAndWait(showTask); } catch (InvocationTargetException | InterruptedException ex) { ex.printStackTrace(); } } } else SwingUtilities.invokeLater(showTask); } @Override public boolean isDarkModeSystemTheme() { switch(getOperatingSystem()) { case WINDOWS: return isWindowsDarkMode(); case MACOS: return isMacOsDarkMode(); default: return false; } } private boolean isMacOsDarkMode() { try { boolean isDarkMode = false; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("defaults read -g AppleInterfaceStyle"); InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader rd = new BufferedReader(is); String line; while((line = rd.readLine()) != null) { if (line.equals("Dark")) { isDarkMode = true; } } int rc = process.waitFor(); return 0 == rc && isDarkMode; } catch (IOException | InterruptedException e) { return false; } } private boolean isWindowsDarkMode() { try { Process process = Runtime.getRuntime().exec(DARK_THEME_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGDWORD_TOKEN); if (p == -1) { return false; } // 1 == Light Mode, 0 == Dark Mode String temp = result.substring(p + REGDWORD_TOKEN.length()).trim(); return ((Integer.parseInt(temp.substring("0x".length()), 16))) == 0; } catch (Exception e) { e.printStackTrace(); showErrorMessage("Exception while invoking \"reg\" utility: " + e.getMessage(), true); return false; } } @Override
package it.xargon.xshellmenu.misc; public class XSGuiPlatform implements XSPlatform { private static final String REGQUERY_UTIL = "reg query "; private static final String REGDWORD_TOKEN = "REG_DWORD"; private static final String DARK_THEME_CMD = REGQUERY_UTIL + "\"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize\"" + " /v SystemUsesLightTheme"; private static class StreamReader extends Thread { private InputStream is; private StringWriter sw; StreamReader(InputStream is) { this.is = is; sw = new StringWriter(); } public void run() { try { int c; while ((c = is.read()) != -1) sw.write(c); } catch (IOException e) { ; } } String getResult() { return sw.toString(); } } private ScheduledExecutorService internalTaskScheduler; private ExecutorService iconFetcherScheduler; public XSGuiPlatform() { internalTaskScheduler = Executors.newSingleThreadScheduledExecutor(); iconFetcherScheduler = Executors.newWorkStealingPool(); } @Override public OperatingSystem getOperatingSystem() { String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { return OperatingSystem.WINDOWS; } else if (os.indexOf("mac") >= 0) { return OperatingSystem.MACOS; } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) { return OperatingSystem.LINUX; } else if (os.indexOf("sunos") >= 0) { return OperatingSystem.SOLARIS; } else { return OperatingSystem.NONE; } } @Override public void abortApplication(String errorMessage, Exception ex) { ex.printStackTrace(); String abortMessage = errorMessage + "\n\n" + ex.getClass().getName() + ": " + ex.getMessage(); showErrorMessage(abortMessage, true); XShellMenuMainClass.exitApplication(255); } @Override public void showErrorMessage(String errorMessage, boolean wait) { Runnable showTask = () -> { JOptionPane.showMessageDialog( null, errorMessage, "XShellMenu", JOptionPane.ERROR_MESSAGE); }; if (wait) { if (SwingUtilities.isEventDispatchThread()) { showTask.run(); } else { try { SwingUtilities.invokeAndWait(showTask); } catch (InvocationTargetException | InterruptedException ex) { ex.printStackTrace(); } } } else SwingUtilities.invokeLater(showTask); } @Override public boolean isDarkModeSystemTheme() { switch(getOperatingSystem()) { case WINDOWS: return isWindowsDarkMode(); case MACOS: return isMacOsDarkMode(); default: return false; } } private boolean isMacOsDarkMode() { try { boolean isDarkMode = false; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("defaults read -g AppleInterfaceStyle"); InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader rd = new BufferedReader(is); String line; while((line = rd.readLine()) != null) { if (line.equals("Dark")) { isDarkMode = true; } } int rc = process.waitFor(); return 0 == rc && isDarkMode; } catch (IOException | InterruptedException e) { return false; } } private boolean isWindowsDarkMode() { try { Process process = Runtime.getRuntime().exec(DARK_THEME_CMD); StreamReader reader = new StreamReader(process.getInputStream()); reader.start(); process.waitFor(); reader.join(); String result = reader.getResult(); int p = result.indexOf(REGDWORD_TOKEN); if (p == -1) { return false; } // 1 == Light Mode, 0 == Dark Mode String temp = result.substring(p + REGDWORD_TOKEN.length()).trim(); return ((Integer.parseInt(temp.substring("0x".length()), 16))) == 0; } catch (Exception e) { e.printStackTrace(); showErrorMessage("Exception while invoking \"reg\" utility: " + e.getMessage(), true); return false; } } @Override
public <T> T getPlatformResource(XSPlatformResource<T> resourceIdentifier) {
2
2023-10-14 16:43:45+00:00
4k
FOBshippingpoint/ncu-punch-clock
src/main/java/com/sdovan1/ncupunchclock/Initializer.java
[ { "identifier": "Passcode", "path": "src/main/java/com/sdovan1/ncupunchclock/passcode/Passcode.java", "snippet": "@Entity\n@Data\n@NoArgsConstructor\n@Table\npublic class Passcode {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @Column(nullable = false, unique = true)\n private String passcode;\n\n public Passcode(String passcode) {\n this.passcode = passcode;\n }\n}" }, { "identifier": "PasscodeRepository", "path": "src/main/java/com/sdovan1/ncupunchclock/passcode/PasscodeRepository.java", "snippet": "public interface PasscodeRepository extends CrudRepository<Passcode, Long> {\n Optional<Passcode> findByPasscode(String passcode);\n\n void deleteByPasscode(String passcode);\n}" }, { "identifier": "Punch", "path": "src/main/java/com/sdovan1/ncupunchclock/schedule/Punch.java", "snippet": "@Entity\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@ToString\npublic class Punch {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n\n @ManyToOne\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @Column(nullable = false)\n private Instant clockInTime;\n\n @Column(nullable = false)\n private Instant clockOutTime;\n\n @Column(nullable = false)\n private String partTimeUsuallyId;\n\n private String jobName;\n\n @Column(nullable = false)\n private String jobDescription;\n\n @Enumerated(EnumType.ORDINAL)\n private ClockInOutStatus status;\n\n @Transient\n public static final ZoneId TIME_ZONE = ZoneId.of(\"Asia/Taipei\");\n\n public static enum ClockInOutStatus {\n PENDING(\"待簽到\"),\n EXPIRED(\"已過期\"),\n CLOCK_IN_SUCCESS(\"簽到成功\"),\n CLOCK_OUT_SUCCESS(\"簽退成功\"),\n CLOCK_IN_FAILED(\"簽到失敗\"),\n CLOCK_OUT_FAILED(\"簽退失敗\");\n\n final String name;\n\n ClockInOutStatus(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n }\n\n public static String partTimeUsuallyIdToUrl(String partTimeUsuallyId) {\n return \"https://cis.ncu.edu.tw/HumanSys/student/stdSignIn/create?ParttimeUsuallyId=\" + partTimeUsuallyId;\n }\n\n public String getPartTimeUsuallyUrl() {\n return partTimeUsuallyIdToUrl(partTimeUsuallyId);\n }\n\n public void resetStatus() {\n if (status == ClockInOutStatus.PENDING && isAfterClockInTime() && isAfterClockOutTime()) {\n this.status = ClockInOutStatus.EXPIRED;\n }\n }\n\n public String getJobName() {\n if (jobName == null || jobName.isEmpty()) {\n return partTimeUsuallyId;\n } else {\n return jobName;\n }\n }\n\n public boolean isAfterClockInTime() {\n return Instant.now().isAfter(clockInTime);\n }\n\n public boolean isAfterClockOutTime() {\n return Instant.now().isAfter(clockOutTime);\n }\n\n public boolean isEditable() {\n return getStatus() == ClockInOutStatus.PENDING;\n }\n\n public static String getPartTimeUsuallyIdFromUrl(String partTimeUrl) {\n var pattern = java.util.regex.Pattern.compile(\"ParttimeUsuallyId=([^&]+)\");\n var matcher = pattern.matcher(partTimeUrl);\n String partTimeUsuallyId;\n if (matcher.find()) {\n partTimeUsuallyId = matcher.group(1);\n } else {\n throw new RuntimeException(\"簽到工作/計畫網址必須包含ParttimeUsuallyId參數\");\n }\n return partTimeUsuallyId;\n }\n}" }, { "identifier": "PunchRepository", "path": "src/main/java/com/sdovan1/ncupunchclock/schedule/PunchRepository.java", "snippet": "public interface PunchRepository extends ListCrudRepository<Punch, Long> {\n List<Punch> findByUserOrderByStatusAscClockInTime(User user);\n List<Punch> findByUser_UsernameOrderByStatusAscClockInTime(String username);\n List<Punch> findAllByOrderByStatusAscClockInTime();\n}" }, { "identifier": "PunchScheduler", "path": "src/main/java/com/sdovan1/ncupunchclock/schedule/PunchScheduler.java", "snippet": "@Component\n@Slf4j\npublic class PunchScheduler {\n @Autowired\n private TaskScheduler taskScheduler;\n @Autowired\n private BytesEncryptor encryptor;\n\n private final Map<Task, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();\n\n @Autowired\n private PunchRepository repository;\n @Autowired\n private Publisher publisher;\n @Autowired\n private PunchAgentFactory punchAgentFactory;\n\n public PunchScheduler(TaskScheduler taskScheduler) {\n this.taskScheduler = taskScheduler;\n }\n\n\n public void cancelScheduledPunch(Punch punch, TaskType taskType) {\n var task = new Task(punch, taskType);\n var scheduledFuture = taskMap.get(task);\n if (scheduledFuture != null) {\n scheduledFuture.cancel(false);\n taskMap.remove(task);\n log.info(\"Canceled {} {} at {}\", punch, taskType, taskType == TaskType.CLOCK_IN ? punch.getClockInTime() : punch.getClockOutTime());\n }\n }\n\n public void cancelScheduledPunch(Punch punch) {\n cancelScheduledPunch(punch, TaskType.CLOCK_IN);\n cancelScheduledPunch(punch, TaskType.CLOCK_OUT);\n }\n\n public void cancelAllScheduledPunches(List<Punch> punches) {\n punches.forEach(this::cancelScheduledPunch);\n }\n\n public void schedule(Punch punch, TaskType taskType) {\n var task = new Task(punch, taskType);\n var future = taskScheduler.schedule(() -> {\n var partTimeUsuallyId = punch.getPartTimeUsuallyId();\n var username = punch.getUser().getUsername();\n var password = new String(encryptor.decrypt(Hex.decode(punch.getUser().getPass())));\n var agent = punchAgentFactory.create(partTimeUsuallyId, username, password);\n try {\n if (taskType == TaskType.CLOCK_IN) {\n agent.login().clockIn();\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_IN_SUCCESS);\n } else {\n agent.login().clockOut(punch.getJobDescription());\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_OUT_SUCCESS);\n }\n } catch (PunchLoginFailedException e) {\n if (taskType == TaskType.CLOCK_IN) {\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_IN_FAILED);\n log.error(\"Schedule {} clock in failed with exception: \", punch, e);\n } else {\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_OUT_FAILED);\n log.error(\"Schedule {} clock out failed with exception: \", punch, e);\n }\n } catch (PunchClockInFailedException e) {\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_IN_FAILED);\n log.error(\"Schedule {} clock in failed with exception: \", punch, e);\n } catch (PunchClockOutFailedException e) {\n punch.setStatus(Punch.ClockInOutStatus.CLOCK_OUT_FAILED);\n log.error(\"Schedule {} clock out failed with exception: \", punch, e);\n } finally {\n repository.save(punch);\n var punchEvent = new IftttPunchEvent(punch);\n agent.getDriver().quit();\n taskMap.remove(task);\n\n publisher.trigger(punchEvent);\n }\n }, taskType == TaskType.CLOCK_IN ? punch.getClockInTime() : punch.getClockOutTime());\n taskMap.put(task, future);\n log.info(\"Scheduled {} {} at {}\", punch, taskType, taskType == TaskType.CLOCK_IN ? punch.getClockInTime() : punch.getClockOutTime());\n }\n\n public void schedule(Punch punch) {\n schedule(punch, TaskType.CLOCK_IN);\n schedule(punch, TaskType.CLOCK_OUT);\n }\n\n public void scheduleAll(List<Punch> punches) {\n // Schedule clock in for punches that are not clocked in yet\n punches.stream()\n .filter(punch -> punch.getStatus() == Punch.ClockInOutStatus.PENDING)\n .filter(punch -> !punch.isAfterClockInTime())\n .forEach(punch -> {\n schedule(punch, TaskType.CLOCK_IN);\n schedule(punch, TaskType.CLOCK_OUT);\n });\n\n // Schedule clock out for punches that are already clocked in\n punches.stream()\n .filter(punch -> punch.getStatus() == Punch.ClockInOutStatus.CLOCK_IN_SUCCESS)\n .filter(punch -> !punch.isAfterClockOutTime())\n .forEach(punch -> schedule(punch, TaskType.CLOCK_OUT));\n }\n\n public record Task(Punch punch, TaskType taskType) {\n }\n\n public enum TaskType {\n CLOCK_IN,\n CLOCK_OUT\n }\n}" }, { "identifier": "User", "path": "src/main/java/com/sdovan1/ncupunchclock/user/User.java", "snippet": "@Entity\n@Data\n@NoArgsConstructor\n@Table(name = \"users\")\n@ToString(onlyExplicitlyIncluded = true)\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @ToString.Include\n private Long id;\n\n @ToString.Include\n @Column(nullable = false, unique = true)\n private String username;\n\n @Column(nullable = false)\n private String password;\n\n @Column\n private String pass;\n\n @Transient\n private String confirmPassword;\n\n @Transient\n private String passcode;\n\n @OneToMany\n @OrderBy(\"clockInTime\")\n private List<Punch> punches;\n\n public User(String username, String password) {\n this.username = username;\n this.password = password;\n }\n\n public User(User user) {\n this.id = user.getId();\n this.username = user.getUsername();\n this.password = user.getPassword();\n this.pass = user.getPass();\n this.punches = user.getPunches();\n }\n\n}" }, { "identifier": "UserRepository", "path": "src/main/java/com/sdovan1/ncupunchclock/user/UserRepository.java", "snippet": "public interface UserRepository extends CrudRepository<User, Long> {\n Optional<User> findByUsername(String username);\n}" } ]
import com.sdovan1.ncupunchclock.passcode.Passcode; import com.sdovan1.ncupunchclock.passcode.PasscodeRepository; import com.sdovan1.ncupunchclock.schedule.Punch; import com.sdovan1.ncupunchclock.schedule.PunchRepository; import com.sdovan1.ncupunchclock.schedule.PunchScheduler; import com.sdovan1.ncupunchclock.user.User; import com.sdovan1.ncupunchclock.user.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component;
2,711
package com.sdovan1.ncupunchclock; @Component @Slf4j public class Initializer { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PunchRepository punchRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired
package com.sdovan1.ncupunchclock; @Component @Slf4j public class Initializer { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private PunchRepository punchRepository; @Autowired private PasscodeRepository passcodeRepository; @Autowired
private PunchScheduler punchScheduler;
4
2023-10-12 15:41:58+00:00
4k
davidsaltacc/shadowclient
src/main/java/net/shadowclient/main/module/modules/combat/KillAura.java
[ { "identifier": "Event", "path": "src/main/java/net/shadowclient/main/event/Event.java", "snippet": "public abstract class Event {\n public boolean cancelled = false;\n public void cancel() {\n this.cancelled = true;\n }\n public void uncancel() {\n this.cancelled = false;\n }\n}" }, { "identifier": "PreTickEvent", "path": "src/main/java/net/shadowclient/main/event/events/PreTickEvent.java", "snippet": "public class PreTickEvent extends Event {\n}" }, { "identifier": "Module", "path": "src/main/java/net/shadowclient/main/module/Module.java", "snippet": "public abstract class Module {\n\n public final ModuleCategory category;\n public final String moduleName;\n public final String friendlyName;\n public final String description;\n\n public KeyBinding keybinding;\n\n public ModuleButton moduleButton = null;\n\n public boolean enabled;\n\n public List<Setting> getSettings() {\n return settings;\n }\n\n public void addSetting(Setting setting) {\n settings.add(setting);\n }\n\n public void addSettings(Setting...settings) {\n for (Setting setting : settings) {\n addSetting(setting);\n }\n }\n\n public final List<Setting> settings = new ArrayList<>();\n\n public final MinecraftClient mc = MinecraftClient.getInstance();\n\n public Module(String name, String friendlyName, String description, ModuleCategory category) {\n moduleName = name;\n this.category = category;\n this.friendlyName = friendlyName;\n this.description = description;\n }\n\n public void setEnabled() {\n this.enabled = true;\n this.onEnable();\n if (this.getClass().isAnnotationPresent(OneClick.class)) {\n setDisabled();\n }\n }\n public void setDisabled() {\n this.enabled = false;\n this.onDisable();\n }\n\n public void setEnabled(boolean event) {\n if (event) {\n this.onEnable();\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event) {\n if (event) {\n this.onDisable();\n }\n this.enabled = false;\n }\n\n public boolean showMessage = true;\n\n public void setEnabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onEnable();\n showMessage = msgOld;\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onDisable();\n showMessage = msgOld;\n }\n this.enabled = false;\n }\n\n public void toggle() {\n if (enabled) {\n setDisabled();\n return;\n }\n setEnabled();\n }\n\n public void onEnable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onDisable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onEvent(Event event) {}\n\n public void postInit() {}\n\n}" }, { "identifier": "ModuleCategory", "path": "src/main/java/net/shadowclient/main/module/ModuleCategory.java", "snippet": "public enum ModuleCategory {\n COMBAT(\"Combat\"),\n PLAYER(\"Player\"),\n MOVEMENT(\"Movement\"),\n WORLD(\"World\"),\n RENDER(\"Render\"),\n FUN(\"Fun\"),\n OTHER(\"Other\"),\n MENUS(\"Menus\");\n\n public final String name;\n\n ModuleCategory(String name) {\n this.name = name;\n }\n}" }, { "identifier": "BooleanSetting", "path": "src/main/java/net/shadowclient/main/setting/settings/BooleanSetting.java", "snippet": "public class BooleanSetting extends Setting {\n\n public BooleanSetting(String name, boolean defaultValue) {\n super(name, defaultValue);\n }\n}" }, { "identifier": "RotationUtils", "path": "src/main/java/net/shadowclient/main/util/RotationUtils.java", "snippet": "public class RotationUtils {\n\n private static final MinecraftClient mc = MinecraftClient.getInstance();\n\n public static void rotateToVec3d(Vec3d vec3d) {\n float[] needed = RotationUtils.getNeededRotations(vec3d);\n ClientPlayerEntity player = mc.player;\n\n float currentWrapped = MathHelper.wrapDegrees(player.getYaw());\n float intendedWrapped = MathHelper.wrapDegrees(needed[0]);\n\n float change = MathHelper.wrapDegrees(intendedWrapped - currentWrapped);\n\n float yaw = player.getYaw() + change;\n float pitch = needed[1];\n\n mc.player.networkHandler.sendPacket(new PlayerMoveC2SPacket.LookAndOnGround(yaw, pitch, mc.player.isOnGround()));\n }\n\n public static float[] getNeededRotations(Vec3d vec) {\n Vec3d eyesPos = new Vec3d(mc.player.getX(), mc.player.getY() + mc.player.getEyeHeight(mc.player.getPose()), mc.player.getZ());\n\n double diffX = vec.x - eyesPos.x;\n double diffY = vec.y - eyesPos.y;\n double diffZ = vec.z - eyesPos.z;\n\n double diffXZ = Math.sqrt(diffX * diffX + diffZ * diffZ);\n\n float yaw = (float) Math.toDegrees(Math.atan2(diffZ, diffX)) - 90F;\n float pitch = (float) -Math.toDegrees(Math.atan2(diffY, diffXZ));\n\n return new float[]{yaw, pitch};\n }\n\n}" }, { "identifier": "WorldUtils", "path": "src/main/java/net/shadowclient/main/util/WorldUtils.java", "snippet": "public class WorldUtils {\n public static boolean lineOfSight(Vec3d from, Vec3d to) {\n RaycastContext context = new RaycastContext(from, to, RaycastContext.ShapeType.COLLIDER, RaycastContext.FluidHandling.NONE, SCMain.mc.player);\n return SCMain.mc.world.raycast(context).getType() == HitResult.Type.MISS;\n }\n public static boolean lineOfSight(Entity from, Vec3d to) {\n return lineOfSight(from.getEyePos(), to);\n }\n public static boolean lineOfSight(Vec3d from, Entity to) {\n return lineOfSight(from, to.getEyePos());\n }\n public static boolean lineOfSight(Entity from, Entity to) {\n return lineOfSight(from.getEyePos(), to.getEyePos());\n }\n\n public static BlockHitResult raycast(Vec3d from, Vec3d to) {\n RaycastContext context = new RaycastContext(from, to, RaycastContext.ShapeType.COLLIDER, RaycastContext.FluidHandling.NONE, SCMain.mc.player);\n return SCMain.mc.world.raycast(context);\n }\n}" } ]
import net.minecraft.client.gui.screen.ingame.HandledScreen; import net.minecraft.entity.LivingEntity; import net.minecraft.util.Hand; import net.shadowclient.main.annotations.EventListener; import net.shadowclient.main.annotations.SearchTags; import net.shadowclient.main.event.Event; import net.shadowclient.main.event.events.PreTickEvent; import net.shadowclient.main.module.Module; import net.shadowclient.main.module.ModuleCategory; import net.shadowclient.main.setting.settings.BooleanSetting; import net.shadowclient.main.util.RotationUtils; import net.shadowclient.main.util.WorldUtils;
1,763
package net.shadowclient.main.module.modules.combat; @EventListener({PreTickEvent.class}) @SearchTags({"killaura", "kill aura", "auto kill", "auto hit"})
package net.shadowclient.main.module.modules.combat; @EventListener({PreTickEvent.class}) @SearchTags({"killaura", "kill aura", "auto kill", "auto hit"})
public class KillAura extends Module {
2
2023-10-07 06:55:12+00:00
4k
MRkto/MappetVoice
src/main/java/mrkto/mvoice/proxy/ServerProxy.java
[ { "identifier": "MappetVoice", "path": "src/main/java/mrkto/mvoice/MappetVoice.java", "snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String MOD_ID = \"mvoice\";\n public static final String NAME = \"MappetVoice\";\n public static final String VERSION = \"0.0.12\";\n @SidedProxy(serverSide = \"mrkto.mvoice.proxy.ServerProxy\", clientSide = \"mrkto.mvoice.proxy.ClientProxy\")\n public static ServerProxy proxy;\n @Mod.Instance(MOD_ID)\n public static MappetVoice INSTANCE;\n public static Logger logger;\n public static VoiceManager voice;\n public static MinecraftServer server;\n public static File config;\n public static Item radio = new RadioItem();\n @SideOnly(Side.CLIENT)\n public static IAudioSystemManager AudioManager;\n //configuration\n public static ValueBoolean push;\n public static ValueBoolean opus;\n public static ValueInt volumes;\n public static ValueInt volumem;\n public static ValueFloat fadetime;\n public static ValueFloat numofaction;\n public static ValueInt range;\n public static ValueBoolean radioItem;\n public static ValueBoolean hearOther;\n public static ValueBoolean hearOtherRadio;\n public static ValueBoolean onRadioSound;\n public static ValueBoolean offRadioSound;\n public static ValueBoolean needInArm;\n public static ValueBoolean noise;\n public static ValueBoolean switchRadioSound;\n public static ValueBoolean onRangeNoise;\n public static ValueInt maxNoise;\n public static ValueInt minNoise;\n public static ValueInt NoiseRange;\n public static ValueBoolean voiceaction;\n\n @SubscribeEvent\n public void onConfigRegister(RegisterConfigEvent event) {\n\n ConfigBuilder builder = event.createBuilder(MOD_ID);\n\n builder.category(\"client\").register(new ValueVoiceButtons(\"buttons\").clientSide()).getCategory();\n push = builder.getBoolean(\"push\", true);\n push.clientSide();\n volumes = builder.getInt(\"volumes\", 100, 0, 200);\n volumes.clientSide();\n volumem = builder.getInt(\"volumem\", 100, 0, 200);\n volumem.clientSide();\n fadetime = builder.getFloat(\"fadetime\", 0.1f, 0.01f, 2);\n fadetime.clientSide();\n voiceaction = builder.getBoolean(\"voiceAction\", false);\n voiceaction.clientSide();\n numofaction = builder.getFloat(\"numofaction\", 0.3f, 0.0f, 1.0f);\n numofaction.clientSide();\n builder.category(\"general\");\n range = builder.getInt(\"hearrange\", 25, 1, 200);\n range.syncable();\n opus = builder.category(\"Voicesettings\").getBoolean(\"calcSoundOnServer\", false);\n builder.category(\"radios\");\n onRadioSound = builder.getBoolean(\"onRadioSound\", true);\n onRadioSound.syncable();\n offRadioSound = builder.getBoolean(\"offRadioSound\", true);\n offRadioSound.syncable();\n switchRadioSound = builder.getBoolean(\"switchRadioSound\", true);\n switchRadioSound.syncable();\n onRangeNoise = builder.getBoolean(\"onRangeNoise\", true);\n onRangeNoise.syncable();\n noise = builder.getBoolean(\"noise\", true);\n noise.syncable();\n minNoise = builder.getInt(\"minNoise\", 50, 0, 100);\n minNoise.syncable();\n maxNoise = builder.getInt(\"maxNoise\", 90, 0, 100);\n maxNoise.syncable();\n NoiseRange = builder.getInt(\"NoiseRange\", 50, 0, 10000);\n NoiseRange.syncable();\n radioItem = builder.getBoolean(\"useItem\", true);\n radioItem.syncable();\n hearOther = builder.getBoolean(\"hearOther\", true);\n hearOther.syncable();\n hearOtherRadio = builder.getBoolean(\"hearOtherRadio\", true);\n hearOtherRadio.syncable();\n needInArm = builder.getBoolean(\"needInArm\", true);\n needInArm.syncable();\n\n }\n @EventHandler\n public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException {\n logger = event.getModLog();\n config = event.getModConfigurationDirectory();\n\n McLib.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new mrkto.mvoice.EventHandler());\n Dispatcher.register();\n CapabilityManager.INSTANCE.register(IProfile.class, new ProfileStorage(), Profile::new);\n\n proxy.preInit(event);\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n MVIcons.register();\n\n proxy.init(event);\n }\n\n @EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n }\n\n @EventHandler\n public void serverStart(FMLServerStartingEvent event) {\n voice = new VoiceManager();\n server = event.getServer();\n logger.info(\"hello world!\");\n\n\n }\n\n\n @EventHandler\n public void serverStop(FMLServerStoppingEvent event){\n voice = null;\n server = null;\n logger.info(\"gg\");\n\n\n }\n @SideOnly(Side.CLIENT)\n @EventHandler\n public void disableMod(FMLModDisabledEvent event){\n AudioManager.fullTerminate();\n SpeakerListener.instance.close();\n logger.info(\"bye\");\n }\n @SubscribeEvent\n public static void onRegistryItem(Register<Item> e){\n e.getRegistry().register(radio);\n }\n @SubscribeEvent\n @SideOnly(Side.CLIENT)\n public static void onRegistryModel(ModelRegistryEvent e) {\n registryModel(radio);\n }\n @SideOnly(Side.CLIENT)\n private static void registryModel(Item item) {\n final ResourceLocation regName = item.getRegistryName();\n final ModelResourceLocation mrl = new ModelResourceLocation(regName != null ? regName : RLUtils.create(\"\"), \"inventory\");\n ModelBakery.registerItemVariants(item, mrl);\n ModelLoader.setCustomModelResourceLocation(item, 0, mrl);\n\n }\n}" }, { "identifier": "AudioUtils", "path": "src/main/java/mrkto/mvoice/client/AudioUtils.java", "snippet": "public class AudioUtils {\n public static final AudioFormat FORMATM = new AudioFormat(48000, 16, 1, true, false);\n public static final AudioFormat FORMATS = new AudioFormat(48000, 16, 2, true, false);\n private static final OpusCodec codec = OpusCodec.newBuilder().withBitrate(96000).build();\n public static Mixer findMixer(String name, Line.Info lineinfo){\n Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();\n Mixer omixer = null;\n // Перебираем аудиоустройства и ищем микрофоны\n for (Mixer.Info info : mixerInfos) {\n Mixer mixer = AudioSystem.getMixer(info);\n if (mixer.isLineSupported(lineinfo)) {\n if(info.getName().equals(name)){\n return mixer;\n }\n if(omixer == null){\n omixer = mixer;\n }\n }\n }\n return omixer;\n }\n public static ArrayList<String> findAudioDevices(Line.Info lineInfo)\n {\n final ArrayList<String> list = new ArrayList<>();\n for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo())\n {\n final Mixer mixer = AudioSystem.getMixer(mixerInfo);\n if (mixer.isLineSupported(lineInfo))\n {\n list.add(mixerInfo.getName());\n }\n }\n return list;\n }\n public static byte[] decode(byte[] data){\n return codec.decodeFrame(data);\n }\n public static byte[] encode(byte[] data){\n return codec.encodeFrame(data);\n }\n public static boolean loadOpus()\n {\n try\n {\n OpusCodec.setupWithTemporaryFolder();\n OpusCodec testCodec = OpusCodec.createDefault();\n testCodec.decodeFrame(new byte[123]);\n return true;\n } catch (Throwable e)\n {\n e.printStackTrace();\n return false;\n }\n }\n public static byte[] mergeSounds(byte[] sound1, byte[] sound2, float volumeBalance){\n int length = Math.min(sound1.length, sound2.length);\n byte[] result = new byte[length];\n\n for (int i = 0; i < length; i++) {\n float sample1 = sound1[i] / 128.0f;\n float sample2 = sound2[i] / 128.0f;\n\n float mixed = sample1 * volumeBalance + sample2 * (1.0f - volumeBalance);\n\n mixed = Math.max(-1.0f, Math.min(1.0f, mixed));\n\n result[i] = (byte)(mixed * 128.0f);\n }\n\n return result;\n }\n private static float lastPeak = 0f;\n public static float calcVolume(byte[] buf) {\n int len = buf.length / 2;\n float[] samples = new float[len];\n\n for (int i = 0, s = 0; i < buf.length; ) {\n int sample = 0;\n\n sample |= buf[i++] & 0xFF;\n sample |= buf[i++] << 8;\n\n samples[s++] = sample / 32768f;\n }\n\n float peak = 0f;\n for (float sample : samples) {\n peak = Math.max(peak, Math.abs(sample));\n }\n\n if (lastPeak > peak) {\n peak = lastPeak * 0.875f;\n }\n\n lastPeak = peak;\n return lastPeak;\n }\n public static byte[] monoToStereo(byte[] data, double leftVolume, double rightVolume) {\n byte[] stereo = new byte[data.length * 2];\n byte[] datal = adjustVolume(data, leftVolume);\n byte[] datar = adjustVolume(data, rightVolume);\n for (int i = 0; i < data.length; i += 2) {\n\n stereo[i*2] = datal[i];\n stereo[i*2 + 1] = datal[i+1];\n stereo[i*2 + 2] = datar[i];\n stereo[i*2 + 3] = datar[i+1];\n\n }\n return stereo;\n }\n public static byte[] monoToStereo(byte[] data) {\n byte[] stereo = new byte[data.length * 2];\n\n for (int i = 0; i < data.length; i += 2) {\n\n stereo[i*2] = data[i];\n stereo[i*2 + 1] = data[i+1];\n stereo[i*2 + 2] = data[i];\n stereo[i*2 + 3] = data[i+1];\n\n }\n return stereo;\n }\n public static byte[] adjustVolume(byte[] audioSamples, double volume) {\n byte[] array = new byte[audioSamples.length];\n for (int i = 0; i < array.length; i += 2) {\n short buf1 = audioSamples[i + 1];\n short buf2 = audioSamples[i];\n buf1 = (short) ((buf1 & 0xff) << 8);\n buf2 = (short) (buf2 & 0xff);\n short res = (short) (buf1 | buf2);\n res = (short) (res * volume);\n array[i] = (byte) res;\n array[i + 1] = (byte) (res >> 8);\n\n }\n return array;\n }\n}" }, { "identifier": "OpusNotLoadedException", "path": "src/main/java/mrkto/mvoice/utils/other/OpusNotLoadedException.java", "snippet": "public class OpusNotLoadedException extends Exception{\n public OpusNotLoadedException() {\n\n super();\n }\n public OpusNotLoadedException(String message) {\n super(message);\n }\n}" } ]
import mrkto.mvoice.MappetVoice; import mrkto.mvoice.client.AudioUtils; import mrkto.mvoice.utils.other.OpusNotLoadedException; import net.labymod.opus.OpusCodec; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import javax.annotation.Nullable;
3,095
package mrkto.mvoice.proxy; public class ServerProxy{ public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException { MappetVoice.logger.info("server pre-init complete"); } public void init(FMLInitializationEvent event) { MappetVoice.logger.info("server init complete"); } public void postInit(FMLPostInitializationEvent event) { if(MappetVoice.opus.get()){
package mrkto.mvoice.proxy; public class ServerProxy{ public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException { MappetVoice.logger.info("server pre-init complete"); } public void init(FMLInitializationEvent event) { MappetVoice.logger.info("server init complete"); } public void postInit(FMLPostInitializationEvent event) { if(MappetVoice.opus.get()){
AudioUtils.loadOpus();
1
2023-10-14 19:20:12+00:00
4k
batmatt/cli-rpg-java
src/com/clirpg/game/Quest.java
[ { "identifier": "Civillian", "path": "src/com/clirpg/characters/Civillian.java", "snippet": "public class Civillian extends Entity implements Talk{\n final static boolean friendly = true;\n String job;\n\n public Civillian(String name, String job)\n {\n super(name);\n this.job = job;\n this.health = 100;\n }\n\n public Civillian(String name, String job, int health)\n {\n super(name, health);\n this.job = job;\n }\n\n public void talk()\n {\n System.out.println(ConsoleColors.GREEN + \"\\n\" + toString() + \": I saw enemies. Do you want to fight them? You would get 10 coins for it\\n\" + ConsoleColors.RESET);\n }\n\n public String toString()\n {\n return this.job + \" \" + this.name; \n }\n\n public void talkEnd()\n {\n System.out.println(ConsoleColors.GREEN + \"\\n\" + toString() + \": Thank you for killing the enemies. Here is your reward.\\n\" + ConsoleColors.RESET);\n }\n}" }, { "identifier": "Player", "path": "src/com/clirpg/characters/Player.java", "snippet": "public class Player extends Entity implements Combat {\n public int attackStrength;\n public int hitProbability;\n public int money;\n public int maxLevelArena;\n\n final boolean friendly = true;\n \n public Player(String name, CharacterClass characterClass)\n {\n super(name);\n money = 100;\n maxLevelArena = 0;\n this.health = characterClass.health;\n this.attackStrength = characterClass.attackStrength;\n this.hitProbability = characterClass.hitProbability; \n }\n\n @Override\n public String toString() {\n return \"Name: \" + this.name + \", Health: \" + health + \", Attack Strength: \" + attackStrength + \", Hit Probability: \" + hitProbability + \", Money: \" + money;\n }\n\n public int combat()\n {\n int randomNumber;\n Random random = new Random();\n randomNumber = random.nextInt(100);\n //System.out.println(\"rng: \" + randomNumber);\n if(randomNumber < this.hitProbability)\n {\n System.out.println(\"Attack hits for \" + this.attackStrength + \" damage\");\n return this.attackStrength;\n }\n else\n {\n System.out.println(\"Attack fails\");\n }\n return 0;\n }\n}" }, { "identifier": "ConsoleColors", "path": "src/com/utils/ConsoleColors.java", "snippet": "public class ConsoleColors {\n // Reset\n public static final String RESET = \"\\033[0m\"; // Text Reset\n\n // Regular Colors\n public static final String BLACK = \"\\033[0;30m\"; // BLACK\n public static final String RED = \"\\033[0;31m\"; // RED\n public static final String GREEN = \"\\033[0;32m\"; // GREEN\n public static final String YELLOW = \"\\033[0;33m\"; // YELLOW\n public static final String BLUE = \"\\033[0;34m\"; // BLUE\n public static final String PURPLE = \"\\033[0;35m\"; // PURPLE\n public static final String CYAN = \"\\033[0;36m\"; // CYAN\n public static final String WHITE = \"\\033[0;37m\"; // WHITE\n\n // Bold\n public static final String BLACK_BOLD = \"\\033[1;30m\"; // BLACK\n public static final String RED_BOLD = \"\\033[1;31m\"; // RED\n public static final String GREEN_BOLD = \"\\033[1;32m\"; // GREEN\n public static final String YELLOW_BOLD = \"\\033[1;33m\"; // YELLOW\n public static final String BLUE_BOLD = \"\\033[1;34m\"; // BLUE\n public static final String PURPLE_BOLD = \"\\033[1;35m\"; // PURPLE\n public static final String CYAN_BOLD = \"\\033[1;36m\"; // CYAN\n public static final String WHITE_BOLD = \"\\033[1;37m\"; // WHITE\n\n // Underline\n public static final String BLACK_UNDERLINED = \"\\033[4;30m\"; // BLACK\n public static final String RED_UNDERLINED = \"\\033[4;31m\"; // RED\n public static final String GREEN_UNDERLINED = \"\\033[4;32m\"; // GREEN\n public static final String YELLOW_UNDERLINED = \"\\033[4;33m\"; // YELLOW\n public static final String BLUE_UNDERLINED = \"\\033[4;34m\"; // BLUE\n public static final String PURPLE_UNDERLINED = \"\\033[4;35m\"; // PURPLE\n public static final String CYAN_UNDERLINED = \"\\033[4;36m\"; // CYAN\n public static final String WHITE_UNDERLINED = \"\\033[4;37m\"; // WHITE\n\n // Background\n public static final String BLACK_BACKGROUND = \"\\033[40m\"; // BLACK\n public static final String RED_BACKGROUND = \"\\033[41m\"; // RED\n public static final String GREEN_BACKGROUND = \"\\033[42m\"; // GREEN\n public static final String YELLOW_BACKGROUND = \"\\033[43m\"; // YELLOW\n public static final String BLUE_BACKGROUND = \"\\033[44m\"; // BLUE\n public static final String PURPLE_BACKGROUND = \"\\033[45m\"; // PURPLE\n public static final String CYAN_BACKGROUND = \"\\033[46m\"; // CYAN\n public static final String WHITE_BACKGROUND = \"\\033[47m\"; // WHITE\n\n // High Intensity\n public static final String BLACK_BRIGHT = \"\\033[0;90m\"; // BLACK\n public static final String RED_BRIGHT = \"\\033[0;91m\"; // RED\n public static final String GREEN_BRIGHT = \"\\033[0;92m\"; // GREEN\n public static final String YELLOW_BRIGHT = \"\\033[0;93m\"; // YELLOW\n public static final String BLUE_BRIGHT = \"\\033[0;94m\"; // BLUE\n public static final String PURPLE_BRIGHT = \"\\033[0;95m\"; // PURPLE\n public static final String CYAN_BRIGHT = \"\\033[0;96m\"; // CYAN\n public static final String WHITE_BRIGHT = \"\\033[0;97m\"; // WHITE\n\n // Bold High Intensity\n public static final String BLACK_BOLD_BRIGHT = \"\\033[1;90m\"; // BLACK\n public static final String RED_BOLD_BRIGHT = \"\\033[1;91m\"; // RED\n public static final String GREEN_BOLD_BRIGHT = \"\\033[1;92m\"; // GREEN\n public static final String YELLOW_BOLD_BRIGHT = \"\\033[1;93m\";// YELLOW\n public static final String BLUE_BOLD_BRIGHT = \"\\033[1;94m\"; // BLUE\n public static final String PURPLE_BOLD_BRIGHT = \"\\033[1;95m\";// PURPLE\n public static final String CYAN_BOLD_BRIGHT = \"\\033[1;96m\"; // CYAN\n public static final String WHITE_BOLD_BRIGHT = \"\\033[1;97m\"; // WHITE\n\n // High Intensity backgrounds\n public static final String BLACK_BACKGROUND_BRIGHT = \"\\033[0;100m\";// BLACK\n public static final String RED_BACKGROUND_BRIGHT = \"\\033[0;101m\";// RED\n public static final String GREEN_BACKGROUND_BRIGHT = \"\\033[0;102m\";// GREEN\n public static final String YELLOW_BACKGROUND_BRIGHT = \"\\033[0;103m\";// YELLOW\n public static final String BLUE_BACKGROUND_BRIGHT = \"\\033[0;104m\";// BLUE\n public static final String PURPLE_BACKGROUND_BRIGHT = \"\\033[0;105m\"; // PURPLE\n public static final String CYAN_BACKGROUND_BRIGHT = \"\\033[0;106m\"; // CYAN\n public static final String WHITE_BACKGROUND_BRIGHT = \"\\033[0;107m\"; // WHITE\n}" } ]
import src.com.clirpg.characters.Civillian; import src.com.clirpg.characters.Player; import src.com.utils.ConsoleColors;
2,075
package src.com.clirpg.game; public class Quest { private Player player; public void setPlayer(Player player) { this.player = player; if(healthQuest < 60 ){ healthQuest = player.health + 20; } if(strengthQuest < 10){ strengthQuest = player.attackStrength + 10; } } private int levelArenaQuest; private int healthQuest; private int strengthQuest; private Civillian mayor; public Quest() { levelArenaQuest = 5; healthQuest = 0; strengthQuest = 0; mayor = new Civillian("Thomas", "Mayor"); } public void showQuests(){ checkQuests(); printQuests();
package src.com.clirpg.game; public class Quest { private Player player; public void setPlayer(Player player) { this.player = player; if(healthQuest < 60 ){ healthQuest = player.health + 20; } if(strengthQuest < 10){ strengthQuest = player.attackStrength + 10; } } private int levelArenaQuest; private int healthQuest; private int strengthQuest; private Civillian mayor; public Quest() { levelArenaQuest = 5; healthQuest = 0; strengthQuest = 0; mayor = new Civillian("Thomas", "Mayor"); } public void showQuests(){ checkQuests(); printQuests();
System.out.println(ConsoleColors.GREEN + "\n" + mayor.toString() + ": Come back the next time you have finished one of those quests\n" + ConsoleColors.RESET);
2
2023-10-14 15:38:50+00:00
4k
lukas-mb/ABAP-SQL-Beautifier
ABAP SQL Beautifier/src/com/abap/sql/beautifier/settings/CommasAdder.java
[ { "identifier": "Abap", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Abap.java", "snippet": "public final class Abap {\n\n\t// class to store keywords and stuff\n\t// --> easier to find use with 'where used list'\n\n\tpublic static final List<String> JOINS = Arrays.asList(\"INNER JOIN\", \"JOIN\", \"CROSS JOIN\", \"OUTER JOIN\",\n\t\t\t\"FULL OUTER JOIN\", \"LEFT OUTER JOIN\", \"RIGHT OUTER JOIN\", \"LEFT JOIN\", \"RIGHT JOIN\");\n\n\tpublic static final String ORDERBY = \"ORDER BY\";\n\tpublic static final String SELECT = \"SELECT\";\n\tpublic static final String UPTO = \"UP TO\";\n\tpublic static final String FROM = \"FROM\";\n\tpublic static final String SELECTFROM = \"SELECT FROM\";\n\tpublic static final String SELECT_SINGLE_FROM = \"SELECT SINGLE FROM\";\n\tpublic static final String INTO = \"INTO\";\n\tpublic static final String WHERE = \"WHERE\";\n\tpublic static final String GROUPBY = \"GROUP BY\";\n\tpublic static final String HAVING = \"HAVING\";\n\tpublic static final String FIELDS = \"FIELDS\";\n\tpublic static final String CONNECTION = \"CONNECTION\";\n\tpublic static final String FORALLENTRIES = \"FOR ALL ENTRIES\";\n\tpublic static final String APPENDING = \"APPENDING\";\n\tpublic static final String OFFSET = \"OFFSET\";\n\tpublic static final String COMMENT = \"COMMENT\";\n\tpublic static final String SINGLE = \"SINGLE\";\n\tpublic static final String INTO_COR_FI_OF = \"INTO CORRESPONDING FIELDS\";\n}" }, { "identifier": "Activator", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Activator.java", "snippet": "public class Activator extends AbstractUIPlugin {\n\n\t// The shared instance\n\tprivate static Activator plugin;\n\n\t// The plug-in ID\n\tpublic static final String PLUGIN_ID = \"com.abap.sql.beautifier\"; //$NON-NLS-1$\n\n\t/**\n\t * Returns the shared instance\n\t *\n\t * @return the shared instance\n\t */\n\tpublic static Activator getDefault() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The constructor\n\t */\n\tpublic Activator() {\n\t}\n\n\t@Override\n\tpublic void start(BundleContext context) throws Exception {\n\t\tsuper.start(context);\n\t\tplugin = this;\n\t}\n\n\t@Override\n\tpublic void stop(BundleContext context) throws Exception {\n\t\tplugin = null;\n\t\tsuper.stop(context);\n\t}\n\n}" }, { "identifier": "PreferenceConstants", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java", "snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"COMBINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_SELECT = \"COMBINE_SMALL_SELECT\";\n\n\tpublic static final String COMMAS = \"COMMAS\";\n\n\tpublic static final String ESCAPING = \"ESCAPING\";\n\n\tpublic static final String OPERSTYLE = \"OPERSTYLE\";\n\n\tpublic static final String ORDER_OLD_SYNTAX = \"ORDER_OLD_SYNTAX\";\n\t\n\tpublic static final String ORDER_NEW_SYNTAX = \"ORDER_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL = \"TAB_ALL\";\n\n\tpublic static final String TAB_CONDITIONS = \"TAB_CONDITIONS\";\n\n\tpublic static final String LINE_CHAR_LIMIT = \"LINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS_LIMIT = \"COMBINE_SMALL_JOINS_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS = \"COMBINE_SMALL_JOINS\";\n\n\tpublic static final String TAB_CONDITIONS_NEW_SYNTAX = \"TAB_CONDITIONS_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL_NEW_SYNTAX = \"TAB_ALL_NEW_SYNTAX\";\n\n\tpublic static final String COMMENTSTYLE = \"COMMENTSTYLE\";\n\n}" }, { "identifier": "AbapSqlPart", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/AbapSqlPart.java", "snippet": "public class AbapSqlPart {\n\n\tpublic String name = this.getClass().toString();\n\n\tpublic AbapSqlPart(List<String> lines) {\n\t\tsetLines(lines);\n\t}\n\n\tprotected List<String> lines;\n\n\tpublic List<String> getLines() {\n\t\treturn lines;\n\t}\n\n\tpublic void setLines(List<String> lines) {\n\t\tthis.lines = lines;\n\t}\n\n}" }, { "identifier": "Factory", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/Factory.java", "snippet": "public final class Factory {\n\n\tpublic static AbapSqlPart getPartObject(String name, List<String> lines) {\n\t\tAbapSqlPart returnPart = null;\n\t\tswitch (name) {\n\t\tcase Abap.SELECT:\n\t\t\treturnPart = new Select(lines);\n\t\tcase Abap.FROM:\n\t\t\treturnPart = new From(lines);\n\t\tcase Abap.SELECTFROM:\n\t\t\treturnPart = new From(lines);\n\t\tcase Abap.ORDERBY:\n\t\t\treturnPart = new OrderBy(lines);\n\t\tcase Abap.UPTO:\n\t\t\treturnPart = new UpTo(lines);\n\t\tcase Abap.FORALLENTRIES:\n\t\t\treturnPart = new UpTo(lines);\n\t\tcase Abap.WHERE:\n\t\t\treturnPart = new Where(lines);\n\t\tcase Abap.GROUPBY:\n\t\t\treturnPart = new GroupBy(lines);\n\t\tcase Abap.INTO:\n\t\t\treturnPart = new Into(lines);\n\t\tcase Abap.HAVING:\n\t\t\treturnPart = new Having(lines);\n\t\tcase Abap.FIELDS:\n\t\t\treturnPart = new Fields(lines);\n\t\tcase Abap.CONNECTION:\n\t\t\treturnPart = new Connection(lines);\n\t\tcase Abap.COMMENT:\n\t\t\treturnPart = new Comment(lines);\n\t\tdefault:\n\t\t\treturnPart = new AbapSqlPart(lines);\n\t\t}\n\t\treturn returnPart;\n\t}\n\n}" }, { "identifier": "Utility", "path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/utility/Utility.java", "snippet": "public class Utility {\n\n\tpublic final static String placeholder = \"@!%&\";\n\n\tpublic static int countKeyword(String statement, String keyword) {\n\n\t\tkeyword = keyword.toUpperCase();\n\n\t\tint count = 0;\n\n\t\tList<String> cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tfor (int i = 0; i < cleanTokenList.size(); i++) {\n\t\t\tString token = cleanTokenList.get(i).trim();\n\t\t\tif (token.equalsIgnoreCase(keyword)) {\n\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (i < cleanTokenList.size()) {\n\t\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1);\n\t\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1);\n\n\t\t\t\t\tif (!tokenBefore.trim().matches(\"'\") && !tokenAfter.trim().matches(\"'\")) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tpublic static boolean isLiteral(String statement, int start, int end) {\n\t\tString statementStart;\n\n\t\tif (start == 0) {\n\t\t\tstatementStart = statement.substring(0, start);\n\t\t} else {\n\t\t\tstatementStart = statement.substring(0, start - 1);\n\t\t}\n\n\t\tString statementMid = statement.substring(statementStart.length(), end + 1) + placeholder + \" \";\n\t\tString statementEnd = statement.substring(end + 1, statement.length());\n\n\t\tstatement = statementStart + statementMid + statementEnd;\n\n\t\tList<String> cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tboolean isLiteral = false;\n\t\tint count = 0;\n\n\t\tfor (int i = 1; i < cleanTokenList.size(); i++) {\n\n\t\t\tString curToken = cleanTokenList.get(i);\n\n\t\t\t// count all \" ' \"\n\t\t\tif (curToken.matches(\"'\")) {\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t\tif (curToken.contains(placeholder)) {\n\n\t\t\t\tcurToken = curToken.replaceAll(placeholder, \"\");\n\n\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1).trim();\n\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1).trim();\n\n\t\t\t\tboolean startLiteral = (tokenBefore.matches(\"'\") || curToken.startsWith(\"'\"));\n\t\t\t\tboolean endsLiteral = (tokenAfter.matches(\"'\") || curToken.endsWith(\"'\"));\n\n\t\t\t\tif (startLiteral && endsLiteral) {\n\t\t\t\t\tif (count % 2 != 0) {\n\t\t\t\t\t\tisLiteral = true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\t\t}\n\n\t\treturn isLiteral;\n\t}\n\n\tprivate static List<String> convertToCleanTokenList(String statement) {\n\t\tstatement = statement.toUpperCase();\n\n\t\tList<String> tokenList = Arrays.asList(statement.trim().split(\" \"));\n\n\t\tList<String> cleanTokenList = new ArrayList<String>();\n\n\t\t// clean tokenList\n\t\tfor (String token : tokenList) {\n\t\t\ttoken = token.replaceAll(\"\\r\\n\", \" \");\n\t\t\tif (!token.isBlank()) {\n\t\t\t\tcleanTokenList.add(token);\n\t\t\t}\n\t\t}\n\n\t\treturn cleanTokenList;\n\n\t}\n\n\tpublic static String deleteSpaces(String statement) {\n\t\t// delete mulitple spaces\n\t\twhile (statement.contains(\" \") || statement.contains(\"\t \")) {\n\t\t\tstatement = statement.replace(\" \", \" \");\n\t\t\tstatement = statement.replace(\"\t\", \" \");\n\t\t}\n\n\t\treturn statement;\n\t}\n\n\tpublic static String deleteLines(String statement) {\n\t\t// return statement.replace(\"\\r\\n\", \" \");\n\t\treturn statement.replace(System.lineSeparator(), \" \");\n\t}\n\n\tpublic static String cleanString(String statement) {\n\t\tString cleanedString = deleteLines(statement);\n\t\tcleanedString = deleteSpaces(cleanedString);\n\t\treturn cleanedString;\n\t}\n\n\tpublic static List<String> getAllOperators() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.addAll(getTwoCharOpers());\n\n\t\topers.addAll(getOneCharOpers());\n\n\t\treturn opers;\n\t}\n\n\tpublic static List<String> getOneCharOpers() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.add(\" = \");\n\t\topers.add(\" < \");\n\t\topers.add(\" > \");\n\n\t\treturn opers;\n\n\t}\n\n\tpublic static List<String> getTwoCharOpers() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.add(\" EQ \");\n\t\topers.add(\" NE \");\n\t\topers.add(\" LT \");\n\t\topers.add(\" GT \");\n\t\topers.add(\" LE \");\n\t\topers.add(\" GE \");\n\n\t\topers.add(\" <> \");\n\t\topers.add(\" <= \");\n\t\topers.add(\" >= \");\n\n\t\topers.add(\" IN \");\n\n\t\treturn opers;\n\t}\n\n\tpublic static List<String> splitLine(String statement, int limit) {\n\t\tList<String> lines = new ArrayList<String>();\n\n\t\tint lengthBefore = statement.length();\n\t\tstatement = statement.strip();\n\t\tString whiteChars = Utility.getWhiteChars(lengthBefore - statement.length());\n\t\tString whiteCharsTabLines = whiteChars + \" \";\n\n\t\tif (statement.length() > limit) {\n\n\t\t\tint count = 0;\n\t\t\tint subStrLength = limit;\n\t\t\twhile (statement != null) {\n\n\t\t\t\tif (statement.length() < subStrLength) {\n\t\t\t\t\tsubStrLength = statement.length();\n\t\t\t\t}\n\n\t\t\t\tString curLine = statement.substring(0, subStrLength);\n\n\t\t\t\tString regex = escapeRegex(statement.trim());\n\n\t\t\t\tif (!curLine.matches(regex)) {\n\n\t\t\t\t\t// get index of last space in this line\n\t\t\t\t\tint curIndex = curLine.lastIndexOf(\" \");\n\n\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t// index found\n\t\t\t\t\t\tcurLine = curLine.substring(0, curIndex);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// no space found --> find next space\n\t\t\t\t\t\tfor (int i = (subStrLength + 1); i < statement.length(); i++) {\n\t\t\t\t\t\t\tcurLine = statement.substring(0, i);\n\t\t\t\t\t\t\tcurIndex = curLine.lastIndexOf(\" \");\n\t\t\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// still not found? take whole statement\n\t\t\t\t\t\tif (curIndex == -1) {\n\t\t\t\t\t\t\tcurLine = statement;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (count == 0) {\n\t\t\t\t\tcurLine = whiteChars + curLine;\n\t\t\t\t} else {\n\t\t\t\t\tcurLine = whiteCharsTabLines + curLine;\n\t\t\t\t}\n\n\t\t\t\tlines.add(curLine);\n\n\t\t\t\tregex = escapeRegex(curLine.trim());\n\n\t\t\t\tstatement = statement.replaceFirst(regex, \"\").trim();\n\n\t\t\t\tif (statement.isBlank()) {\n\t\t\t\t\tstatement = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t} else {\n\t\t\tstatement = whiteChars + statement;\n\t\t\tlines.add(statement);\n\t\t}\n\n\t\treturn lines;\n\n\t}\n\n\tpublic static String getWhiteChars(int amount) {\n\t\tString white = \"\";\n\n\t\tfor (int i = 0; i < amount; i++) {\n\t\t\twhite = white + \" \";\n\t\t}\n\n\t\treturn white;\n\t}\n\n\tpublic static String escapeRegex(String regex) {\n\t\tregex = regex.replace(\"*\", \"\\\\*\");\n\t\tregex = regex.replace(\"(\", \"\\\\(\");\n\t\tregex = regex.replace(\")\", \"\\\\)\");\n\n\t\treturn regex;\n\t}\n\n}" } ]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.abap.sql.beautifier.Abap; import com.abap.sql.beautifier.Activator; import com.abap.sql.beautifier.preferences.PreferenceConstants; import com.abap.sql.beautifier.statement.AbapSqlPart; import com.abap.sql.beautifier.statement.Factory; import com.abap.sql.beautifier.utility.Utility;
3,445
package com.abap.sql.beautifier.settings; public class CommasAdder extends AbstractSqlSetting { public CommasAdder() { // TODO Auto-generated constructor stub } @Override public void apply() { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMMAS)) {
package com.abap.sql.beautifier.settings; public class CommasAdder extends AbstractSqlSetting { public CommasAdder() { // TODO Auto-generated constructor stub } @Override public void apply() { if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.COMMAS)) {
String select = Utility.cleanString(abapSql.getPart(Abap.SELECT).getLines().toString());
0
2023-10-10 18:56:27+00:00
4k
Milosz08/screen-sharing-system
host/src/main/java/pl/polsl/screensharing/host/view/tabbed/TabbedScreenFramePanel.java
[ { "identifier": "HostWindow", "path": "host/src/main/java/pl/polsl/screensharing/host/view/HostWindow.java", "snippet": "@Getter\npublic class HostWindow extends AbstractRootFrame {\n private final HostState hostState;\n private final Optional<Image> streamingImageIconOptional;\n\n private final TopMenuBar topMenuBar;\n private final TopToolbar topToolbar;\n private final TabbedPaneWindow tabbedPaneWindow;\n private final BottomInfobar bottomInfobar;\n\n private final AboutDialogWindow aboutDialogWindow;\n private final LicenseDialogWindow licenseDialogWindow;\n private final SessionDetailsDialogWindow sessionDetailsDialogWindow;\n private final ParticipantsDialogWindow participantsDialogWindow;\n private final SessionInfoDialogWindow sessionInfoDialogWindow;\n\n @Setter\n private ServerDatagramSocket serverDatagramSocket;\n @Setter\n private ServerTcpSocket serverTcpSocket;\n @Setter\n private DatagramKey datagramKey;\n\n public HostWindow(HostState hostState) {\n super(AppType.HOST, hostState, HostWindow.class);\n this.hostState = hostState;\n streamingImageIconOptional = FileUtils.getImageFileFromResources(getClass(), \"HostIconStreaming.png\");\n\n topMenuBar = new TopMenuBar(this);\n topToolbar = new TopToolbar(this);\n tabbedPaneWindow = new TabbedPaneWindow(this);\n bottomInfobar = new BottomInfobar(this);\n\n aboutDialogWindow = new AboutDialogWindow(this);\n licenseDialogWindow = new LicenseDialogWindow(this);\n sessionDetailsDialogWindow = new SessionDetailsDialogWindow(this);\n participantsDialogWindow = new ParticipantsDialogWindow(this);\n sessionInfoDialogWindow = new SessionInfoDialogWindow(this);\n\n initObservables();\n\n setResizable(false);\n setMaximumSize(AppType.HOST.getRootWindowSize());\n }\n\n @Override\n protected void extendsFrame(JFrame frame, JPanel rootPanel) {\n frame.setJMenuBar(topMenuBar);\n frame.add(topToolbar, BorderLayout.NORTH);\n frame.add(tabbedPaneWindow, BorderLayout.CENTER);\n frame.add(bottomInfobar, BorderLayout.SOUTH);\n }\n\n public void initObservables() {\n hostState.wrapAsDisposable(hostState.getStreamingState$(), streamingState -> {\n if (streamingState.equals(StreamingState.STREAMING)) {\n streamingImageIconOptional.ifPresent(this::setIconImage);\n } else {\n imageIconOptional.ifPresent(this::setIconImage);\n }\n });\n }\n\n public BottomInfobarController getBottomInfobarController() {\n return bottomInfobar.getBottomInfobarController();\n }\n\n public VideoCanvas getVideoCanvas() {\n return tabbedPaneWindow.getTabbedScreenFramePanel().getVideoCanvas();\n }\n}" }, { "identifier": "DisableScreenPanel", "path": "host/src/main/java/pl/polsl/screensharing/host/view/fragment/DisableScreenPanel.java", "snippet": "public class DisableScreenPanel extends AbstractTextInfoPanel {\n private final HostState hostState;\n\n public DisableScreenPanel(HostWindow hostWindow) {\n super(\"Showing screen is disabled\");\n hostState = hostWindow.getHostState();\n initObservables();\n }\n\n private void initObservables() {\n hostState.wrapAsDisposable(hostState.isScreenIsShowForParticipants$(), isShowing -> {\n setVisible(!isShowing);\n });\n }\n}" }, { "identifier": "VideoCanvas", "path": "host/src/main/java/pl/polsl/screensharing/host/view/fragment/VideoCanvas.java", "snippet": "@Slf4j\n@Getter\npublic class VideoCanvas extends JPanel {\n private final HostState hostState;\n private final VideoCanvasController controller;\n private final FrameSelectorPanel frameSelectorPanel;\n\n private GraphicsDevice graphicsDevice;\n private StreamingState streamingState;\n private final AtomicBoolean isScreenShowingForParticipants;\n private final AtomicBoolean isCursorShowing;\n\n public VideoCanvas(HostWindow hostWindow, TabbedScreenFramePanel tabbedScreenFramePanel) {\n hostState = hostWindow.getHostState();\n controller = new VideoCanvasController(hostWindow, this, tabbedScreenFramePanel);\n\n frameSelectorPanel = new FrameSelectorPanel(hostWindow, this);\n isScreenShowingForParticipants = new AtomicBoolean(true);\n isCursorShowing = new AtomicBoolean(true);\n streamingState = StreamingState.STOPPED;\n\n setBackground(Color.BLACK);\n initObservables();\n setLayout(null);\n\n hostWindow.addComponentListener(new ResizeComponentAdapter(controller::onResizeWithAspectRatio));\n\n add(frameSelectorPanel);\n }\n\n @Override\n protected void paintComponent(Graphics g) {\n super.paintComponent(g);\n controller.renderContent(g);\n }\n\n private void initObservables() {\n final Observable<StreamingStateFrameModeAggregator> aggregator = Observable.combineLatest(\n hostState.getStreamingState$(),\n hostState.isFrameSelectorShowing$(),\n StreamingStateFrameModeAggregator::new);\n\n hostState.wrapAsDisposable(aggregator, state -> {\n if (!state.isFrameVisible()) {\n final StreamingState streamingState = state.getStreamingState();\n setBorder(streamingState.equals(StreamingState.STREAMING)\n ? BorderFactory.createLineBorder(streamingState.getColor(), 3) : null);\n }\n });\n hostState.wrapAsDisposable(hostState.getSelectedGraphicsDevice$(), graphicsDevice -> {\n this.graphicsDevice = graphicsDevice;\n if (!controller.isAlive()) {\n controller.start();\n }\n controller.onResizeWithAspectRatio();\n repaint();\n });\n hostState.wrapAsDisposable(hostState.isScreenIsShowForParticipants$(), isShowing -> {\n isScreenShowingForParticipants.set(isShowing);\n setVisible(isShowing);\n });\n hostState.wrapAsDisposable(hostState.isCursorShowing$(), isCursorShowing::set);\n hostState.wrapAsDisposable(hostState.getStreamingState$(), streamingState -> {\n this.streamingState = streamingState;\n });\n }\n}" }, { "identifier": "VideoParametersPanel", "path": "host/src/main/java/pl/polsl/screensharing/host/view/fragment/VideoParametersPanel.java", "snippet": "@Getter\npublic class VideoParametersPanel extends JPanel {\n private final HostState hostState;\n\n private final JPanel rootSettingsPanel;\n private final CaptureSettingsPanel captureSettingsPanel;\n private final GraphicsSettingsPanel graphicsSettingsPanel;\n\n private final JPanel actionButtonsPanel;\n private final GridBagConstraints gridBagConstraints;\n private final JAppIconButton showParticipantsButton;\n private final JAppIconButton startVideoStreamingButton;\n private final JAppIconButton stopVideoStreamingButton;\n private final JAppIconButton showScreenToParticipantsButton;\n private final JAppIconButton hideScreenToParticipantsButton;\n\n private final VideoParametersController controller;\n\n public VideoParametersPanel(HostWindow hostWindow) {\n hostState = hostWindow.getHostState();\n controller = new VideoParametersController(hostWindow);\n\n setLayout(new BorderLayout());\n setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));\n\n captureSettingsPanel = new CaptureSettingsPanel(hostWindow);\n graphicsSettingsPanel = new GraphicsSettingsPanel(hostWindow);\n\n rootSettingsPanel = new JPanel(new BorderLayout());\n rootSettingsPanel.add(captureSettingsPanel, BorderLayout.NORTH);\n rootSettingsPanel.add(graphicsSettingsPanel, BorderLayout.SOUTH);\n\n actionButtonsPanel = new JPanel(new GridBagLayout());\n gridBagConstraints = new GridBagConstraints();\n gridBagConstraints.insets = new Insets(3, 5, 3, 5);\n\n startVideoStreamingButton = new JAppIconButton(\"Start stream\", HostIcon.DEBUG_INTERACTIVE_WINDOW, false);\n stopVideoStreamingButton = new JAppIconButton(\"Stop stream\", HostIcon.APPLICATION_ERROR, false, false);\n showScreenToParticipantsButton = new JAppIconButton(\"Show screen\", HostIcon.OPEN_QUERY, false, false);\n hideScreenToParticipantsButton = new JAppIconButton(\"Hide screen\", HostIcon.STOP_QUERY, false);\n showParticipantsButton = new JAppIconButton(\"Show participants (0)\", HostIcon.LOOKUP_GROUP_MEMBERS, false);\n\n initObservables();\n\n startVideoStreamingButton.addActionListener(e -> controller.startVideoStreaming());\n stopVideoStreamingButton.addActionListener(e -> controller.stopVideoStreaming());\n showScreenToParticipantsButton.addActionListener(e -> controller.toggleScreenShowingForParticipants(true));\n hideScreenToParticipantsButton.addActionListener(e -> controller.toggleScreenShowingForParticipants(false));\n showParticipantsButton.addActionListener(e -> controller.showParticipantsDialog());\n\n gridBagConstraints.weightx = 1.0;\n gridBagConstraints.weighty = 1.0;\n gridBagConstraints.fill = GridBagConstraints.BOTH;\n\n addToGridBag(startVideoStreamingButton, 0, 0);\n addToGridBag(showScreenToParticipantsButton, 1, gridBagConstraints.gridy);\n addToGridBag(stopVideoStreamingButton, 0, 1);\n addToGridBag(hideScreenToParticipantsButton, 1, 1);\n addToGridBag(showParticipantsButton, 0, 2, 2);\n\n add(rootSettingsPanel, BorderLayout.NORTH);\n add(new JPanel(), BorderLayout.CENTER);\n add(actionButtonsPanel, BorderLayout.SOUTH);\n }\n\n private void addToGridBag(JComponent component, int x, int y, int width) {\n gridBagConstraints.gridx = x;\n gridBagConstraints.gridy = y;\n gridBagConstraints.gridwidth = width;\n actionButtonsPanel.add(component, gridBagConstraints);\n }\n\n private void addToGridBag(JComponent component, int x, int y) {\n addToGridBag(component, x, y, 1);\n }\n\n private void initObservables() {\n final Observable<SessionStreamingAggregator> aggregator = Observable.combineLatest(\n hostState.getSessionState$(),\n hostState.getStreamingState$(),\n SessionStreamingAggregator::new);\n\n hostState.wrapAsDisposable(aggregator, state -> {\n final boolean isCreated = state.getSessionState().equals(SessionState.CREATED);\n final boolean isStreaming = state.getStreamingState().equals(StreamingState.STREAMING);\n startVideoStreamingButton.setEnabled(!isStreaming && isCreated);\n stopVideoStreamingButton.setEnabled(isStreaming && isCreated);\n });\n hostState.wrapAsDisposable(hostState.isScreenIsShowForParticipants$(), isShowing -> {\n showScreenToParticipantsButton.setEnabled(!isShowing);\n hideScreenToParticipantsButton.setEnabled(isShowing);\n });\n hostState.wrapAsDisposable(hostState.getConnectedClientsInfo$(), clients -> {\n showParticipantsButton.setText(String.format(\"Show participants (%s)\", clients.size()));\n });\n }\n}" }, { "identifier": "AbstractTabbedPanel", "path": "lib/src/main/java/pl/polsl/screensharing/lib/gui/AbstractTabbedPanel.java", "snippet": "public abstract class AbstractTabbedPanel extends JPanel {\n public AbstractTabbedPanel() {\n setLayout(new BorderLayout());\n setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n }\n}" } ]
import lombok.Getter; import pl.polsl.screensharing.host.view.HostWindow; import pl.polsl.screensharing.host.view.fragment.DisableScreenPanel; import pl.polsl.screensharing.host.view.fragment.VideoCanvas; import pl.polsl.screensharing.host.view.fragment.VideoParametersPanel; import pl.polsl.screensharing.lib.gui.AbstractTabbedPanel; import javax.swing.*; import java.awt.*;
2,655
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.view.tabbed; @Getter public class TabbedScreenFramePanel extends AbstractTabbedPanel { private final JPanel videoFrameHolder; private final VideoCanvas videoCanvas; private final DisableScreenPanel disableScreenPanel;
/* * Copyright (c) 2023 by MULTIPLE AUTHORS * Part of the CS study course project. */ package pl.polsl.screensharing.host.view.tabbed; @Getter public class TabbedScreenFramePanel extends AbstractTabbedPanel { private final JPanel videoFrameHolder; private final VideoCanvas videoCanvas; private final DisableScreenPanel disableScreenPanel;
private final VideoParametersPanel videoParametersPanel;
3
2023-10-11 16:12:02+00:00
4k
cbfacademy-admin/java-rest-api-assessment-jenieb3
src/test/java/com/cbfacademy/apiassessment/repository/InvestmentRepositoryTest.java
[ { "identifier": "InvestmentValidationException", "path": "src/main/java/com/cbfacademy/apiassessment/exceptions/InvestmentValidationException.java", "snippet": "public class InvestmentValidationException extends RuntimeException{\n public InvestmentValidationException(String message) {\n super(message);\n }\n}" }, { "identifier": "Bond", "path": "src/main/java/com/cbfacademy/apiassessment/model/Bond.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\n\npublic class Bond implements Investment {\n // Class properties for Bond.\n private Long id;\n private String name;\n private int quantity;\n private double purchasePrice;\n private double currentPrice;\n\n// Constructor\n public Bond(Long id , String name, int quantity, double purchasePrice, double currentPrice) {\n this.id = id;\n this.name = name;\n this.quantity = quantity;\n this.purchasePrice = purchasePrice;\n this.currentPrice = currentPrice;\n\n }\n\n public Bond() {\n\n }\n // Getters and Setters\n\n public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id =id;\n }\n public String getName() {\n return name;\n }\n public void setName (String name) {\n this.name = name;\n }\n public int getQuantity() {\n return quantity;\n }\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n public double getPurchasePrice() {\n return purchasePrice;\n }\n public void setPurchasePrice(double purchasePrice) {\n this.purchasePrice = purchasePrice;\n }\n public double getCurrentPrice() {\n return currentPrice;\n }\n public void setCurrentPrice(double currentPrice) {\n this.currentPrice = currentPrice;\n }\n\n @Override\n public double getReturns() {\n //Calculate returns for a Bond.\n return(currentPrice -purchasePrice) * quantity;\n }\n}" }, { "identifier": "Investment", "path": "src/main/java/com/cbfacademy/apiassessment/model/Investment.java", "snippet": "@JsonTypeInfo(\n use = JsonTypeInfo.Id.NAME,\n property = \"type\")\n@JsonSubTypes({\n @JsonSubTypes.Type(value = Bond.class, name = \"Bond\"),\n @JsonSubTypes.Type(value = Stock.class, name = \"Stock\")\n})\n\n\n// Investment interface to represent any kind of investment\npublic interface Investment {\n // Abstract methods for basic Investment properties.\n\n Long getId();\n void setId(Long id);\n String getName();\n void setName(String name);\n int getQuantity();\n void setQuantity(int quantity);\n double getPurchasePrice();\n void setPurchasePrice(double purchasePrice);\n double getCurrentPrice();\n void setCurrentPrice(double currentPrice);\n double getReturns();\n\n}" }, { "identifier": "Stock", "path": "src/main/java/com/cbfacademy/apiassessment/model/Stock.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\n\npublic class Stock implements Investment {\n // Class properties for a Stock\n private Long id;\n private String name;\n private int quantity;\n private double purchasePrice;\n private double currentPrice;\n// Constructor\n public Stock(Long id, String name, int quantity, double purchasePrice, double currentPrice) {\n this.id = id;\n this.name = name;\n this.quantity = quantity;\n this.purchasePrice = purchasePrice;\n this.currentPrice = currentPrice;\n }\n\n public Stock() {\n\n }\n // Getters and Setters\n public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getQuantity() {\n return quantity;\n }\n public void setQuantity(int quantity) {\n this.quantity = quantity;\n }\n public double getPurchasePrice() {\n return purchasePrice;\n }\n public void setPurchasePrice(double purchasePrice) {\n this.purchasePrice = purchasePrice;\n }\n public double getCurrentPrice() {\n return currentPrice;\n }\n public void setCurrentPrice(double currentPrice) {\n this.currentPrice = currentPrice;\n }\n @Override\n public double getReturns() {\n //Calculation for stock returns\n return (currentPrice - purchasePrice) * quantity;\n }\n}" }, { "identifier": "JsonUtil", "path": "src/main/java/com/cbfacademy/apiassessment/utility/JsonUtil.java", "snippet": "@Component\n//Utility class to handle JSON operations related to investment objects,\npublic class JsonUtil {\n private final ObjectMapper objectMapper;\n private final ResourceLoader resourceLoader;\n private final String filePath;\n\n public JsonUtil(ObjectMapper objectMapper, ResourceLoader resourceLoader, @Value(\"${json.file.path}\") String filePath) {\n this.objectMapper = objectMapper;\n this.resourceLoader = resourceLoader;\n this.filePath = filePath;\n }\n\n // Method to read investments from JSON file.\n public List<Investment> readInvestmentsFromJson() throws IOException {\n Resource resource = resourceLoader.getResource(filePath);\n try (InputStream inputStream = resource.getInputStream()) {\n InvestmentWrapper wrapper = objectMapper.readValue(inputStream, InvestmentWrapper.class);\n return wrapper.getInvestments();\n }\n }\n\n // Method to write investments to the JSON file.\n public void writeInvestmentsToJson(List<Investment> investments, boolean prettyPrint) throws IOException {\n Resource resource = resourceLoader.getResource(filePath);\n File file = resource.getFile();\n try (OutputStream fileOutputStream = new FileOutputStream(file)) {\n InvestmentWrapper wrapper = new InvestmentWrapper();\n wrapper.setInvestments(investments);\n // Configure ObjectMapper to use the default pretty printer\n if (prettyPrint) {\n objectMapper.writerWithDefaultPrettyPrinter().writeValue(fileOutputStream, wrapper);\n } else {\n objectMapper.writeValue(fileOutputStream, wrapper);\n }\n }\n }\n}" } ]
import com.cbfacademy.apiassessment.exceptions.InvestmentValidationException; import com.cbfacademy.apiassessment.model.Bond; import com.cbfacademy.apiassessment.model.Investment; import com.cbfacademy.apiassessment.model.Stock; import com.cbfacademy.apiassessment.utility.JsonUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*;
2,119
package com.cbfacademy.apiassessment.repository; /** * Unit tests for the InvestmentRepository class. * This class verifies the functionality of data access operations, including the ability to correctly * perform CRUD operations on investment data. * Special focus is given to the correct handling of edge cases and exceptions. */ @ExtendWith(MockitoExtension.class) public class InvestmentRepositoryTest { @Mock private JsonUtil jsonUtil; @InjectMocks private InvestmentRepository investmentRepository; // Concrete implementation of Investments private Bond sampleBond; private Stock sampleStock; @BeforeEach void setup() throws IOException { sampleBond = new Bond(); sampleBond.setId(1L); sampleBond.setName("Sample Bond"); sampleBond.setQuantity(15); sampleStock = new Stock(); sampleStock.setId(2L); sampleStock.setName("Sample Stock"); sampleStock.setQuantity(20); // Mocking the JsonUtil response lenient().when(jsonUtil.readInvestmentsFromJson()).thenReturn(Arrays.asList(sampleBond, sampleStock)); investmentRepository.init(); } @Test // Initialize the repository and verify contents void initTest() { List<Investment> investments = investmentRepository.findAll(); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findAllTest() { // Test to retrieve all Investments List<Investment> investments = investmentRepository.findAll(); assertFalse(investments.isEmpty()); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findByIdTest() { // Test for finding investments by ID investmentRepository.init(); // Make sure the repository is initialized Optional<Investment> foundBond = investmentRepository.findById(sampleBond.getId()); assertTrue(foundBond.isPresent()); assertEquals(sampleBond, foundBond.get()); Optional<Investment> foundStock = investmentRepository.findById(sampleStock.getId()); assertTrue(foundStock.isPresent()); assertEquals(sampleStock, foundStock.get()); } @Test void saveTest() throws IOException { // Test saving a new investment Stock newStock = new Stock(); newStock.setId(2L); newStock.setName("New Investment"); investmentRepository.save(newStock); verify(jsonUtil).writeInvestmentsToJson(any(List.class), eq(false)); assertEquals(newStock, investmentRepository.findById(2L).orElse(null)); } @Test void saveWithInvalidIdTest () { Bond invalidBond = new Bond(); invalidBond.setId(0L); invalidBond.setName("Invalid Bond");
package com.cbfacademy.apiassessment.repository; /** * Unit tests for the InvestmentRepository class. * This class verifies the functionality of data access operations, including the ability to correctly * perform CRUD operations on investment data. * Special focus is given to the correct handling of edge cases and exceptions. */ @ExtendWith(MockitoExtension.class) public class InvestmentRepositoryTest { @Mock private JsonUtil jsonUtil; @InjectMocks private InvestmentRepository investmentRepository; // Concrete implementation of Investments private Bond sampleBond; private Stock sampleStock; @BeforeEach void setup() throws IOException { sampleBond = new Bond(); sampleBond.setId(1L); sampleBond.setName("Sample Bond"); sampleBond.setQuantity(15); sampleStock = new Stock(); sampleStock.setId(2L); sampleStock.setName("Sample Stock"); sampleStock.setQuantity(20); // Mocking the JsonUtil response lenient().when(jsonUtil.readInvestmentsFromJson()).thenReturn(Arrays.asList(sampleBond, sampleStock)); investmentRepository.init(); } @Test // Initialize the repository and verify contents void initTest() { List<Investment> investments = investmentRepository.findAll(); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findAllTest() { // Test to retrieve all Investments List<Investment> investments = investmentRepository.findAll(); assertFalse(investments.isEmpty()); assertTrue(investments.contains(sampleBond)); assertTrue(investments.contains(sampleStock)); assertEquals(2, investments.size()); } @Test void findByIdTest() { // Test for finding investments by ID investmentRepository.init(); // Make sure the repository is initialized Optional<Investment> foundBond = investmentRepository.findById(sampleBond.getId()); assertTrue(foundBond.isPresent()); assertEquals(sampleBond, foundBond.get()); Optional<Investment> foundStock = investmentRepository.findById(sampleStock.getId()); assertTrue(foundStock.isPresent()); assertEquals(sampleStock, foundStock.get()); } @Test void saveTest() throws IOException { // Test saving a new investment Stock newStock = new Stock(); newStock.setId(2L); newStock.setName("New Investment"); investmentRepository.save(newStock); verify(jsonUtil).writeInvestmentsToJson(any(List.class), eq(false)); assertEquals(newStock, investmentRepository.findById(2L).orElse(null)); } @Test void saveWithInvalidIdTest () { Bond invalidBond = new Bond(); invalidBond.setId(0L); invalidBond.setName("Invalid Bond");
Exception exception = assertThrows(InvestmentValidationException.class, () -> {
0
2023-10-10 18:57:19+00:00
4k
sh0inx/Dragon-Cancel
src/main/java/io/github/sh0inx/dragoncancellite/commands/HelpCommand.java
[ { "identifier": "DragonCancelLite", "path": "src/main/java/io/github/sh0inx/dragoncancellite/DragonCancelLite.java", "snippet": "public class DragonCancelLite extends JavaPlugin {\n\n private static DragonCancelLite instance;\n public static FileConfiguration config;\n public static List<String> worldsToCancel;\n\n @Override\n public void onLoad() {\n loadConfiguration();\n }\n\n @Override\n public void onEnable() {\n instance = this;\n Bukkit.getPluginManager().registerEvents(new EntitySpawnEventListener(), this);\n this.getCommand(\"dragonCancel\").setExecutor(new CommandManager());\n\n for(String world : getWorldsToCancel()) {\n try {\n if(world.equalsIgnoreCase(\"\")) {\n getLogger().warning(\"config.yml needs world names to continue, restart server with config.yml populated with world names\");\n return;\n }\n editLevelData(world);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n private void loadConfiguration() {\n this.saveDefaultConfig();\n config = this.getConfig();\n }\n\n public List<String> getWorldsToCancel() {\n return worldsToCancel = config.getStringList(\"worlds\");\n }\n\n public String getSubString(Substring selection) {\n\n String hexColorBright = \"F3C5FF\";\n String hexColorDark = \"592463\";\n String highlightColor = \"<SOLID:\" + hexColorBright + \">\";\n String lowLightColor = \"<SOLID:\" + hexColorDark + \">\";\n String dragonCancel = DragonCancelLite.getInstance().getDescription().getName();\n String dragon = dragonCancel.substring(0,6);\n String cancel = dragonCancel.substring(6,12);\n String titleprefix = \"*+*+*+ \";\n String titlesuffix = \" +*+*+*\";\n String prefixPluginName = \"<GRADIENT:\" + hexColorDark + \">\" + dragonCancel + \"</GRADIENT:\" + hexColorBright + \">\";\n String prefixInsignia = \"&8}\";\n String messagePrefix = prefixPluginName + \" \" + prefixInsignia + \" \";\n String dragonCancelTitle =\n \"<GRADIENT:\" + hexColorDark + \">\"\n + titleprefix\n + dragon\n + \"</GRADIENT:\" + hexColorBright + \">\"\n + \"<GRADIENT:\" + hexColorBright + \">\"\n + cancel\n + titlesuffix\n + \"</GRADIENT:\" + hexColorDark + \">\";\n String dragonCancelSubTitle =\n lowLightColor + \"--{ \"\n + highlightColor + \"&oHere be &nno\"\n + highlightColor + \"&o dragons.&r\"\n + lowLightColor + \" }--\";\n String consoleDecorator = \"*+*+*+**+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*\";\n\n String reponse = null;\n\n switch (selection) {\n case HEXCOLORBRIGHT: {\n return hexColorBright;\n }\n case HEXCOLORDARK: {\n return hexColorDark;\n }\n case HIGHLIGHTCOLOR: {\n return highlightColor;\n }\n case LOWLIGHTCOLOR: {\n return lowLightColor;\n }\n case DRAGONCANCEL: {\n return dragonCancel;\n }\n case DRAGON: {\n return dragon;\n }\n case CANCEL: {\n return cancel;\n }\n case DRAGONCANCELTITLE: {\n return dragonCancelTitle;\n }\n case DRAGONCANCELSUBTITLE: {\n return dragonCancelSubTitle;\n }\n case TITLEPREFIX: {\n return titleprefix;\n }\n case TITLESUFFIX: {\n return titlesuffix;\n }\n case PREFIXPLUGINNAME: {\n return prefixPluginName;\n }\n case PREFIXINSIGNIA: {\n return prefixInsignia;\n }\n case MESSAGEPREFIX: {\n return messagePrefix;\n }\n case CONSOLEDECORATOR: {\n return consoleDecorator;\n }\n default: {\n return \"[invalid string call \\\"\" + selection + \"\\\"]\";\n }\n }\n }\n\n private void editLevelData(String world) throws IOException {\n\n if(!backupWorld(world, \"backupWorlds\")) {\n getLogger().warning(\n IridiumColorAPI.process(DragonCancelLite.getInstance().getSubString(Substring.CONSOLEDECORATOR)));\n\n getLogger().warning(\"Not editing \\\"\" + world + \"\\\" because backup failed.\");\n getLogger().warning(\"Restart server with valid config and EXISTING world you want to dragon cancel.\");\n getLogger().warning(\"If you still want to dragon cancel in \\\"\" + world + \"\\\", DO NOT ENTER THE WORLD.\");\n getLogger().warning(\"If \\\"\" + world + \"\\\" already existed, see previous error/stacktrace.\");\n\n getLogger().warning(\n IridiumColorAPI.process(DragonCancelLite.getInstance().getSubString(Substring.CONSOLEDECORATOR)));\n return;\n }\n\n File file = new File(world + File.separator + \"level.dat\");\n NBTFile worldFile = new NBTFile(file);\n\n if(worldFile.getCompound(\"Data\").getCompound(\"DragonFight\") == null) {\n getLogger().warning(\"Cannot load \\\"DragonFight\\\" compound because \\\"DragonFight\\\" is null.\");\n return;\n }\n\n NBTCompound compound = worldFile.getCompound(\"Data\").getCompound(\"DragonFight\");\n Byte PreviouslyKilled = compound.getByte(\"PreviouslyKilled\");\n Byte DragonKilled = compound.getByte(\"DragonKilled\");\n Byte NeedsStateScanning = compound.getByte(\"NeedsStateScanning\");\n Byte Dragon = compound.getByte(\"Dragon\");\n\n if(PreviouslyKilled == (byte) 0) {\n compound.setByte(\"PreviouslyKilled\", (byte) 1);\n }\n if(DragonKilled == 0) {\n compound.setByte(\"DragonKilled\", (byte) 1);\n }\n if(NeedsStateScanning == 1) {\n compound.setByte(\"NeedsStateScanning\", (byte) 0);\n }\n\n if(Dragon != null) {\n compound.removeKey(\"Dragon\");\n }\n\n worldFile.save();\n }\n\n private boolean backupWorld(String world, String backupFolderName) {\n\n getLogger().info(\"Attempting to create backup of \\\"level.dat\\\" for \\\"\" + world + \"\\\"...\");\n\n File pluginFolder = new File(getDataFolder().getPath());\n File worldFolder = new File(world);\n File levelData = new File(worldFolder + File.separator + \"level.dat\");\n\n File backupFolder = new File(pluginFolder.getPath() + File.separator + backupFolderName);\n File backupWorldFolder = new File(backupFolder + File.separator + world);\n File backupLevelData = new File(backupWorldFolder + File.separator + \"level.dat\");\n\n if (!backupFolder.exists()) backupFolder.mkdir();\n\n try {\n if(worldFolder.listFiles() == null) {\n getLogger().warning(\"No files in world folder found (Has \\\"\" + world + \"\\\" been created?).\");\n return false;\n }\n if(!backupWorldFolder.exists()) {\n Files.copy(worldFolder.toPath(), backupWorldFolder.toPath());\n }\n\n Files.copy(levelData.toPath(), backupLevelData.toPath(), StandardCopyOption.REPLACE_EXISTING);\n\n } catch (IOException exception) {\n getLogger().warning(\"Could not copy \" + worldFolder.getName() + \" to \" + backupWorldFolder.getAbsolutePath());\n exception.printStackTrace();\n return false;\n }\n\n getLogger().info(\"Backup successful, check \" + backupFolder.getPath() + \".\");\n return true;\n }\n\n public static DragonCancelLite getInstance() {\n return instance;\n }\n\n\n\n\n\n\n}" }, { "identifier": "Substring", "path": "src/main/java/io/github/sh0inx/dragoncancellite/Substring.java", "snippet": "public enum Substring {\n HEXCOLORBRIGHT,\n HEXCOLORDARK,\n HIGHLIGHTCOLOR,\n LOWLIGHTCOLOR,\n DRAGONCANCEL,\n DRAGON,\n CANCEL,\n TITLEPREFIX,\n TITLESUFFIX,\n PREFIXPLUGINNAME,\n PREFIXINSIGNIA,\n MESSAGEPREFIX,\n DRAGONCANCELTITLE,\n DRAGONCANCELSUBTITLE,\n CONSOLEDECORATOR\n}" } ]
import com.iridium.iridiumcolorapi.IridiumColorAPI; import io.github.sh0inx.dragoncancellite.DragonCancelLite; import io.github.sh0inx.dragoncancellite.Substring; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender;
2,147
package io.github.sh0inx.dragoncancellite.commands; public class HelpCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage(IridiumColorAPI.process(
package io.github.sh0inx.dragoncancellite.commands; public class HelpCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { sender.sendMessage(IridiumColorAPI.process(
DragonCancelLite.getInstance().getSubString(Substring.DRAGONCANCELTITLE)));
0
2023-10-09 05:32:02+00:00
4k
Bawnorton/Potters
src/main/java/com/bawnorton/potters/block/entity/BottomlessDecoratedPotBlockEntity.java
[ { "identifier": "BottomlessDecoratedPotBlock", "path": "src/main/java/com/bawnorton/potters/block/BottomlessDecoratedPotBlock.java", "snippet": "public class BottomlessDecoratedPotBlock extends PottersDecoratedPotBlockBase {\n public static final Identifier WITH_CONTENT = Potters.id(\"with_content\");\n public static final BooleanProperty EMTPY = BooleanProperty.of(\"empty\");\n private static final DirectionProperty FACING = Properties.HORIZONTAL_FACING;\n private static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED;\n\n public BottomlessDecoratedPotBlock(Supplier<Item> materialSupplier) {\n super(materialSupplier, FabricBlockSettings.copy(Blocks.DECORATED_POT));\n this.setDefaultState(this.stateManager.getDefaultState()\n .with(FACING, Direction.NORTH)\n .with(WATERLOGGED, Boolean.FALSE)\n .with(EMTPY, Boolean.TRUE));\n }\n\n @Override\n public BlockState getPlacementState(ItemPlacementContext ctx) {\n FluidState fluidState = ctx.getWorld().getFluidState(ctx.getBlockPos());\n BlockState state = this.getDefaultState()\n .with(FACING, ctx.getHorizontalPlayerFacing())\n .with(WATERLOGGED, fluidState.getFluid() == Fluids.WATER)\n .with(EMTPY, Boolean.TRUE);\n\n ItemStack stack = ctx.getStack();\n NbtCompound nbt = stack.getNbt();\n if (nbt == null) return state;\n\n NbtCompound blockEntityTag = nbt.getCompound(\"BlockEntityTag\");\n if (blockEntityTag.isEmpty()) return state;\n\n String count = blockEntityTag.getString(\"count\");\n try {\n int amount = Integer.parseInt(count);\n if (amount > 0) {\n state = state.with(EMTPY, Boolean.FALSE);\n }\n } catch (NumberFormatException ignored) {}\n\n return state;\n }\n\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(FACING, WATERLOGGED, EMTPY);\n }\n\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new BottomlessDecoratedPotBlockEntity(pos, state);\n }\n\n @Override\n public BlockSoundGroup getSoundGroup(BlockState state) {\n return BlockSoundGroup.DECORATED_POT;\n }\n\n @Override\n protected BlockEntityType<? extends PottersDecoratedPotBlockEntityBase> getBlockEntityType() {\n return PottersBlockEntityType.BOTTOMLESS_DECORATED_POT;\n }\n\n @Override\n public List<ItemStack> getDroppedStacks(BlockState state, LootContextParameterSet.Builder builder) {\n BlockEntity blockEntity = builder.getOptional(LootContextParameters.BLOCK_ENTITY);\n if (blockEntity instanceof BottomlessDecoratedPotBlockEntity bottomlessDecoratedPotBlockEntity) {\n builder.addDynamicDrop(WITH_CONTENT, lootConsumer -> {\n ItemStack stack = bottomlessDecoratedPotBlockEntity.asStack(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, this.asItem());\n NbtCompound blockEntityTag = stack.getOrCreateNbt().getCompound(\"BlockEntityTag\");\n bottomlessDecoratedPotBlockEntity.getStorage().writeNbt(blockEntityTag);\n stack.getOrCreateNbt().put(\"BlockEntityTag\", blockEntityTag);\n lootConsumer.accept(stack);\n });\n }\n\n List<ItemStack> droppedStacks = super.getDroppedStacks(state, builder);\n // correct nbt for bottomless decorated pot with sherds\n for(ItemStack stack: droppedStacks) {\n if (!(Block.getBlockFromItem(stack.getItem()) instanceof BottomlessDecoratedPotBlock)) continue;\n\n NbtCompound nbt = stack.getNbt();\n if(nbt == null) continue;\n\n NbtCompound blockEntityTag = nbt.getCompound(\"BlockEntityTag\");\n if(blockEntityTag.isEmpty()) continue;\n\n if(blockEntityTag.contains(\"sherds\")) {\n if (blockEntityTag.contains(\"id\")) continue;\n\n Identifier id = Registries.BLOCK_ENTITY_TYPE.getId(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT);\n if(id == null) continue;\n\n blockEntityTag.putString(\"id\", id.toString());\n }\n }\n return droppedStacks;\n }\n\n @Override\n public boolean isFinite() {\n return false;\n }\n}" }, { "identifier": "PottersDecoratedPotBlockEntityBase", "path": "src/main/java/com/bawnorton/potters/block/entity/base/PottersDecoratedPotBlockEntityBase.java", "snippet": "public abstract class PottersDecoratedPotBlockEntityBase extends DecoratedPotBlockEntity {\n public static final ThreadLocal<BlockEntityType<?>> TYPE = ThreadLocal.withInitial(() -> null);\n\n protected PottersDecoratedPotBlockEntityBase(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n super(setType(pos, type), state);\n }\n\n private static BlockPos setType(BlockPos pos, BlockEntityType<?> type) {\n TYPE.set(type);\n return pos;\n }\n\n public static ItemStack getStackWith(BlockEntityType<? extends BlockEntity> type, Item asItem, DecoratedPotBlockEntity.Sherds sherds) {\n ItemStack itemStack = asItem.getDefaultStack();\n NbtCompound nbtCompound = sherds.toNbt(new NbtCompound());\n BlockItem.setBlockEntityNbt(itemStack, type, nbtCompound);\n return itemStack;\n }\n\n public abstract PottersDecoratedPotStorageBase getStorage();\n\n @Override\n public void readNbt(NbtCompound nbt) {\n super.readNbt(nbt);\n getStorage().readNbt(nbt);\n }\n\n @Override\n protected void writeNbt(NbtCompound nbt) {\n super.writeNbt(nbt);\n getStorage().writeNbt(nbt);\n }\n\n @Override\n public abstract BlockEntityUpdateS2CPacket toUpdatePacket();\n\n @Override\n public abstract NbtCompound toInitialChunkDataNbt();\n\n public ItemStack asStack(BlockEntityType<? extends PottersDecoratedPotBlockEntityBase> type, Item asItem) {\n return getStackWith(type, asItem, this.getSherds());\n }\n}" }, { "identifier": "PottersBlockEntityType", "path": "src/main/java/com/bawnorton/potters/registry/PottersBlockEntityType.java", "snippet": "public class PottersBlockEntityType {\n public static final BlockEntityType<FiniteDecoratedPotBlockEntity> FINITE_DECORATED_POT;\n public static final BlockEntityType<BottomlessDecoratedPotBlockEntity> BOTTOMLESS_DECORATED_POT;\n private static final List<BlockEntityType<? extends PottersDecoratedPotBlockEntityBase>> ALL;\n\n static {\n ALL = new ArrayList<>();\n List<Block> blocks = new ArrayList<>();\n PottersBlocks.forEachFinite(blocks::add);\n FINITE_DECORATED_POT = register(\"finite\", FabricBlockEntityTypeBuilder.create((pos, state) -> {\n FiniteDecoratedPotBlock block = (FiniteDecoratedPotBlock) state.getBlock();\n return new FiniteDecoratedPotBlockEntity(pos, state, block.getStackCountSupplier());\n }, blocks.toArray(new Block[]{})).build());\n BOTTOMLESS_DECORATED_POT = register(\"bottomless\", FabricBlockEntityTypeBuilder.create(BottomlessDecoratedPotBlockEntity::new, PottersBlocks.BOTTOMLESS_DECORATED_POT)\n .build());\n }\n\n public static void forEach(Consumer<BlockEntityType<? extends PottersDecoratedPotBlockEntityBase>> blockEntityTypeConsumer) {\n ALL.forEach(blockEntityTypeConsumer);\n }\n\n public static void init() {\n ItemStorage.SIDED.registerForBlockEntities(((blockEntity, context) -> {\n if (blockEntity instanceof PottersDecoratedPotBlockEntityBase pottersBlockEntity) {\n return pottersBlockEntity.getStorage();\n }\n return null;\n }), ALL.toArray(new BlockEntityType[]{}));\n }\n\n private static <T extends PottersDecoratedPotBlockEntityBase> BlockEntityType<T> register(String name, BlockEntityType<T> type) {\n BlockEntityType<T> blockEntityType = Registry.register(Registries.BLOCK_ENTITY_TYPE, Potters.id(name + \"_decorated_pot\"), type);\n ALL.add(blockEntityType);\n return blockEntityType;\n }\n}" }, { "identifier": "BottomlessDecoratedPotStorage", "path": "src/main/java/com/bawnorton/potters/storage/BottomlessDecoratedPotStorage.java", "snippet": "public class BottomlessDecoratedPotStorage extends PottersDecoratedPotStorageBase {\n private BigInteger count = BigInteger.ZERO;\n\n {\n amount = 1; // set to allow extracting to work\n }\n\n @Override\n public long getCapacity(ItemVariant variant) {\n throw new UnsupportedOperationException(\"Infinite storage has infinite capacity\");\n }\n\n @Override\n public long insert(ItemVariant insertedVariant, long maxAmount, TransactionContext transaction) {\n StoragePreconditions.notBlankNotNegative(insertedVariant, maxAmount);\n\n if ((insertedVariant.equals(variant) || variant.isBlank()) && canInsert(insertedVariant)) {\n BigInteger insertedAmount = BigInteger.valueOf(maxAmount);\n\n if (insertedAmount.compareTo(BigInteger.ZERO) > 0) {\n updateSnapshots(transaction);\n\n if (variant.isBlank()) {\n variant = insertedVariant;\n count = insertedAmount;\n } else {\n count = count.add(insertedAmount);\n }\n\n return insertedAmount.longValue();\n }\n }\n\n return 0;\n }\n\n @Override\n public long extract(ItemVariant extractedVariant, long maxAmount, TransactionContext transaction) {\n StoragePreconditions.notBlankNotNegative(extractedVariant, maxAmount);\n\n if (extractedVariant.equals(variant) && canExtract(extractedVariant)) {\n BigInteger extractedAmount = BigInteger.valueOf(maxAmount);\n\n if (extractedAmount.compareTo(BigInteger.ZERO) > 0) {\n updateSnapshots(transaction);\n count = count.subtract(extractedAmount);\n\n if (count.compareTo(BigInteger.ZERO) <= 0) {\n variant = getBlankVariant();\n }\n\n return extractedAmount.longValue();\n }\n }\n\n return 0;\n }\n\n @Override\n public Number getCount() {\n return count;\n }\n\n @Override\n public void setCount(Number number) {\n count = BigInteger.valueOf(number.longValue());\n }\n\n @Override\n public float getPitch() {\n return 0.7F;\n }\n\n @Override\n public void readNbt(NbtCompound nbt) {\n variant = ItemVariant.fromNbt(nbt.getCompound(\"variant\"));\n count = new BigInteger(nbt.getString(\"count\"));\n }\n\n @Override\n public void writeNbt(NbtCompound nbt) {\n nbt.put(\"variant\", variant.toNbt());\n nbt.putString(\"count\", count.toString());\n }\n}" }, { "identifier": "PottersDecoratedPotStorageBase", "path": "src/main/java/com/bawnorton/potters/storage/PottersDecoratedPotStorageBase.java", "snippet": "public abstract class PottersDecoratedPotStorageBase extends SingleItemStorage {\n private final List<Consumer<PottersDecoratedPotStorageBase>> listeners = new ArrayList<>();\n\n public void addListener(Consumer<PottersDecoratedPotStorageBase> listener) {\n listeners.add(listener);\n }\n\n public void clear() {\n variant = getBlankVariant();\n setCount(0);\n }\n\n @Override\n protected boolean canInsert(ItemVariant variant) {\n if (variant.getItem().getDefaultStack().isIn(PottersItemTags.POT_BLACKLIST)) return false;\n if (isResourceBlank()) return true;\n if (!variant.equals(getResource())) return false;\n return getResource().nbtMatches(variant.getNbt());\n }\n\n @Override\n public abstract void writeNbt(NbtCompound nbt);\n\n public boolean canInsert(ItemStack stack) {\n return canInsert(ItemVariant.of(stack));\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n public void insert(ItemStack stack) {\n TransactionManagerImpl transactionManager = TransactionManagerImpl.MANAGERS.get();\n TransactionContext openTransaction;\n if (transactionManager.isOpen()) {\n openTransaction = transactionManager.getCurrentUnsafe();\n if (openTransaction == null) openTransaction = transactionManager.openOuter();\n } else {\n openTransaction = transactionManager.openOuter();\n }\n\n insert(ItemVariant.of(stack), 1, openTransaction);\n openTransaction.getOpenTransaction(openTransaction.nestingDepth()).commit();\n listeners.forEach(listener -> listener.accept(this));\n }\n\n @SuppressWarnings(\"UnstableApiUsage\")\n public ItemStack extract() {\n TransactionManagerImpl transactionManager = TransactionManagerImpl.MANAGERS.get();\n TransactionContext openTransaction;\n long extracted;\n if (transactionManager.isOpen()) {\n openTransaction = transactionManager.getCurrentUnsafe();\n if (openTransaction == null) openTransaction = transactionManager.openOuter();\n } else {\n openTransaction = transactionManager.openOuter();\n }\n Item item = getResource().getItem();\n NbtCompound nbt = getResource().getNbt();\n // can't guarantee that getResource() will return the same after the transaction\n extracted = extract(getResource(), 1, openTransaction);\n openTransaction.getOpenTransaction(openTransaction.nestingDepth()).commit();\n listeners.forEach(listener -> listener.accept(this));\n ItemStack stack = new ItemStack(item, (int) extracted);\n stack.setNbt(nbt);\n return stack;\n }\n\n public abstract Number getCount();\n\n public abstract void setCount(Number number);\n\n public abstract float getPitch();\n\n @Override\n public abstract void readNbt(NbtCompound nbt);\n}" } ]
import com.bawnorton.potters.block.BottomlessDecoratedPotBlock; import com.bawnorton.potters.block.entity.base.PottersDecoratedPotBlockEntityBase; import com.bawnorton.potters.registry.PottersBlockEntityType; import com.bawnorton.potters.storage.BottomlessDecoratedPotStorage; import com.bawnorton.potters.storage.PottersDecoratedPotStorageBase; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.nbt.NbtCompound; import net.minecraft.network.packet.s2c.play.BlockEntityUpdateS2CPacket; import net.minecraft.util.math.BlockPos;
3,568
package com.bawnorton.potters.block.entity; public class BottomlessDecoratedPotBlockEntity extends PottersDecoratedPotBlockEntityBase { private final BottomlessDecoratedPotStorage storage; public BottomlessDecoratedPotBlockEntity(BlockPos pos, BlockState state) { super(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, pos, state); storage = new BottomlessDecoratedPotStorage(); storage.addListener(storageView -> { if (world == null) return; if (world.isClient) return; if (storageView.isResourceBlank()) { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, true), Block.NO_REDRAW); } else { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, false), Block.NO_REDRAW); } }); } @Override
package com.bawnorton.potters.block.entity; public class BottomlessDecoratedPotBlockEntity extends PottersDecoratedPotBlockEntityBase { private final BottomlessDecoratedPotStorage storage; public BottomlessDecoratedPotBlockEntity(BlockPos pos, BlockState state) { super(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, pos, state); storage = new BottomlessDecoratedPotStorage(); storage.addListener(storageView -> { if (world == null) return; if (world.isClient) return; if (storageView.isResourceBlank()) { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, true), Block.NO_REDRAW); } else { world.setBlockState(pos, state.with(BottomlessDecoratedPotBlock.EMTPY, false), Block.NO_REDRAW); } }); } @Override
public PottersDecoratedPotStorageBase getStorage() {
4
2023-10-13 19:14:56+00:00
4k
YinQin257/mqs-adapter
mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/factory/CreateKafkaConsumer.java
[ { "identifier": "Constants", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/Constants.java", "snippet": "public interface Constants {\n int SUCCESS = 1;\n int ERROR = 0;\n String TRAN = \"TRAN\";\n String BATCH = \"BATCH\";\n String BROADCAST = \"BROADCAST\";\n String TRUE = \"true\";\n String EMPTY = \"\";\n String HYPHEN = \"-\";\n String UNDER_SCORE = \"_\";\n String BROADCAST_CONNECTOR = \"_BROADCAST_\";\n String BROADCAST_SUFFIX = \"_BROADCAST\";\n String BATCH_SUFFIX = \"_BATCH\";\n String WILDCARD =\"*\";\n}" }, { "identifier": "MqsProperties", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/config/MqsProperties.java", "snippet": "@ConfigurationProperties(MqsProperties.PREFIX)\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MqsProperties {\n\n /**\n * 配置项前缀\n */\n public static final String PREFIX = \"mqs\";\n\n /**\n * 配置集合\n */\n private Map<String, AdapterProperties> adapter = new LinkedHashMap<>();\n\n /**\n * 消息中间件实例配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class AdapterProperties {\n\n /**\n * 消息中间件厂商名称\n */\n private String vendorName;\n\n /**\n * 生产组或消费组名称\n * 批量消费组(groupName)、单条消费组(groupName + ‘_TRAN’)、广播消费组(groupName + ‘BROADCAST’)\n */\n private String groupName;\n\n /**\n * 消费者启动开关\n */\n private boolean consumerEnabled = false;\n\n /**\n * 生产者启动开关\n */\n private boolean producerEnabled = false;\n\n /**\n * 消费组配置类\n */\n private ConvertProperties group = new ConvertProperties();\n\n /**\n * topic配置类\n */\n private ConvertProperties topic = new ConvertProperties();\n\n /**\n * rocketmq配置类\n */\n private CustomRocketmqProperties rocketmq = new CustomRocketmqProperties();\n\n /**\n * kafka配置类\n */\n private CustomKafkaProperties kafka = new CustomKafkaProperties();\n\n /**\n * 转换配置类\n *\n * @author YinQin\n * @version 1.0.4\n * @createDate 2023年11月20日\n * @since 1.0.0\n */\n @Data\n public static class ConvertProperties {\n\n /**\n * 前缀\n */\n private String prefix;\n\n /**\n * 后缀\n */\n private String suffix;\n\n /**\n * 是否小写转大写\n */\n private boolean isLowerToUpper = false;\n\n /**\n * 是否大写转小写\n */\n private boolean isUpperToLower = false;\n\n /**\n * 是否下划线转中划线\n */\n private boolean isUnderScoreToHyphen = false;\n\n /**\n * 是否中划线转下划线\n */\n private boolean isHyphenToUnderScore = false;\n }\n\n /**\n * rocketmq配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class CustomRocketmqProperties {\n\n /**\n * rocketmq acl访问控制\n * 可配置acl开关、accessKey、secretKey\n */\n private Acl acl = new Acl();\n\n /**\n * 批量消费最大数量,建议不超过32\n */\n private int consumeMessageBatchMaxSize = 1;\n\n /**\n * 消费线程最大数量\n */\n private int consumeThreadMax = 1;\n\n /**\n * 消费线程最小数量\n */\n private int consumeThreadMin = 1;\n\n /**\n * 流量控制\n * 消费者本地缓存消息数超过pullThresholdForQueue时,降低拉取消息频率\n */\n private int pullThresholdForQueue = 1000;\n\n /**\n * 流量控制\n * 消费者本地缓存消息跨度超过consumeConcurrentlyMaxSpan时,降低拉取消息频率\n */\n private int consumeConcurrentlyMaxSpan = 500;\n\n /**\n * rocketmq其他源生配置项,可自行参考官网配置\n *\n * @see ClientConfig\n */\n private ClientConfig clientConfig;\n\n /**\n * acl访问控制类,继承SessionCredentials\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @see org.apache.rocketmq.acl.common.SessionCredentials\n * @since 1.0.0\n */\n @EqualsAndHashCode(callSuper = true)\n @Data\n public static class Acl extends SessionCredentials {\n\n /**\n * acl访问控制开关\n */\n private boolean enabled;\n }\n }\n\n /**\n * kafka配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class CustomKafkaProperties {\n\n /**\n * kafka其他源生配置项,可自行参考官网配置\n *\n * @see org.apache.kafka.clients.consumer.ConsumerConfig\n */\n private Properties clientConfig;\n\n /**\n * 拉取消息间隔时间,单位:毫秒\n */\n private int interval = 100;\n }\n }\n\n}" }, { "identifier": "MessageHandler", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/handler/MessageHandler.java", "snippet": "public interface MessageHandler {\n\n /**\n * 单条或广播消息处理方法\n *\n * @param message 消息\n * @throws Exception 异常\n */\n void process(AdapterMessage message) throws Exception;\n\n /**\n * 批量消息处理方法\n *\n * @param messages 消息\n * @throws Exception 异常\n */\n void process(List<AdapterMessage> messages) throws Exception;\n}" }, { "identifier": "ConvertUtil", "path": "mqs-starter/src/main/java/org/yinqin/mqs/common/util/ConvertUtil.java", "snippet": "public class ConvertUtil {\n /**\n * topic名称或者消费组名称转换\n *\n * @param name 消费组名称或topic名称\n * @param convertProperties 转换配置\n * @return 转换后的名称\n */\n public static String convertName(String name, AdapterProperties.ConvertProperties convertProperties) {\n if (convertProperties == null) return name;\n if (StringUtils.isNotBlank(convertProperties.getPrefix()) &&!name.startsWith(convertProperties.getPrefix()))\n name = convertProperties.getPrefix().concat(name);\n if (StringUtils.isNotBlank(convertProperties.getSuffix()) &&!name.endsWith(convertProperties.getSuffix()))\n name = name.concat(convertProperties.getSuffix());\n if (convertProperties.isLowerToUpper()) name = name.toUpperCase();\n if (convertProperties.isUpperToLower()) name = name.toLowerCase();\n if (convertProperties.isUnderScoreToHyphen()) name = name.replace(Constants.UNDER_SCORE, Constants.HYPHEN);\n if (convertProperties.isHyphenToUnderScore()) name = name.replace(Constants.HYPHEN, Constants.UNDER_SCORE);\n return name;\n }\n\n /**\n * 适配器消息转rocketmq原生消息\n * @param message 消息\n * @return rocketmq原生消息\n */\n public static Message AdapterMessageToRocketmqMessage(AdapterMessage message, AdapterProperties.ConvertProperties topicProperties) {\n return new Message(ConvertUtil.convertName(message.getTopic(),topicProperties), message.getTag(), message.getBizKey(), message.getBody());\n }\n\n /**\n * 适配器消息转kafka原生消息\n * @param message 消息\n * @return kafka原生消息\n */\n public static ProducerRecord<String, byte[]> AdapterMessageToKafkaMessage(AdapterMessage message, AdapterProperties.ConvertProperties topicProperties) {\n return new ProducerRecord<>(ConvertUtil.convertName(message.getTopic(),topicProperties), null, message.getBizKey(), message.getBody(), null);\n }\n}" } ]
import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yinqin.mqs.common.Constants; import org.yinqin.mqs.common.config.MqsProperties; import org.yinqin.mqs.common.handler.MessageHandler; import org.yinqin.mqs.common.util.ConvertUtil; import java.util.Map; import java.util.Properties; import java.util.UUID;
2,859
package org.yinqin.mqs.kafka.consumer.factory; /** * 创建kafka消费者公共方法 * * @author YinQin * @version 1.0.6 * @createDate 2023年11月30日 * @since 1.0.6 */ public interface CreateKafkaConsumer { Logger logger = LoggerFactory.getLogger(CreateKafkaConsumer.class); /** * 初始化kafka配置 * * @param kafkaProperties kafka配置 * @param properties mqs配置 */ default void init(Properties kafkaProperties, MqsProperties.AdapterProperties properties) { kafkaProperties.putAll(properties.getKafka().getClientConfig()); kafkaProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString().replace(Constants.HYPHEN, Constants.EMPTY).substring(0, 8)); kafkaProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Constants.TRUE); } /** * 订阅topic * * @param kafkaConsumer kafka消费者 * @param instanceId 实例ID * @param groupName 消费组名称 * @param messageHandlers 消息处理器 */ default void subscribe(KafkaConsumer<String, byte[]> kafkaConsumer, String instanceId, String groupName, Map<String, MessageHandler> messageHandlers) { kafkaConsumer.subscribe(messageHandlers.keySet()); for (String topic : messageHandlers.keySet()) { logger.info("实例:{} 消费者启动中,消费组:{},订阅Topic:{}", instanceId, groupName, topic); } } /** * 创建kafka原生消费者 * * @param groupName 消费组名称 * @param properties mqs配置 * @param kafkaProperties kafka配置 * @return kafka原生消费者 */ default KafkaConsumer<String, byte[]> createKafkaConsumer(String groupName, MqsProperties.AdapterProperties properties, Properties kafkaProperties) {
package org.yinqin.mqs.kafka.consumer.factory; /** * 创建kafka消费者公共方法 * * @author YinQin * @version 1.0.6 * @createDate 2023年11月30日 * @since 1.0.6 */ public interface CreateKafkaConsumer { Logger logger = LoggerFactory.getLogger(CreateKafkaConsumer.class); /** * 初始化kafka配置 * * @param kafkaProperties kafka配置 * @param properties mqs配置 */ default void init(Properties kafkaProperties, MqsProperties.AdapterProperties properties) { kafkaProperties.putAll(properties.getKafka().getClientConfig()); kafkaProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); kafkaProperties.put(ConsumerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString().replace(Constants.HYPHEN, Constants.EMPTY).substring(0, 8)); kafkaProperties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, Constants.TRUE); } /** * 订阅topic * * @param kafkaConsumer kafka消费者 * @param instanceId 实例ID * @param groupName 消费组名称 * @param messageHandlers 消息处理器 */ default void subscribe(KafkaConsumer<String, byte[]> kafkaConsumer, String instanceId, String groupName, Map<String, MessageHandler> messageHandlers) { kafkaConsumer.subscribe(messageHandlers.keySet()); for (String topic : messageHandlers.keySet()) { logger.info("实例:{} 消费者启动中,消费组:{},订阅Topic:{}", instanceId, groupName, topic); } } /** * 创建kafka原生消费者 * * @param groupName 消费组名称 * @param properties mqs配置 * @param kafkaProperties kafka配置 * @return kafka原生消费者 */ default KafkaConsumer<String, byte[]> createKafkaConsumer(String groupName, MqsProperties.AdapterProperties properties, Properties kafkaProperties) {
groupName = ConvertUtil.convertName(groupName, properties.getGroup());
3
2023-10-11 03:23:43+00:00
4k
openpilot-hub/devpilot-intellij
src/main/java/com/zhongan/devpilot/settings/DevPilotConfigForm.java
[ { "identifier": "ModelServiceEnum", "path": "src/main/java/com/zhongan/devpilot/enums/ModelServiceEnum.java", "snippet": "public enum ModelServiceEnum {\n OPENAI(\"OpenAI\", \"OpenAI Service\"),\n LLAMA(\"LLaMA\", \"Code LLaMA (Locally)\"),\n AIGATEWAY(\"AIGateway\", \"AI Gateway\");\n\n // model name\n private final String name;\n\n // model display name\n private final String displayName;\n\n ModelServiceEnum(String name, String displayName) {\n this.name = name;\n this.displayName = displayName;\n }\n\n public String getName() {\n return name;\n }\n\n public static ModelServiceEnum fromName(String name) {\n if (name == null) {\n return OPENAI;\n }\n for (ModelServiceEnum type : ModelServiceEnum.values()) {\n if (type.getName().equals(name)) {\n return type;\n }\n }\n return OPENAI;\n }\n\n @Override\n public String toString() {\n return displayName;\n }\n}" }, { "identifier": "ModelTypeEnum", "path": "src/main/java/com/zhongan/devpilot/enums/ModelTypeEnum.java", "snippet": "public enum ModelTypeEnum {\n GPT3_5(\"GPT-3.5\", \"azure/gpt-3.5-turbo\", \"GPT-3.5\"),\n ERNIE(\"Ernie\", \"baidu/ernie-bot-4\", \"Ernie Bot\"),\n TYQW(\"TYQW\", \"ali/qwen-plus\", \"Qwen\"),\n SENSENOVA(\"sensenova\", \"sensenova/nova-ptc-xl-v1\", \"Sense Nova\");\n\n // model name\n private final String name;\n\n // model code\n private final String code;\n\n // model display name\n private final String displayName;\n\n ModelTypeEnum(String name, String code, String displayName) {\n this.name = name;\n this.code = code;\n this.displayName = displayName;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getName() {\n return name;\n }\n\n public static ModelTypeEnum fromName(String name) {\n if (name == null) {\n return GPT3_5;\n }\n for (ModelTypeEnum type : ModelTypeEnum.values()) {\n if (type.getName().equals(name)) {\n return type;\n }\n }\n return GPT3_5;\n }\n\n @Override\n public String toString() {\n return displayName;\n }\n}" }, { "identifier": "OpenAIModelNameEnum", "path": "src/main/java/com/zhongan/devpilot/enums/OpenAIModelNameEnum.java", "snippet": "public enum OpenAIModelNameEnum {\n GPT3_5_TURBO(\"gpt-3.5-turbo\", \"gpt-3.5-turbo\"),\n GPT3_5_TURBO_16K(\"gpt-3.5-turbo-16k\", \"gpt-3.5-turbo(16k)\"),\n GPT4(\"gpt-4\", \"gpt-4\"),\n GPT4_32K(\"gpt-4-32k\", \"gpt-4(32k)\"),\n CUSTOM(\"custom\", \"Custom Model\");\n\n private String name;\n\n private String displayName;\n\n OpenAIModelNameEnum(String name, String displayName) {\n this.name = name;\n this.displayName = displayName;\n }\n\n public static OpenAIModelNameEnum fromName(String name) {\n if (name == null) {\n return GPT3_5_TURBO;\n }\n for (OpenAIModelNameEnum type : OpenAIModelNameEnum.values()) {\n if (type.getName().equals(name)) {\n return type;\n }\n }\n return GPT3_5_TURBO;\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 getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n @Override\n public String toString() {\n return displayName;\n }\n}" }, { "identifier": "AIGatewaySettingsState", "path": "src/main/java/com/zhongan/devpilot/settings/state/AIGatewaySettingsState.java", "snippet": "@State(name = \"DevPilot_AIGatewaySettings\", storages = @Storage(\"DevPilot_AIGatewaySettings.xml\"))\npublic class AIGatewaySettingsState implements PersistentStateComponent<AIGatewaySettingsState> {\n private String selectedModel = ModelTypeEnum.GPT3_5.getName();\n\n private Map<String, String> modelBaseHostMap = new ConcurrentHashMap<>();\n\n public static AIGatewaySettingsState getInstance() {\n return ApplicationManager.getApplication().getService(AIGatewaySettingsState.class);\n }\n\n public String getSelectedModel() {\n return selectedModel;\n }\n\n public void setSelectedModel(String selectedModel) {\n this.selectedModel = selectedModel;\n }\n\n public String getModelBaseHost(String selectedModel) {\n String openAIBaseHost = \"\";\n return modelBaseHostMap.getOrDefault(selectedModel, openAIBaseHost);\n }\n\n public void setModelBaseHost(String model, String host) {\n this.modelBaseHostMap.put(model, host);\n }\n\n public Map<String, String> getModelBaseHostMap() {\n return modelBaseHostMap;\n }\n\n public void setModelBaseHostMap(Map<String, String> modelBaseHostMap) {\n this.modelBaseHostMap = modelBaseHostMap;\n }\n\n @Override\n public AIGatewaySettingsState getState() {\n return this;\n }\n\n @Override\n public void loadState(AIGatewaySettingsState state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n}" }, { "identifier": "CodeLlamaSettingsState", "path": "src/main/java/com/zhongan/devpilot/settings/state/CodeLlamaSettingsState.java", "snippet": "@State(name = \"DevPilot_CodeLlamaSettings\", storages = @Storage(\"DevPilot_CodeLlamaSettings.xml\"))\npublic class CodeLlamaSettingsState implements PersistentStateComponent<CodeLlamaSettingsState> {\n private String modelHost;\n\n private String modelName = \"CodeLlama-7b\";\n\n public static CodeLlamaSettingsState getInstance() {\n return ApplicationManager.getApplication().getService(CodeLlamaSettingsState.class);\n }\n\n public String getModelHost() {\n return modelHost;\n }\n\n public void setModelHost(String modelHost) {\n this.modelHost = modelHost;\n }\n\n public String getModelName() {\n return modelName;\n }\n\n public void setModelName(String modelName) {\n this.modelName = modelName;\n }\n\n @Override\n public @Nullable CodeLlamaSettingsState getState() {\n return this;\n }\n\n @Override\n public void loadState(@NotNull CodeLlamaSettingsState state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n}" }, { "identifier": "DevPilotLlmSettingsState", "path": "src/main/java/com/zhongan/devpilot/settings/state/DevPilotLlmSettingsState.java", "snippet": "@State(name = \"DevPilot_Settings\", storages = @Storage(\"DevPilot_Settings.xml\"))\npublic class DevPilotLlmSettingsState implements PersistentStateComponent<DevPilotLlmSettingsState> {\n\n private String fullName;\n\n private String uuid;\n\n private String selectedModel = ModelServiceEnum.LLAMA.getName();\n\n public static DevPilotLlmSettingsState getInstance() {\n return ApplicationManager.getApplication().getService(DevPilotLlmSettingsState.class);\n }\n\n public String getSelectedModel() {\n return selectedModel;\n }\n\n public void setSelectedModel(String selectedModel) {\n this.selectedModel = selectedModel;\n }\n\n public String getUuid() {\n if (uuid == null || uuid.isEmpty()) {\n uuid = UUID.randomUUID().toString();\n }\n\n return uuid;\n }\n\n public void setUuid(String uuid) {\n this.uuid = uuid;\n }\n\n @Override\n public DevPilotLlmSettingsState getState() {\n return this;\n }\n\n @Override\n public void loadState(DevPilotLlmSettingsState state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n\n // getting fullName\n public String getFullName() {\n if (fullName == null || fullName.isEmpty()) {\n return System.getProperty(\"user.name\", \"User\");\n }\n return fullName;\n }\n\n public void setFullName(String displayName) {\n this.fullName = displayName;\n }\n\n}" }, { "identifier": "LanguageSettingsState", "path": "src/main/java/com/zhongan/devpilot/settings/state/LanguageSettingsState.java", "snippet": "@State(name = \"DevPilot_LanguageSettings\", storages = @Storage(\"DevPilot_LanguageSettings.xml\"))\npublic class LanguageSettingsState implements PersistentStateComponent<LanguageSettingsState> {\n\n private static Integer languageIndex = 1;\n\n public static LanguageSettingsState getInstance() {\n return ApplicationManager.getApplication().getService(LanguageSettingsState.class);\n }\n\n public Integer getLanguageIndex() {\n return languageIndex;\n }\n\n public void setLanguageIndex(Integer languageIndex) {\n this.languageIndex = languageIndex;\n }\n\n @Override\n public LanguageSettingsState getState() {\n return this;\n }\n\n @Override\n public void loadState(LanguageSettingsState state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n\n}" }, { "identifier": "OpenAISettingsState", "path": "src/main/java/com/zhongan/devpilot/settings/state/OpenAISettingsState.java", "snippet": "@State(name = \"DevPilot_OpenAISettings\", storages = @Storage(\"DevPilot_OpenAISettings.xml\"))\npublic class OpenAISettingsState implements PersistentStateComponent<OpenAISettingsState> {\n private String modelHost;\n\n private String privateKey;\n\n private String modelName = OpenAIModelNameEnum.GPT3_5_TURBO.getName();\n\n private String customModelName;\n\n public static OpenAISettingsState getInstance() {\n return ApplicationManager.getApplication().getService(OpenAISettingsState.class);\n }\n\n public String getModelHost() {\n return modelHost;\n }\n\n public void setModelHost(String modelHost) {\n this.modelHost = modelHost;\n }\n\n public String getPrivateKey() {\n return privateKey;\n }\n\n public void setPrivateKey(String privateKey) {\n this.privateKey = privateKey;\n }\n\n public String getModelName() {\n return modelName;\n }\n\n public void setModelName(String modelName) {\n this.modelName = modelName;\n }\n\n public String getCustomModelName() {\n return customModelName;\n }\n\n public void setCustomModelName(String customModelName) {\n this.customModelName = customModelName;\n }\n\n @Override\n public OpenAISettingsState getState() {\n return this;\n }\n\n @Override\n public void loadState(OpenAISettingsState state) {\n XmlSerializerUtil.copyBean(state, this);\n }\n\n}" }, { "identifier": "DevPilotMessageBundle", "path": "src/main/java/com/zhongan/devpilot/util/DevPilotMessageBundle.java", "snippet": "public class DevPilotMessageBundle extends DynamicBundle {\n\n private static final DevPilotMessageBundle INSTANCE = new DevPilotMessageBundle();\n\n private static ResourceBundle bundleEn;\n\n private static ResourceBundle bundleCN;\n\n private static final String pathToBundle = \"messages.devpilot\";\n\n private DevPilotMessageBundle() {\n super(pathToBundle);\n }\n\n static {\n bundleEn = ResourceBundle.getBundle(pathToBundle, Locale.ENGLISH);\n bundleCN = ResourceBundle.getBundle(pathToBundle, Locale.CHINA);\n }\n\n public static String get(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key) {\n Integer languageIndex = LanguageSettingsState.getInstance().getLanguageIndex();\n if (languageIndex == 1) {\n return bundleCN.getString(key);\n }\n return bundleEn.getString(key);\n }\n\n public static String get(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key, Object... params) {\n return INSTANCE.getMessage(key, params);\n }\n\n public static String getFromBundleEn(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key) {\n return bundleEn.getString(key);\n }\n\n}" } ]
import com.intellij.openapi.ui.ComboBox; import com.intellij.ui.components.JBTextField; import com.intellij.util.ui.FormBuilder; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UI; import com.zhongan.devpilot.enums.ModelServiceEnum; import com.zhongan.devpilot.enums.ModelTypeEnum; import com.zhongan.devpilot.enums.OpenAIModelNameEnum; import com.zhongan.devpilot.settings.state.AIGatewaySettingsState; import com.zhongan.devpilot.settings.state.CodeLlamaSettingsState; import com.zhongan.devpilot.settings.state.DevPilotLlmSettingsState; import com.zhongan.devpilot.settings.state.LanguageSettingsState; import com.zhongan.devpilot.settings.state.OpenAISettingsState; import com.zhongan.devpilot.util.DevPilotMessageBundle; import javax.swing.JComponent; import javax.swing.JPanel;
3,391
package com.zhongan.devpilot.settings; public class DevPilotConfigForm { private final JPanel comboBoxPanel; private final ComboBox<ModelServiceEnum> modelComboBox; private final JPanel openAIServicePanel; private final JBTextField openAIBaseHostField; private final JBTextField openAIKeyField; private final ComboBox<OpenAIModelNameEnum> openAIModelNameComboBox; private final JBTextField openAICustomModelNameField; private final JPanel aiGatewayServicePanel; private final JBTextField aiGatewayBaseHostField; private final ComboBox<ModelTypeEnum> aiGatewayModelComboBox; private final JPanel codeLlamaServicePanel; private final JBTextField codeLlamaBaseHostField; private final JBTextField codeLlamaModelNameField; private Integer index; public DevPilotConfigForm() {
package com.zhongan.devpilot.settings; public class DevPilotConfigForm { private final JPanel comboBoxPanel; private final ComboBox<ModelServiceEnum> modelComboBox; private final JPanel openAIServicePanel; private final JBTextField openAIBaseHostField; private final JBTextField openAIKeyField; private final ComboBox<OpenAIModelNameEnum> openAIModelNameComboBox; private final JBTextField openAICustomModelNameField; private final JPanel aiGatewayServicePanel; private final JBTextField aiGatewayBaseHostField; private final ComboBox<ModelTypeEnum> aiGatewayModelComboBox; private final JPanel codeLlamaServicePanel; private final JBTextField codeLlamaBaseHostField; private final JBTextField codeLlamaModelNameField; private Integer index; public DevPilotConfigForm() {
var devPilotSettings = DevPilotLlmSettingsState.getInstance();
5
2023-11-29 06:37:51+00:00
4k
Gaia3D/mago-3d-tiler
tiler/src/main/java/com/gaia3d/process/ProcessFlowThread.java
[ { "identifier": "FileLoader", "path": "tiler/src/main/java/com/gaia3d/converter/FileLoader.java", "snippet": "public interface FileLoader {\n public List<TileInfo> loadTileInfo(File file);\n public List<File> loadFiles();\n}" }, { "identifier": "PostProcess", "path": "tiler/src/main/java/com/gaia3d/process/postprocess/PostProcess.java", "snippet": "public interface PostProcess {\n ContentInfo run(ContentInfo contentInfo);\n}" }, { "identifier": "ProcessThreadPool", "path": "tiler/src/main/java/com/gaia3d/process/postprocess/thread/ProcessThreadPool.java", "snippet": "@Slf4j\npublic class ProcessThreadPool {\n private static final int THREAD_COUNT = 8;\n\n public void preProcessStart(List<TileInfo> tileInfos, List<File> fileList, FileLoader fileLoader, List<PreProcess> preProcessors) throws InterruptedException {\n log.info(\"[ThreadPool][Start Pre-process]\");\n ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);\n List<Runnable> tasks = new ArrayList<>();\n\n log.info(\"[pre-process] Total file counts : {}\", fileList.size());\n AtomicInteger count = new AtomicInteger();\n int size = fileList.size();\n for (File file : fileList) {\n Runnable callableTask = () -> {\n count.getAndIncrement();\n log.info(\"[load] : {}/{} : {}\", count, size, file);\n List<TileInfo> tileInfoResult = fileLoader.loadTileInfo(file);\n int serial = 0;\n for (TileInfo tileInfo : tileInfoResult) {\n if (tileInfo != null) {\n log.info(\"[{}/{}][{}/{}] load tile...\", count, size, serial, tileInfoResult.size());\n for (PreProcess preProcessor : preProcessors) {\n preProcessor.run(tileInfo);\n }\n tileInfo.minimize(serial++);\n tileInfos.add(tileInfo);\n }\n }\n };\n tasks.add(callableTask);\n }\n\n for (Runnable task : tasks) {\n executorService.submit(task);\n }\n executorService.shutdown();\n\n do {\n if (executorService.isTerminated()) {\n executorService.shutdownNow();\n }\n } while (!executorService.awaitTermination(3, TimeUnit.SECONDS));\n log.info(\"[ThreadPool][End Pre-process]\");\n }\n\n public void postProcessStart(List<ContentInfo> contentInfos, List<PostProcess> postProcesses) throws InterruptedException {\n log.info(\"[ThreadPool][Start Post-process]\");\n ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);\n\n AtomicInteger count = new AtomicInteger();\n int size = contentInfos.size();\n List<Runnable> tasks = new ArrayList<>();\n for (ContentInfo contentInfo : contentInfos) {\n Runnable callableTask = () -> {\n count.getAndIncrement();\n log.info(\"[post-process][{}/{}] content-info : {}\", count, size, contentInfo.getName());\n List<TileInfo> childTileInfos = contentInfo.getTileInfos();\n List<TileInfo> copiedTileInfos = childTileInfos.stream()\n .map((childTileInfo) -> TileInfo.builder()\n .kmlInfo(childTileInfo.getKmlInfo())\n .scenePath(childTileInfo.getScenePath())\n .tempPath(childTileInfo.getTempPath())\n .transformMatrix(childTileInfo.getTransformMatrix())\n .boundingBox(childTileInfo.getBoundingBox())\n .build())\n .collect(Collectors.toList());\n contentInfo.setTileInfos(copiedTileInfos);\n\n for (TileInfo tileInfo : copiedTileInfos) {\n tileInfo.maximize();\n }\n for (PostProcess postProcessor : postProcesses) {\n postProcessor.run(contentInfo);\n }\n contentInfo.deleteTexture();\n\n copiedTileInfos.clear();\n copiedTileInfos = null;\n };\n tasks.add(callableTask);\n }\n\n for (Runnable task : tasks) {\n executorService.submit(task);\n }\n executorService.shutdown();\n\n do {\n if (executorService.isTerminated()) {\n executorService.shutdownNow();\n }\n } while (!executorService.awaitTermination(3, TimeUnit.SECONDS));\n log.info(\"[ThreadPool][End Post-process]\");\n }\n}" }, { "identifier": "PreProcess", "path": "tiler/src/main/java/com/gaia3d/process/preprocess/PreProcess.java", "snippet": "public interface PreProcess {\n TileInfo run(TileInfo tileInfo);\n}" }, { "identifier": "Process", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/Process.java", "snippet": "public interface Process {\n public void process(FileLoader fileLoader) throws IOException;\n}" }, { "identifier": "TileProcess", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/TileProcess.java", "snippet": "public interface TileProcess {\n Tileset run(List<TileInfo> tileInfo);\n\n public void writeTileset(Tileset tileset);\n}" }, { "identifier": "Tiler", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/Tiler.java", "snippet": "public interface Tiler extends TileProcess {\n public void writeTileset(Tileset tileset);\n}" }, { "identifier": "ContentInfo", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/ContentInfo.java", "snippet": "@Slf4j\n@Getter\n@Setter\npublic class ContentInfo {\n private String name;\n private String nodeCode;\n private LevelOfDetail lod;\n private List<TileInfo> tileInfos;\n private List<TileInfo> remainTileInfos;\n private GaiaBoundingBox boundingBox;\n private GaiaSet batchedSet;\n\n public void deleteTexture() {\n for (TileInfo tileInfo : tileInfos) {\n GaiaSet set = tileInfo.getSet();\n set.deleteTextures();\n }\n for (TileInfo tileInfo : remainTileInfos) {\n GaiaSet set = tileInfo.getSet();\n if (set != null) {\n set.deleteTextures();\n }\n }\n }\n\n public void clear() {\n this.name = null;\n this.boundingBox = null;\n this.batchedSet = null;\n this.tileInfos.forEach(TileInfo::clear);\n this.tileInfos = null;\n this.remainTileInfos.forEach(TileInfo::clear);\n this.remainTileInfos = null;\n }\n}" }, { "identifier": "TileInfo", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/TileInfo.java", "snippet": "@Getter\n@Setter\n@Builder\n@Slf4j\npublic class TileInfo {\n private KmlInfo kmlInfo;\n private GaiaScene scene;\n private GaiaSet set;\n private GaiaPointCloud pointCloud;\n private String name;\n\n private Matrix4d transformMatrix;\n private GaiaBoundingBox boundingBox;\n private Path scenePath;\n private Path outputPath;\n private Path tempPath;\n\n private void init() {\n GaiaNode rootNode = this.scene.getNodes().get(0);\n this.transformMatrix = rootNode.getTransformMatrix();\n this.boundingBox = this.scene.getGaiaBoundingBox();\n this.scenePath = this.scene.getOriginalPath();\n this.name = rootNode.getName();\n\n this.tempPath = this.outputPath.resolve(\"temp\");\n if (this.tempPath.toFile().mkdir()) {\n log.info(\"Create directory: {}\", this.tempPath);\n }\n //this.tempPath = this.tempPath.resolve(scenePath.getFileName() + \".set\");\n }\n\n public void minimize(int serial) {\n if (this.scene != null) {\n init();\n\n GaiaSet tempSet = new GaiaSet(this.scene);\n this.tempPath = tempSet.writeFile(this.tempPath, serial);\n\n tempSet.clear();\n tempSet = null;\n this.scene.clear();\n this.scene = null;\n } else {\n log.warn(\"[Warn] Can't minimize tile info because scene is null.\");\n }\n }\n\n public void maximize() {\n if (this.set != null) {\n this.set.deleteTextures();\n this.set = null;\n }\n this.set = new GaiaSet(this.tempPath);\n }\n\n public void clear() {\n this.scene = null;\n this.set = null;\n }\n\n public void deleteTemp() throws IOException {\n if (this.tempPath != null) {\n File file = this.tempPath.toFile();\n File parent = file.getParentFile();\n\n log.info(\"[DeleteTemp] {}\", file);\n if (parent.isDirectory()) {\n FileUtils.deleteDirectory(parent);\n } else if (file.isFile()) {\n FileUtils.delete(file);\n } else if (file.isDirectory()) {\n FileUtils.deleteDirectory(file);\n } else {\n log.warn(\"[Warn] Can't delete temp file because it is not file or directory.\");\n }\n }\n }\n}" }, { "identifier": "Tileset", "path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/tileset/Tileset.java", "snippet": "@Getter\n@Setter\npublic class Tileset {\n private Asset asset;\n private double geometricError = 0.0d;\n private Node root;\n private Properties properties;\n\n @JsonIgnore\n public List<ContentInfo> findAllContentInfo() {\n return root.findAllContentInfo(new ArrayList<>());\n }\n}" } ]
import com.gaia3d.converter.FileLoader; import com.gaia3d.process.postprocess.PostProcess; import com.gaia3d.process.postprocess.thread.ProcessThreadPool; import com.gaia3d.process.preprocess.PreProcess; import com.gaia3d.process.tileprocess.Process; import com.gaia3d.process.tileprocess.TileProcess; import com.gaia3d.process.tileprocess.Tiler; import com.gaia3d.process.tileprocess.tile.ContentInfo; import com.gaia3d.process.tileprocess.tile.TileInfo; import com.gaia3d.process.tileprocess.tile.tileset.Tileset; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;
2,341
package com.gaia3d.process; @Slf4j @AllArgsConstructor public class ProcessFlowThread implements Process { private List<PreProcess> preProcesses;
package com.gaia3d.process; @Slf4j @AllArgsConstructor public class ProcessFlowThread implements Process { private List<PreProcess> preProcesses;
private TileProcess tileProcess;
5
2023-11-30 01:59:44+00:00
4k
xuemingqi/x-cloud
x-config/src/main/java/com/x/config/filter/BaseFilter.java
[ { "identifier": "CommonConstant", "path": "x-common/src/main/java/com/x/common/constants/CommonConstant.java", "snippet": "public class CommonConstant {\n\n /**\n * traceId\n */\n public static final String TRACE_ID = \"traceId\";\n\n /**\n * ip\n */\n public static final String IP = \"ip\";\n\n /**\n * token\n */\n public static final String TOKEN = \"X-TOKEN\";\n\n public static final String TOKEN_PRE = \"Bearer \";\n\n public static final String INTERNAL_TOKEN = \"X-Internal-Token\";\n\n public static final String INTERNAL_TIMESTAMP = \"X-Internal-Timestamp\";\n\n /**\n * redis pre\n */\n public static final String TOKEN_KEY = \"x_token:\";\n\n public static final String VERIFICATION_CODE_ID = \"x_code_id:\";\n\n public static final String LOCK_MOBILE = \"x-lock_mobile:\";\n\n public static final String LOGIN_FAIL = \"x_login_fail:\";\n\n public static int EXPIRE_TIME = 120;\n\n public static String KEY = \"dfb35213c7834bd5a97ca4d46f5e101f\";\n\n}" }, { "identifier": "ServletUtil", "path": "x-common/src/main/java/com/x/common/utils/ServletUtil.java", "snippet": "@Slf4j\npublic class ServletUtil {\n private static final String[] ipHeaders = {\"X-Real-IP\", \"Proxy-Client-IP\", \"WL-Proxy-Client-IP\", \"x-forwarded-for\"};\n\n\n /**\n * 获取请求对象\n *\n * @return HttpServlet请求对象\n */\n public static HttpServletRequest getRequest() {\n ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n return Objects.requireNonNull(requestAttributes).getRequest();\n }\n\n\n /**\n * 获取响应对象\n *\n * @return HttpServlet响应对象\n */\n public static HttpServletResponse getResponse() {\n ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();\n return Objects.requireNonNull(requestAttributes).getResponse();\n }\n\n\n /**\n * 获取全路径\n *\n * @return 全路径\n */\n public static String getRequestURL() {\n return getRequest().getRequestURL().toString();\n }\n\n\n /**\n * 获取项目路径\n *\n * @return 项目路径\n */\n public static String getContextPath() {\n return getRequest().getContextPath();\n }\n\n\n /**\n * 获取项目路径后续部分\n *\n * @return 项目路径后续部分\n */\n public static String getServletPath() {\n return getRequest().getServletPath();\n }\n\n\n /**\n * 获取除domain的路径\n *\n * @return 除domain的路径\n */\n public static String getRequestURI() {\n return getRequest().getRequestURI();\n }\n\n /**\n * 获取除请求头内容\n *\n * @param key 请求头\n * @return 请求头内容\n */\n\n public static String getHeader(String key) {\n return getRequest().getHeader(key);\n }\n\n\n /**\n * 获取客户端浏览器信息\n *\n * @return 客户端浏览器信息\n */\n public static UserAgent getUserAgent() {\n return UserAgent.parseUserAgentString(getRequest().getHeader(\"User-Agent\"));\n }\n\n\n /**\n * 获取服务名称\n *\n * @return 服务名称\n */\n public static String getServerName() {\n return getRequest().getServerName();\n }\n\n\n /**\n * 获取服务监听端口\n *\n * @return 服务监听端口\n */\n public static int getServerPort() {\n return getRequest().getServerPort();\n }\n\n\n /**\n * 获取远程请求IP地址\n *\n * @return 远程请求IP地址\n */\n public static String getRemoteIP() {\n final HttpServletRequest request = getRequest();\n for (final String ipHeader : ipHeaders) {\n final String ip = request.getHeader(ipHeader);\n if (ip != null && !ip.trim().isEmpty()) {\n return ip.trim();\n }\n }\n return request.getRemoteAddr();\n }\n\n\n /**\n * 获取国家标识\n */\n public static Locale getRemoteCountry() {\n final HttpServletRequest request = getRequest();\n return request.getLocale();\n }\n\n\n /**\n * 获取远程请求端口\n *\n * @return 远程请求端口\n */\n public static int getRemotePort() {\n final HttpServletRequest request = getRequest();\n try {\n return Integer.parseInt(request.getHeader(\"X-Real-PORT\"));\n } catch (final Exception e) {\n return request.getRemotePort();\n }\n }\n\n\n /**\n * 获取请求Scheme\n *\n * @return requestScheme\n */\n public static String getRequestScheme() {\n if (StringUtils.isBlank(getRequest().getHeader(\"X-Forwarded-Scheme\"))) {\n return getRequest().getScheme();\n }\n return getRequest().getHeader(\"X-Forwarded-Scheme\");\n }\n\n\n /**\n * 跳转到指定URL\n *\n * @param url URL地址\n */\n public static void redirectUrl(final String url) {\n final HttpServletResponse response = getResponse();\n try {\n response.sendRedirect(url);\n response.flushBuffer();\n } catch (final Exception e) {\n log.error(\"\", e);\n }\n }\n\n public static BufferedInputStream getBufferedInputStream() throws IOException {\n return new BufferedInputStream(getRequest().getInputStream(), 32 * 1024);\n }\n\n\n public static BufferedOutputStream getBufferedOutputStream() throws IOException {\n return new BufferedOutputStream(getResponse().getOutputStream(), 32 * 1024);\n }\n}" } ]
import com.x.common.constants.CommonConstant; import com.x.common.utils.ServletUtil; import org.slf4j.MDC; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException;
1,636
package com.x.config.filter; /** * @author xuemingqi */ @Configuration public class BaseFilter { @Bean public Filter filter() { return new Filter() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest) servletRequest; String traceId = req.getHeader(CommonConstant.TRACE_ID); MDC.put(CommonConstant.TRACE_ID, traceId);
package com.x.config.filter; /** * @author xuemingqi */ @Configuration public class BaseFilter { @Bean public Filter filter() { return new Filter() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest) servletRequest; String traceId = req.getHeader(CommonConstant.TRACE_ID); MDC.put(CommonConstant.TRACE_ID, traceId);
MDC.put(CommonConstant.IP, ServletUtil.getRemoteIP());
1
2023-11-27 08:23:38+00:00
4k
okx/OKBund
aa-task/src/main/java/com/okcoin/dapp/bundler/task/logevent/LogEventService.java
[ { "identifier": "ChainUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/ChainUtil.java", "snippet": "public class ChainUtil {\n\n //region getBlockNumber getNonce getGasPrice getNetVersion getChainId\n\n @SneakyThrows\n public static BigInteger getBlockNumber(IChain chain) {\n EthBlockNumber ethBlockNumber = chain.getWeb3j().ethBlockNumber().send();\n ChainErrorUtil.throwChainError(ethBlockNumber);\n return ethBlockNumber.getBlockNumber();\n }\n\n @SneakyThrows\n public static String getNetVersion(IChain chain) {\n NetVersion netVersion = chain.getWeb3j().netVersion().send();\n ChainErrorUtil.throwChainError(netVersion);\n return netVersion.getNetVersion();\n }\n\n @SneakyThrows\n public static BigInteger getChainId(IChain chain) {\n EthChainId ethChainId = chain.getWeb3j().ethChainId().send();\n ChainErrorUtil.throwChainError(ethChainId);\n return ethChainId.getChainId();\n }\n\n @SneakyThrows\n public static String getWeb3ClientVersion(IChain chain) {\n Web3ClientVersion web3ClientVersion = chain.getWeb3j().web3ClientVersion().send();\n ChainErrorUtil.throwChainError(web3ClientVersion);\n return web3ClientVersion.getWeb3ClientVersion();\n }\n //endregion\n\n\n @SneakyThrows\n public static TxPoolContent.TxPoolContentResult getTxPoolContent(IChain chain) {\n TxPoolContent txPoolContent = chain.getWeb3j().txPoolContent().send();\n ChainErrorUtil.throwChainError(txPoolContent);\n return txPoolContent.getResult();\n }\n\n}" }, { "identifier": "ReceiptUtil", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/ReceiptUtil.java", "snippet": "public class ReceiptUtil {\n\n @SneakyThrows\n public static List<Log> getLogs(DefaultBlockParameter blockNumberStart, DefaultBlockParameter blockNumberEnd, List<String> addresses, IChain chain, String... topics) {\n EthFilter ethFilter = new EthFilter(blockNumberStart, blockNumberEnd, addresses);\n ethFilter.addOptionalTopics(topics);\n EthLog ethLog = chain.getWeb3j().ethGetLogs(ethFilter).send();\n ChainErrorUtil.throwChainError(ethLog);\n if (ethLog.getLogs() == null || ethLog.getLogs().isEmpty()) {\n return Lists.newArrayList();\n }\n return ethLog.getLogs().stream().map(l -> ((EthLog.LogObject) l.get()).get()).collect(Collectors.toList());\n }\n\n public static List<Log> getLogs(long blockNumberStart, long blockNumberEnd, List<String> addresses, IChain chain, String... topics) {\n return getLogs(DefaultBlockParameter.valueOf(BigInteger.valueOf(blockNumberStart)), DefaultBlockParameter.valueOf(BigInteger.valueOf(blockNumberEnd)), addresses, chain, topics);\n }\n\n public static List<Log> getLogs(long blockNumber, List<String> addresses, IChain chain, String... topics) {\n return getLogs(blockNumber, blockNumber, addresses, chain, topics);\n }\n\n public static List<Log> getLogs(long blockNumber, String address, IChain chain, String... topics) {\n return getLogs(blockNumber, Collections.singletonList(address), chain, topics);\n }\n\n @SneakyThrows\n public static EthBlock.Block getBlock(DefaultBlockParameter defaultBlockParameter, IChain chain) {\n EthBlock ethBlock = chain.getWeb3j().ethGetBlockByNumber(defaultBlockParameter, true).send();\n ChainErrorUtil.throwChainError(ethBlock);\n return ethBlock.getBlock();\n }\n\n public static EthBlock.Block getBlock(long blockNumber, IChain chain) {\n return getBlock(DefaultBlockParameter.valueOf(BigInteger.valueOf(blockNumber)), chain);\n }\n\n @SneakyThrows\n public static Transaction getTransactionByHash(String txHash, IChain chain) {\n EthTransaction ethTransaction = chain.getWeb3j().ethGetTransactionByHash(txHash).send();\n ChainErrorUtil.throwChainError(ethTransaction);\n return ethTransaction.getTransaction().orElse(null);\n }\n\n @SneakyThrows\n public static TransactionReceiptCommon getTransactionReceipt(String txHash, IChain chain) {\n EthGetTransactionReceipt transactionReceipt = chain.getWeb3j().ethGetTransactionReceipt(txHash).send();\n ChainErrorUtil.throwChainError(transactionReceipt);\n\n JSONObject result = JSON.parseObject(transactionReceipt.getRawResponse()).getJSONObject(\"result\");\n if (result == null) {\n return null;\n }\n\n TransactionReceiptCommon receipt;\n if (chain.getChainId() == ChainIdConstant.OP_MAIN) {\n receipt = result.toJavaObject(TransactionReceiptOp.class);\n } else if (chain.getChainId() == ChainIdConstant.ARB_MAIN) {\n receipt = result.toJavaObject(TransactionReceiptArb.class);\n } else {\n receipt = result.toJavaObject(TransactionReceiptCommon.class);\n }\n\n receipt.setRawResponse(result.toJSONString());\n return receipt;\n\n }\n}" }, { "identifier": "BlockHeightSignEntity", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/storage/DTO/BlockHeightSignEntity.java", "snippet": "@Data\npublic class BlockHeightSignEntity implements Serializable {\n private Long chainId;\n private Long blockHeight;\n}" }, { "identifier": "BlockHeightSignDAO", "path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/storage/dao/BlockHeightSignDAO.java", "snippet": "@Component\npublic class BlockHeightSignDAO extends AbstractTemplate<BlockHeightSignEntity> {\n @Override\n public String getTableName() {\n return \"/block_height_sign\";\n }\n\n @Override\n public String getSaveKey(BlockHeightSignEntity blockHeightSignEntity) {\n return String.valueOf(blockHeightSignEntity.getChainId());\n }\n\n @Override\n public Class<BlockHeightSignEntity> getTClass() {\n return BlockHeightSignEntity.class;\n }\n}" }, { "identifier": "ChainConfig", "path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/config/ChainConfig.java", "snippet": "@Component\n@Getter\npublic class ChainConfig implements IChain {\n\n private static final int DEFAULT_BLOCK_TIME_MS = 1000;\n\n private final long chainId;\n\n private final boolean eip1559;\n\n private final int blockTime;\n\n @Setter\n private Web3jDebug web3j;\n\n public ChainConfig(PoolConfig poolConfig) {\n this.chainId = poolConfig.getChainId();\n this.eip1559 = poolConfig.isEip1559();\n this.blockTime = poolConfig.getBlockTime() == null ? DEFAULT_BLOCK_TIME_MS : poolConfig.getBlockTime();\n HttpService web3jService = new HttpService(poolConfig.getRpc(), true);\n this.web3j = Web3jDebug.build(web3jService);\n }\n\n}" }, { "identifier": "PoolConfig", "path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/config/PoolConfig.java", "snippet": "@Configuration\n@ConfigurationProperties(prefix = \"pool.core\")\n@Data\npublic class PoolConfig {\n\n private boolean safeMode;\n\n private Long chainId;\n\n private boolean eip1559;\n\n private String rpc;\n\n private String entrypoint;\n\n private long maxMempoolSize;\n\n private int autoBundleInterval;\n\n private String entrypointRuntimeCodeV6;\n\n private Integer blockTime;\n\n public void setEntrypoint(String entrypoint) {\n this.entrypoint = entrypoint.toLowerCase();\n }\n\n}" }, { "identifier": "AccountDeployedEvent", "path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/domain/event/AccountDeployedEvent.java", "snippet": "@Getter\npublic class AccountDeployedEvent implements IEvent {\n\n public static final Event EVENT = new Event(\"UserOperationEvent\", Lists.newArrayList(\n TypeReference.create(Bytes32.class, true), TypeReference.create(Address.class, true),\n TypeReference.create(Address.class), TypeReference.create(Address.class)));\n\n public static final String EVENT_SIG = EventEncoder.encode(EVENT);\n\n private final String userOpHash;\n\n private final String sender;\n\n private final String factory;\n\n private final String paymaster;\n\n private final Log log;\n\n public AccountDeployedEvent(Log logEvent) {\n this.log = logEvent;\n EventValues eventValues = Contract.staticExtractEventParameters(EVENT, log);\n List<Type> indexedValues = eventValues.getIndexedValues();\n List<Type> nonIndexedValues = eventValues.getNonIndexedValues();\n userOpHash = Numeric.toHexString(((Bytes32) (indexedValues.get(0))).getValue());\n sender = ((Address) indexedValues.get(1)).getValue();\n factory = ((Address) nonIndexedValues.get(0)).getValue();\n paymaster = ((Address) nonIndexedValues.get(1)).getValue();\n }\n\n public static boolean isMatched(Log logEvent) {\n return EVENT_SIG.equals(logEvent.getTopics().get(0));\n }\n\n}" }, { "identifier": "UserOperationEvent", "path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/domain/event/UserOperationEvent.java", "snippet": "@Getter\npublic class UserOperationEvent implements IEvent {\n\n public static final Event EVENT = new Event(\"UserOperationEvent\", Lists.newArrayList(\n TypeReference.create(Bytes32.class, true), TypeReference.create(Address.class, true),\n TypeReference.create(Address.class, true), TypeReference.create(Uint256.class),\n TypeReference.create(Bool.class), TypeReference.create(Uint256.class), TypeReference.create(Uint256.class)));\n\n public static final String EVENT_SIG = EventEncoder.encode(EVENT);\n\n private final String userOpHash;\n\n private final String sender;\n\n private final String paymaster;\n\n private final BigInteger nonce;\n\n private final boolean success;\n\n private final BigInteger actualGasCost;\n\n private final BigInteger actualGasUsed;\n\n private final Log log;\n\n public UserOperationEvent(Log log) {\n this.log = log;\n EventValues eventValues = Contract.staticExtractEventParameters(EVENT, log);\n List<Type> indexedValues = eventValues.getIndexedValues();\n List<Type> nonIndexedValues = eventValues.getNonIndexedValues();\n userOpHash = Numeric.toHexString(((Bytes32) (indexedValues.get(0))).getValue());\n sender = ((Address) indexedValues.get(1)).getValue();\n paymaster = ((Address) indexedValues.get(2)).getValue();\n nonce = ((Uint256) nonIndexedValues.get(0)).getValue();\n success = ((Bool) nonIndexedValues.get(1)).getValue();\n actualGasCost = ((Uint256) nonIndexedValues.get(2)).getValue();\n actualGasUsed = ((Uint256) nonIndexedValues.get(3)).getValue();\n }\n\n public static boolean isMatch(Log log) {\n return EVENT_SIG.equals(log.getTopics().get(0));\n }\n\n}" }, { "identifier": "OnChainResultService", "path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/result/OnChainResultService.java", "snippet": "@Slf4j\n@Service\npublic class OnChainResultService {\n\n @Resource\n private UopAndTxMapDAO uopAndTxMapDAO;\n @Resource\n private ReputationService reputationService;\n @Resource\n private MempoolService mempoolService;\n\n public boolean processLogEvent(Log logEvent) {\n if (UserOperationEvent.isMatch(logEvent)) {\n processUopEvent(new UserOperationEvent(logEvent));\n } else {\n processDeployAccountEvent(new AccountDeployedEvent(logEvent));\n }\n // TODO YUKINO 2023/10/31: getEventAggregator\n return true;\n }\n\n private void processUopEvent(UserOperationEvent uopEvent) {\n String sender = uopEvent.getSender();\n String txHash = uopEvent.getTransactionHash();\n String uopHash = uopEvent.getUserOpHash();\n String paymaster = uopEvent.getPaymaster();\n log.info(\"receive uop event for sender: {}, uop_hash: {}, tx_hash: {}\", sender, uopHash, txHash);\n UopAndTxMapEntity entity = new UopAndTxMapEntity();\n entity.setOpHash(uopHash);\n entity.setTxHash(txHash);\n uopAndTxMapDAO.save(entity);\n log.info(\"add opIncluded for sender: {}, paymaster: {}, by uop_hash: {}\", sender, paymaster, uopHash);\n updateAddressIncluded(sender, uopEvent.getPaymaster());\n //remove uop\n mempoolService.removeUop(uopEvent.getSender(), uopEvent.getNonce());\n }\n\n private void processDeployAccountEvent(AccountDeployedEvent event) {\n log.info(\"process account map factory event for hash: {}, account: {}, factory: {}\", event.getTransactionHash(),\n event.getSender(), event.getFactory());\n updateAddressIncluded(event.getFactory());\n }\n\n private void updateAddressIncluded(String... addressArr) {\n Arrays.stream(addressArr).forEach(address -> reputationService.updateIncludedStatus(address));\n }\n\n}" }, { "identifier": "LogEventConstant", "path": "aa-task/src/main/java/com/okcoin/dapp/bundler/task/constant/LogEventConstant.java", "snippet": "public interface LogEventConstant {\n\n int LOG_EVENT_THREAD_POOL_CORE_SIZE = 2;\n int LOG_EVENT_THREAD_POOL_MAX_SIZE = 2;\n int LOG_EVENT_THREAD_POOL_MAX_QUEUE_SIZE = 1000;\n int BACKTRACK_BLOCK_SIZE = 1000;\n int PULL_BLOCK_SIZE = 1000;\n\n}" } ]
import com.google.common.collect.Lists; import com.okcoin.dapp.bundler.infra.chain.ChainUtil; import com.okcoin.dapp.bundler.infra.chain.ReceiptUtil; import com.okcoin.dapp.bundler.infra.storage.DTO.BlockHeightSignEntity; import com.okcoin.dapp.bundler.infra.storage.dao.BlockHeightSignDAO; import com.okcoin.dapp.bundler.pool.config.ChainConfig; import com.okcoin.dapp.bundler.pool.config.PoolConfig; import com.okcoin.dapp.bundler.pool.domain.event.AccountDeployedEvent; import com.okcoin.dapp.bundler.pool.domain.event.UserOperationEvent; import com.okcoin.dapp.bundler.pool.result.OnChainResultService; import com.okcoin.dapp.bundler.task.constant.LogEventConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.web3j.protocol.core.methods.response.Log; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
3,528
package com.okcoin.dapp.bundler.task.logevent; /** * @Author fanweiqiang * @create 2023/10/24 17:54 */ @Slf4j @Component public class LogEventService { private Long lastProcessBlockHeight; @Resource
package com.okcoin.dapp.bundler.task.logevent; /** * @Author fanweiqiang * @create 2023/10/24 17:54 */ @Slf4j @Component public class LogEventService { private Long lastProcessBlockHeight; @Resource
private OnChainResultService onChainResultService;
8
2023-11-27 10:54:49+00:00
4k
lidaofu-hub/j_media_server
src/main/java/com/ldf/media/api/service/impl/ApiServiceImpl.java
[ { "identifier": "MediaInfoResult", "path": "src/main/java/com/ldf/media/api/model/result/MediaInfoResult.java", "snippet": "@Data\n@ApiModel(value = \"GetMediaListParam对象\", description = \"流信息\")\npublic class MediaInfoResult implements Serializable {\n\n private static final long serialVersionUID = 1;\n\n @ApiModelProperty(value = \"app\")\n private String app;\n\n @ApiModelProperty(value = \"流id\")\n private String stream;\n\n @ApiModelProperty(value = \"本协议观看人数\")\n private Integer readerCount;\n\n @ApiModelProperty(value = \"产生源类型,包括 unknown = 0,rtmp_push=1,rtsp_push=2,rtp_push=3,pull=4,ffmpeg_pull=5,mp4_vod=6,device_chn=7\")\n private Integer originType;\n\n @ApiModelProperty(value = \"产生源的url\")\n private String originUrl;\n\n @ApiModelProperty(value = \"产生源的url的类型\")\n private String originTypeStr;\n\n @ApiModelProperty(value = \"观看总数 包括hls/rtsp/rtmp/http-flv/ws-flv\")\n private Integer totalReaderCount;\n\n @ApiModelProperty(value = \"schema\")\n private String schema;\n\n @ApiModelProperty(value = \"存活时间,单位秒\")\n private Integer aliveSecond;\n\n @ApiModelProperty(value = \"数据产生速度,单位byte/s\")\n private Long bytesSpeed;\n\n @ApiModelProperty(value = \"GMT unix系统时间戳,单位秒\")\n private Long createStamp;\n\n @ApiModelProperty(value = \"是否录制Hls\")\n private Boolean isRecordingHLS;\n\n @ApiModelProperty(value = \"是否录制mp4\")\n private Boolean isRecordingMP4;\n\n @ApiModelProperty(value = \"虚拟地址\")\n private String vhost;\n\n private List<Track> tracks;\n\n\n}" }, { "identifier": "Track", "path": "src/main/java/com/ldf/media/api/model/result/Track.java", "snippet": "@Data\npublic class Track implements Serializable {\n private static final long serialVersionUID = 1;\n\n private Integer is_video;\n private Integer codec_id;\n private String codec_id_name;\n private Integer codec_type;\n private Integer fps;\n private Integer frames;\n private Integer bit_rate;\n private Integer gop_interval_ms;\n private Integer gop_size;\n private Integer height;\n private Integer key_frames;\n private Integer loss;\n private Boolean ready;\n private Integer width;\n private Integer sample_rate;\n private Integer audio_channel;\n private Integer audio_sample_bit;\n\n}" }, { "identifier": "IApiService", "path": "src/main/java/com/ldf/media/api/service/IApiService.java", "snippet": "public interface IApiService {\n\n void addStreamProxy(StreamProxyParam param);\n\n Integer closeStream(CloseStreamParam param);\n\n Integer closeStreams(CloseStreamsParam param);\n List<MediaInfoResult> getMediaList(GetMediaListParam param);\n\n Boolean startRecord(StartRecordParam param);\n\n Boolean stopRecord(StopRecordParam param);\n\n Boolean isRecording(RecordStatusParam param);\n}" }, { "identifier": "MKSourceFindCallBack", "path": "src/main/java/com/ldf/media/callback/MKSourceFindCallBack.java", "snippet": "public class MKSourceFindCallBack implements IMKSourceFindCallBack {\n private IMKSourceHandleCallBack imkSourceHandleCallBack;\n\n public MKSourceFindCallBack(IMKSourceHandleCallBack imkSourceHandleCallBack) {\n this.imkSourceHandleCallBack = imkSourceHandleCallBack;\n //回调使用同一个线程\n Native.setCallbackThreadInitializer(this, new CallbackThreadInitializer(true, false, \"MediaSourceFindThread\"));\n }\n\n public void invoke(Pointer user_data, MK_MEDIA_SOURCE ctx) {\n imkSourceHandleCallBack.invoke(ctx);\n }\n}" }, { "identifier": "MediaServerConstants", "path": "src/main/java/com/ldf/media/constants/MediaServerConstants.java", "snippet": "public interface MediaServerConstants {\n\n /**\n * 默认vhost\n */\n String DEFAULT_VHOST=\"__defaultVhost__\";\n\n /**\n * 默认app\n */\n String DEFAULT_APP=\"live\";\n}" }, { "identifier": "MediaServerContext", "path": "src/main/java/com/ldf/media/context/MediaServerContext.java", "snippet": "@Slf4j\n@Component\npublic class MediaServerContext {\n @Autowired\n private MediaServerConfig config;\n public static ZLMApi ZLM_API = null;\n private static MK_EVENTS MK_EVENTS = null;\n\n @PostConstruct\n public void initMediaServer() {\n ZLM_API = Native.load(\"mk_api\", ZLMApi.class);\n log.info(\"【MediaServer】初始化MediaServer程序成功\");\n this.initServerConf();\n }\n\n\n public void initServerConf() {\n //初始化环境配置\n MK_INI mkIni = ZLM_API.mk_ini_default();\n ZLM_API.mk_ini_set_option(mkIni, \"general.mediaServerId\", \"JMediaServer\");\n ZLM_API.mk_ini_set_option(mkIni, \"http.notFound\", \"<h1 style=\\\"text-align:center;\\\">Media Server V1.0 By LiDaoFu</h1>\");\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.auto_close\", config.getAuto_close());\n ZLM_API.mk_ini_set_option_int(mkIni, \"general.streamNoneReaderDelayMS\", config.getStreamNoneReaderDelayMS());\n ZLM_API.mk_ini_set_option_int(mkIni, \"general.maxStreamWaitMS\", config.getMaxStreamWaitMS());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_ts\", config.getEnable_ts());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_hls\", config.getEnable_hls());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_fmp4\", config.getEnable_fmp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_rtsp\", config.getEnable_rtsp());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_rtmp\", config.getEnable_rtmp());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_mp4\", config.getEnable_mp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_hls_fmp4\", config.getEnable_hls_fmp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_audio\", config.getEnable_audio());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.mp4_as_player\", config.getMp4_as_player());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.mp4_max_second\", config.getMp4_max_second());\n ZLM_API.mk_ini_set_option(mkIni, \"http.rootPath\", config.getRootPath());\n ZLM_API.mk_ini_set_option(mkIni, \"protocol.mp4_save_path\", config.getMp4_save_path());\n ZLM_API.mk_ini_set_option(mkIni, \"protocol.hls_save_path\", config.getHls_save_path());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.hls_demand\", config.getHls_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.rtsp_demand\", config.getRtsp_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.rtmp_demand\", config.getRtmp_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.ts_demand\", config.getTs_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.fmp4_demand\", config.getFmp4_demand());\n //全局回调\n MK_EVENTS = new MK_EVENTS();\n MK_EVENTS.on_mk_media_changed = new MKStreamChangeCallBack();\n MK_EVENTS.on_mk_media_no_reader = new MKNoReaderCallBack();\n MK_EVENTS.on_mk_media_publish = new MKPublishCallBack();\n MK_EVENTS.on_mk_media_not_found = new MKNoFoundCallBack();\n MK_EVENTS.on_mk_flow_report = new MKHttpFlowReportCallBack();\n MK_EVENTS.on_mk_media_play = new MKPlayCallBack();\n /* MK_EVENTS.on_mk_http_access = new MKHttpAccessCallBack();\n MK_EVENTS.on_mk_http_request = new MKHttpRequestCallBack();\n MK_EVENTS.on_mk_http_access = new MKHttpAccessCallBack();\n MK_EVENTS.on_mk_http_before_access = new MKHttpBeforeAccessCallBack();*/\n MK_EVENTS.on_mk_record_mp4 = new MKRecordMp4CallBack();\n MK_EVENTS.on_mk_log = new MKLogCallBack();\n //添加全局回调\n ZLM_API.mk_events_listen(MK_EVENTS);\n //初始化zmk服务器\n ZLM_API.mk_env_init1(config.getThread_num(), config.getLog_level(), config.getLog_mask(), config.getLog_path(), config.getLog_file_days(), 0, null, 0, null, null);\n //创建http服务器 0:失败,非0:端口号\n short http_server_port = ZLM_API.mk_http_server_start(config.getHttp_port().shortValue(), 0);\n log.info(\"【MediaServer】HTTP流媒体服务启动:{}\", http_server_port == 0 ? \"失败\" : \"成功,端口:\" + http_server_port);\n //创建rtsp服务器 0:失败,非0:端口号\n short rtsp_server_port = ZLM_API.mk_rtsp_server_start(config.getRtsp_port().shortValue(), 0);\n log.info(\"【MediaServer】RTSP流媒体服务启动:{}\", rtsp_server_port == 0 ? \"失败\" : \"成功,端口:\" + rtsp_server_port);\n //创建rtmp服务器 0:失败,非0:端口号\n short rtmp_server_port = ZLM_API.mk_rtmp_server_start(config.getRtmp_port().shortValue(), 0);\n log.info(\"【MediaServer】RTMP流媒体服务启动:{}\", rtmp_server_port == 0 ? \"失败\" : \"成功,端口:\" + rtmp_server_port);\n }\n\n @PreDestroy\n public void release() {\n ZLM_API.mk_stop_all_server();\n log.info(\"【MediaServer】关闭所有流媒体服务\");\n }\n}" }, { "identifier": "IMKProxyPlayCloseCallBack", "path": "src/main/java/com/ldf/media/sdk/callback/IMKProxyPlayCloseCallBack.java", "snippet": "public interface IMKProxyPlayCloseCallBack extends Callback {\n /**\n * MediaSource.close()回调事件\n * 在选择关闭一个关联的MediaSource时,将会最终触发到该回调\n * 你应该通过该事件调用mk_proxy_player_release函数并且释放其他资源\n * 如果你不调用mk_proxy_player_release函数,那么MediaSource.close()操作将无效\n *\n * @param pUser 用户数据指针,通过mk_proxy_player_set_on_close函数设置\n */\n public void invoke(Pointer pUser, int err, String what, int sys_err);\n}" }, { "identifier": "MK_MEDIA_SOURCE", "path": "src/main/java/com/ldf/media/sdk/structure/MK_MEDIA_SOURCE.java", "snippet": "public class MK_MEDIA_SOURCE extends SdkStructure {\n public int dwSize;\n public MK_MEDIA_SOURCE(Pointer pointer) {\n super(pointer);\n }\n public MK_MEDIA_SOURCE() {\n }\n}" }, { "identifier": "MK_PROXY_PLAYER", "path": "src/main/java/com/ldf/media/sdk/structure/MK_PROXY_PLAYER.java", "snippet": "public class MK_PROXY_PLAYER extends SdkStructure {\n public int dwSize;\n public MK_PROXY_PLAYER(Pointer pointer) {\n super(pointer);\n }\n public MK_PROXY_PLAYER() {\n }\n\n}" }, { "identifier": "MK_TRACK", "path": "src/main/java/com/ldf/media/sdk/structure/MK_TRACK.java", "snippet": "public class MK_TRACK extends SdkStructure {\n public int dwSize;\n\n public MK_TRACK(Pointer pointer){\n super(pointer);\n }\n public MK_TRACK() {\n }\n}" } ]
import cn.hutool.core.lang.Assert; import com.ldf.media.api.model.param.*; import com.ldf.media.api.model.result.MediaInfoResult; import com.ldf.media.api.model.result.Track; import com.ldf.media.api.service.IApiService; import com.ldf.media.callback.MKSourceFindCallBack; import com.ldf.media.constants.MediaServerConstants; import com.ldf.media.context.MediaServerContext; import com.ldf.media.sdk.callback.IMKProxyPlayCloseCallBack; import com.ldf.media.sdk.structure.MK_MEDIA_SOURCE; import com.ldf.media.sdk.structure.MK_PROXY_PLAYER; import com.ldf.media.sdk.structure.MK_TRACK; import com.sun.jna.Pointer; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference;
2,999
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在
package com.ldf.media.api.service.impl; /** * 接口服务 * * @author lidaofu * @since 2023/11/29 **/ @Service public class ApiServiceImpl implements IApiService { @Override public void addStreamProxy(StreamProxyParam param) { //查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
5
2023-11-29 07:47:56+00:00
4k
qdrant/java-client
src/test/java/io/qdrant/client/PointsTest.java
[ { "identifier": "QdrantContainer", "path": "src/test/java/io/qdrant/client/container/QdrantContainer.java", "snippet": "public class QdrantContainer extends GenericContainer<QdrantContainer> {\n\n private static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse(\"qdrant/qdrant\");\n private static final String DEFAULT_TAG = System.getProperty(\"qdrantVersion\");\n private static final int GRPC_PORT = 6334;\n private static final int HTTP_PORT = 6333;\n\n public QdrantContainer() {\n this(DEFAULT_IMAGE_NAME.withTag(DEFAULT_TAG));\n }\n\n public QdrantContainer(String dockerImageName) {\n this(DockerImageName.parse(dockerImageName));\n }\n\n public QdrantContainer(final DockerImageName dockerImageName) {\n super(dockerImageName);\n\n addExposedPorts(GRPC_PORT, HTTP_PORT);\n\n setWaitStrategy(new LogMessageWaitStrategy().withRegEx(\".*Actix runtime found; starting in Actix runtime.*\"));\n }\n\n public QdrantContainer withApiKey(String apiKey) {\n return withEnv(\"QDRANT__SERVICE__API_KEY\", apiKey);\n }\n\n public String getGrpcHostAddress() {\n return getHost() + \":\" + getMappedPort(GRPC_PORT);\n }\n\n public String getHttpHostAddress() {\n return getHost() + \":\" + getMappedPort(HTTP_PORT);\n }\n}" }, { "identifier": "hasId", "path": "src/main/java/io/qdrant/client/ConditionFactory.java", "snippet": "public static Condition hasId(PointId id) {\n\treturn Condition.newBuilder()\n\t\t.setHasId(HasIdCondition.newBuilder()\n\t\t\t.addHasId(id)\n\t\t\t.build())\n\t\t.build();\n}" }, { "identifier": "matchKeyword", "path": "src/main/java/io/qdrant/client/ConditionFactory.java", "snippet": "public static Condition matchKeyword(String field, String keyword) {\n\treturn Condition.newBuilder()\n\t\t.setField(FieldCondition.newBuilder()\n\t\t\t.setKey(field)\n\t\t\t.setMatch(Match.newBuilder()\n\t\t\t\t.setKeyword(keyword)\n\t\t\t\t.build())\n\t\t\t.build())\n\t\t.build();\n}" }, { "identifier": "id", "path": "src/main/java/io/qdrant/client/PointIdFactory.java", "snippet": "public static PointId id(long id) {\n\treturn PointId.newBuilder().setNum(id).build();\n}" }, { "identifier": "targetVector", "path": "src/main/java/io/qdrant/client/TargetVectorFactory.java", "snippet": "public static TargetVector targetVector(PointId id) {\n return TargetVector.newBuilder().setSingle(VectorExample.newBuilder().setId(id)).build();\n}" }, { "identifier": "value", "path": "src/main/java/io/qdrant/client/ValueFactory.java", "snippet": "public static Value value(String value) {\n\treturn Value.newBuilder().setStringValue(value).build();\n}" }, { "identifier": "vector", "path": "src/main/java/io/qdrant/client/VectorFactory.java", "snippet": "public static Vector vector(List<Float> values) {\n return Vector.newBuilder().addAllData(values).build();\n}" }, { "identifier": "vectors", "path": "src/main/java/io/qdrant/client/VectorsFactory.java", "snippet": "public static Vectors vectors(List<Float> values) {\n\treturn Vectors.newBuilder()\n\t\t.setVector(vector(values))\n\t\t.build();\n}" } ]
import io.grpc.Grpc; import io.grpc.InsecureChannelCredentials; import io.grpc.ManagedChannel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import io.qdrant.client.container.QdrantContainer; import io.qdrant.client.grpc.Points.DiscoverPoints; import io.qdrant.client.grpc.Points.PointVectors; import io.qdrant.client.grpc.Points.PointsIdsList; import io.qdrant.client.grpc.Points.PointsSelector; import io.qdrant.client.grpc.Points.PointsUpdateOperation; import io.qdrant.client.grpc.Points.UpdateBatchResponse; import io.qdrant.client.grpc.Points.PointsUpdateOperation.ClearPayload; import io.qdrant.client.grpc.Points.PointsUpdateOperation.UpdateVectors; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static io.qdrant.client.grpc.Collections.CollectionInfo; import static io.qdrant.client.grpc.Collections.CreateCollection; import static io.qdrant.client.grpc.Collections.Distance; import static io.qdrant.client.grpc.Collections.PayloadSchemaType; import static io.qdrant.client.grpc.Collections.VectorParams; import static io.qdrant.client.grpc.Collections.VectorsConfig; import static io.qdrant.client.grpc.Points.BatchResult; import static io.qdrant.client.grpc.Points.Filter; import static io.qdrant.client.grpc.Points.PointGroup; import static io.qdrant.client.grpc.Points.PointStruct; import static io.qdrant.client.grpc.Points.RecommendPointGroups; import static io.qdrant.client.grpc.Points.RecommendPoints; import static io.qdrant.client.grpc.Points.RetrievedPoint; import static io.qdrant.client.grpc.Points.ScoredPoint; import static io.qdrant.client.grpc.Points.ScrollPoints; import static io.qdrant.client.grpc.Points.ScrollResponse; import static io.qdrant.client.grpc.Points.SearchPointGroups; import static io.qdrant.client.grpc.Points.SearchPoints; import static io.qdrant.client.grpc.Points.UpdateResult; import static io.qdrant.client.grpc.Points.UpdateStatus; import static io.qdrant.client.grpc.Points.Vectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static io.qdrant.client.ConditionFactory.hasId; import static io.qdrant.client.ConditionFactory.matchKeyword; import static io.qdrant.client.PointIdFactory.id; import static io.qdrant.client.TargetVectorFactory.targetVector; import static io.qdrant.client.ValueFactory.value; import static io.qdrant.client.VectorFactory.vector; import static io.qdrant.client.VectorsFactory.vectors;
3,152
List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); } @Test public void createFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.createPayloadIndexAsync( testName, "bar", PayloadSchemaType.Integer, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); CollectionInfo collectionInfo = client.getCollectionInfoAsync(testName).get(); assertEquals(ImmutableSet.of("foo", "bar"), collectionInfo.getPayloadSchemaMap().keySet()); assertEquals(PayloadSchemaType.Keyword, collectionInfo.getPayloadSchemaMap().get("foo").getDataType()); assertEquals(PayloadSchemaType.Integer, collectionInfo.getPayloadSchemaMap().get("bar").getDataType()); } @Test public void deleteFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.deletePayloadIndexAsync( testName, "foo", null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); } @Test public void search() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<ScoredPoint> points = client.searchAsync( SearchPoints.newBuilder() .setCollectionName(testName) .setWithPayload(WithPayloadSelectorFactory.enable(true)) .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build()).get(); assertEquals(1, points.size()); ScoredPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertFalse(point.getVectors().hasVector()); } @Test public void searchBatch() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<BatchResult> batchResults = client.searchBatchAsync(testName, ImmutableList.of( SearchPoints.newBuilder() .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build(), SearchPoints.newBuilder() .addAllVector(ImmutableList.of(3.4f, 4.4f)) .setLimit(1) .build() ), null).get(); assertEquals(2, batchResults.size()); BatchResult result = batchResults.get(0); assertEquals(1, result.getResultCount()); assertEquals(id(9), result.getResult(0).getId()); result = batchResults.get(1); assertEquals(1, result.getResultCount()); assertEquals(id(8), result.getResult(0).getId()); } @Test public void searchGroups() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.upsertAsync( testName, ImmutableList.of( PointStruct.newBuilder() .setId(id(10))
package io.qdrant.client; @Testcontainers class PointsTest { @Container private static final QdrantContainer QDRANT_CONTAINER = new QdrantContainer(); private QdrantClient client; private ManagedChannel channel; private String testName; @BeforeEach public void setup(TestInfo testInfo) { testName = testInfo.getDisplayName().replace("()", ""); channel = Grpc.newChannelBuilder( QDRANT_CONTAINER.getGrpcHostAddress(), InsecureChannelCredentials.create()) .build(); QdrantGrpcClient grpcClient = QdrantGrpcClient.newBuilder(channel).build(); client = new QdrantClient(grpcClient); } @AfterEach public void teardown() throws Exception { List<String> collectionNames = client.listCollectionsAsync().get(); for (String collectionName : collectionNames) { client.deleteCollectionAsync(collectionName).get(); } client.close(); channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } @Test public void retrieve() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertEquals(Vectors.getDefaultInstance(), point.getVectors()); } @Test public void retrieve_with_vector_without_payload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<RetrievedPoint> points = client.retrieveAsync( testName, id(8), false, true, null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(8), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); assertEquals(Vectors.VectorsOptionsCase.VECTOR, point.getVectors().getVectorsOptionsCase()); } @Test public void setPayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.setPayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); } @Test public void overwritePayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.overwritePayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); } @Test public void deletePayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.setPayloadAsync( testName, ImmutableMap.of("bar", value("some bar")), id(9), null, null, null).get(); client.deletePayloadAsync(testName, ImmutableList.of("foo"), id(9), null, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("bar"), point.getPayloadMap().keySet()); assertEquals(value("some bar"), point.getPayloadMap().get("bar")); } @Test public void clearPayload() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.clearPayloadAsync(testName, id(9), true, null, null).get(); List<RetrievedPoint> points = client.retrieveAsync(testName, id(9), null).get(); assertEquals(1, points.size()); RetrievedPoint point = points.get(0); assertEquals(id(9), point.getId()); assertTrue(point.getPayloadMap().isEmpty()); } @Test public void createFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.createPayloadIndexAsync( testName, "bar", PayloadSchemaType.Integer, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); CollectionInfo collectionInfo = client.getCollectionInfoAsync(testName).get(); assertEquals(ImmutableSet.of("foo", "bar"), collectionInfo.getPayloadSchemaMap().keySet()); assertEquals(PayloadSchemaType.Keyword, collectionInfo.getPayloadSchemaMap().get("foo").getDataType()); assertEquals(PayloadSchemaType.Integer, collectionInfo.getPayloadSchemaMap().get("bar").getDataType()); } @Test public void deleteFieldIndex() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); UpdateResult result = client.createPayloadIndexAsync( testName, "foo", PayloadSchemaType.Keyword, null, null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); result = client.deletePayloadIndexAsync( testName, "foo", null, null, null).get(); assertEquals(UpdateStatus.Completed, result.getStatus()); } @Test public void search() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<ScoredPoint> points = client.searchAsync( SearchPoints.newBuilder() .setCollectionName(testName) .setWithPayload(WithPayloadSelectorFactory.enable(true)) .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build()).get(); assertEquals(1, points.size()); ScoredPoint point = points.get(0); assertEquals(id(9), point.getId()); assertEquals(ImmutableSet.of("foo", "bar"), point.getPayloadMap().keySet()); assertEquals(value("goodbye"), point.getPayloadMap().get("foo")); assertEquals(value(2), point.getPayloadMap().get("bar")); assertFalse(point.getVectors().hasVector()); } @Test public void searchBatch() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); List<BatchResult> batchResults = client.searchBatchAsync(testName, ImmutableList.of( SearchPoints.newBuilder() .addAllVector(ImmutableList.of(10.4f, 11.4f)) .setLimit(1) .build(), SearchPoints.newBuilder() .addAllVector(ImmutableList.of(3.4f, 4.4f)) .setLimit(1) .build() ), null).get(); assertEquals(2, batchResults.size()); BatchResult result = batchResults.get(0); assertEquals(1, result.getResultCount()); assertEquals(id(9), result.getResult(0).getId()); result = batchResults.get(1); assertEquals(1, result.getResultCount()); assertEquals(id(8), result.getResult(0).getId()); } @Test public void searchGroups() throws ExecutionException, InterruptedException { createAndSeedCollection(testName); client.upsertAsync( testName, ImmutableList.of( PointStruct.newBuilder() .setId(id(10))
.setVectors(VectorsFactory.vectors(30f, 31f))
7
2023-11-30 10:21:23+00:00
4k
seraxis/lr2oraja-endlessdream
core/src/bms/player/beatoraja/skin/SkinHeader.java
[ { "identifier": "Resolution", "path": "core/src/bms/player/beatoraja/Resolution.java", "snippet": "public enum Resolution {\n\tSD(640, 480),\n\tSVGA(800, 600),\n\tXGA(1024, 768),\n\tHD(1280, 720),\n\tQUADVGA(1280, 960),\n\tFWXGA(1366, 768),\n\tSXGAPLUS(1400, 1050),\n\tHDPLUS(1600, 900),\n\tUXGA(1600, 1200),\n\tWSXGAPLUS(1680,1050),\n\tFULLHD(1920, 1080),\n\tWUXGA(1920, 1200),\n\tQXGA(2048, 1536),\n\tWQHD(2560, 1440),\n\tULTRAHD(3840, 2160);\n\n\t/**\n\t * 幅\n\t */\n\tpublic final int width;\n\t/**\n\t * 高さ\n\t */\n\tpublic final int height;\n\n\tprivate Resolution(int width, int height) {\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn name() + \" (\" + width + \" x \" + height + \")\";\n\t}\n}" }, { "identifier": "SkinConfig", "path": "core/src/bms/player/beatoraja/SkinConfig.java", "snippet": "public class SkinConfig implements Validatable {\n\t/**\n\t * ファイルパス\n\t */\n\tprivate String path;\n\t/**\n\t * 設定項目\n\t */\n\tprivate Property properties;\n\n\tpublic SkinConfig() {\n\n\t}\n\n\tpublic SkinConfig(String path) {\n\t\tthis.path = path;\n\t}\n\n\tpublic String getPath() {\n\t\treturn path;\n\t}\n\n\tpublic void setPath(String path) {\n\t\tthis.path = path;\n\t}\n\n\tpublic Property getProperties() {\n\t\treturn properties;\n\t}\n\n\tpublic void setProperties(Property property) {\n\t\tthis.properties = property;\n\t}\n\t\n\tpublic boolean validate() {\n\t\tif(path == null || path.length() == 0) {\n\t\t\treturn false;\n\t\t}\n\t\tif(properties == null) {\n\t\t\tproperties = new Property();\n\t\t}\n\t\tproperties.validate();\n\t\treturn true;\n\t}\n\t\n\tpublic static SkinConfig getDefault(int id) {\n\t\tSkinConfig skin = new SkinConfig();\n\t\tDefault dskin = Default.get(SkinType.getSkinTypeById(id));\n\t\tif(dskin != null) {\n\t\t\tskin.setPath(dskin.path);\n\t\t\tskin.validate();\n\t\t}\n\t\treturn skin;\n\t}\n\n\t/**\n\t * スキンの各種設定項目\n\t * \n\t * @author exch\n\t */\n\tpublic static class Property implements Validatable {\n\t\t/**\n\t\t * 設定項目名-数値のセット\n\t\t */\n\t\tprivate Option[] option = new Option[0];\n\t\t/**\n\t\t * 設定項目名-ファイルパスのセット\n\t\t */\n\t\tprivate FilePath[] file = new FilePath[0];\n\t\t/**\n\t\t * 設定項目名-オフセットのセット\n\t\t */\n\t\tprivate Offset[] offset = new Offset[0];\n\n\t\tpublic Option[] getOption() {\n\t\t\treturn option;\n\t\t}\n\n\t\tpublic void setOption(Option[] option) {\n\t\t\tthis.option = option;\n\t\t}\n\n\t\tpublic FilePath[] getFile() {\n\t\t\treturn file;\n\t\t}\n\n\t\tpublic void setFile(FilePath[] file) {\n\t\t\tthis.file = file;\n\t\t}\n\n\t\tpublic Offset[] getOffset() {\n\t\t\treturn offset;\n\t\t}\n\n\t\tpublic void setOffset(Offset[] offset) {\n\t\t\tthis.offset = offset;\n\t\t}\n\t\t\n\t\tpublic boolean validate() {\n\t\t\tif(option == null) {\n\t\t\t\toption = new Option[0];\n\t\t\t}\n\t\t\toption = Validatable.removeInvalidElements(option);\n\t\t\t\n\t\t\tif(file == null) {\n\t\t\t\tfile = new FilePath[0];\n\t\t\t}\n\t\t\tfile = Validatable.removeInvalidElements(file);\n\t\t\t\n\t\t\tif(offset == null) {\n\t\t\t\toffset = new Offset[0];\n\t\t\t}\n\t\t\toffset = Validatable.removeInvalidElements(offset);\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic static class Option implements Validatable {\n\t\tpublic String name;\n\t\tpublic int value;\n\n\t\t@Override\n\t\tpublic boolean validate() {\n\t\t\treturn name != null && name.length() > 0;\n\t\t}\n\t}\n\n\tpublic static class FilePath implements Validatable {\n\t\tpublic String name;\n\t\tpublic String path;\n\t\t\n\t\t@Override\n\t\tpublic boolean validate() {\n\t\t\treturn name != null && name.length() > 0 && path != null && path.length() > 0;\n\t\t}\n\t}\n\n\tpublic static class Offset implements Validatable {\n\t\tpublic String name;\n\t\tpublic int x;\n\t\tpublic int y;\n\t\tpublic int w;\n\t\tpublic int h;\n\t\tpublic int r;\n\t\tpublic int a;\n\t\t\n\t\t@Override\n\t\tpublic boolean validate() {\n\t\t\treturn name != null && name.length() > 0;\n\t\t}\n\t}\n\n\t/**\n\t * デフォルトスキンのパス\n\t * \n\t * @author exch\n\t */\n\tpublic enum Default {\n\t\tPLAY7(SkinType.PLAY_7KEYS, \"skin/default/play/play7.luaskin\"),\n\t\tPLAY5(SkinType.PLAY_5KEYS, \"skin/default/play5.json\"),\n\t\tPLAY14(SkinType.PLAY_14KEYS, \"skin/default/play14.json\"),\n\t\tPLAY10(SkinType.PLAY_10KEYS, \"skin/default/play10.json\"),\n\t\tPLAY9(SkinType.PLAY_9KEYS, \"skin/default/play9.json\"),\n\t\tSELECT(SkinType.MUSIC_SELECT, \"skin/default/select.json\"),\n\t\tDECIDE(SkinType.DECIDE, \"skin/default/decide/decide.luaskin\"),\n\t\tRESULT(SkinType.RESULT, \"skin/default/result/result.luaskin\"),\n\t\tCOURSERESULT(SkinType.COURSE_RESULT, \"skin/default/graderesult.json\"),\n\t\tPLAY24(SkinType.PLAY_24KEYS, \"skin/default/play24.json\"),\n\t\tPLAY24DOUBLE(SkinType.PLAY_24KEYS_DOUBLE, \"skin/default/play24double.json\"),\n\t\tKEYCONFIG(SkinType.KEY_CONFIG, \"skin/default/keyconfig/keyconfig.luaskin\"),\n\t\tSKINSELECT(SkinType.SKIN_SELECT, \"skin/default/skinselect/skinselect.luaskin\"),\n\t\t;\n\n\t\tpublic final SkinType type;\n\t\tpublic final String path;\n\n\t\tprivate Default(SkinType type, String path) {\n\t\t\tthis.type = type;\n\t\t\tthis.path = path;\n\t\t}\n\n\t\tpublic static Default get(SkinType type) {\n\t\t\tfor(Default skin : values()) {\n\t\t\t\tif(skin.type == type) {\n\t\t\t\t\treturn skin;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n}" }, { "identifier": "OPTION_RANDOM_VALUE", "path": "core/src/bms/player/beatoraja/skin/SkinProperty.java", "snippet": "public static final int OPTION_RANDOM_VALUE = -1;" } ]
import bms.player.beatoraja.Resolution; import bms.player.beatoraja.SkinConfig; import static bms.player.beatoraja.skin.SkinProperty.OPTION_RANDOM_VALUE; import java.io.File; import java.nio.file.Path; import java.util.*;
2,498
package bms.player.beatoraja.skin; /** * スキンのヘッダ情報 * * @author exch */ public class SkinHeader { /** * スキンの種類 */ private int type; /** * スキン:LR2 */ public static final int TYPE_LR2SKIN = 0; /** * スキン:beatoraja */ public static final int TYPE_BEATORJASKIN = 1; /** * スキンファイルのパス */ private Path path; /** * スキンタイプ */ private SkinType mode; /** * スキン名 */ private String name; /** * スキン製作者名 */ private String author; /** * カスタムオプション */ private CustomOption[] options = CustomOption.EMPTY_ARRAY; /** * カスタムファイル */ private CustomFile[] files = CustomFile.EMPTY_ARRAY; /** * カスタムオフセット */ private CustomOffset[] offsets = CustomOffset.EMPTY_ARRAY; /** * カスタムカテゴリー */ private CustomCategory[] categories = CustomCategory.EMPTY_ARRAY; /** * スキン解像度 */ private Resolution resolution = Resolution.SD; private Resolution sourceResolution; private Resolution destinationResolution; public SkinType getSkinType() { return mode; } public void setSkinType(SkinType mode) { this.mode = mode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public CustomOption[] getCustomOptions() { return options; } public void setCustomOptions(CustomOption[] options) { this.options = options; } public CustomFile[] getCustomFiles() { return files; } public void setCustomFiles(CustomFile[] files) { this.files = files; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Resolution getResolution() { return resolution; } public void setResolution(Resolution resolution) { this.resolution = resolution; } public int getType() { return type; } public void setType(int type) { this.type = type; } public CustomOffset[] getCustomOffsets() { return offsets; } public void setCustomOffsets(CustomOffset[] offsets) { this.offsets = offsets; } public CustomCategory[] getCustomCategories() { return categories; } public void setCustomCategories(CustomCategory[] categories) { this.categories = categories; }
package bms.player.beatoraja.skin; /** * スキンのヘッダ情報 * * @author exch */ public class SkinHeader { /** * スキンの種類 */ private int type; /** * スキン:LR2 */ public static final int TYPE_LR2SKIN = 0; /** * スキン:beatoraja */ public static final int TYPE_BEATORJASKIN = 1; /** * スキンファイルのパス */ private Path path; /** * スキンタイプ */ private SkinType mode; /** * スキン名 */ private String name; /** * スキン製作者名 */ private String author; /** * カスタムオプション */ private CustomOption[] options = CustomOption.EMPTY_ARRAY; /** * カスタムファイル */ private CustomFile[] files = CustomFile.EMPTY_ARRAY; /** * カスタムオフセット */ private CustomOffset[] offsets = CustomOffset.EMPTY_ARRAY; /** * カスタムカテゴリー */ private CustomCategory[] categories = CustomCategory.EMPTY_ARRAY; /** * スキン解像度 */ private Resolution resolution = Resolution.SD; private Resolution sourceResolution; private Resolution destinationResolution; public SkinType getSkinType() { return mode; } public void setSkinType(SkinType mode) { this.mode = mode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public CustomOption[] getCustomOptions() { return options; } public void setCustomOptions(CustomOption[] options) { this.options = options; } public CustomFile[] getCustomFiles() { return files; } public void setCustomFiles(CustomFile[] files) { this.files = files; } public Path getPath() { return path; } public void setPath(Path path) { this.path = path; } public Resolution getResolution() { return resolution; } public void setResolution(Resolution resolution) { this.resolution = resolution; } public int getType() { return type; } public void setType(int type) { this.type = type; } public CustomOffset[] getCustomOffsets() { return offsets; } public void setCustomOffsets(CustomOffset[] offsets) { this.offsets = offsets; } public CustomCategory[] getCustomCategories() { return categories; } public void setCustomCategories(CustomCategory[] categories) { this.categories = categories; }
public void setSkinConfigProperty(SkinConfig.Property property) {
1
2023-12-02 23:41:17+00:00
4k