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 |
---|---|---|---|---|---|---|---|---|---|---|
Walter-Stroebel/Jllama | src/main/java/nl/infcomtec/jllama/Vagrant.java | [
{
"identifier": "ARROWS",
"path": "src/main/java/nl/infcomtec/tools/ARROWS.java",
"snippet": "public class ARROWS {\n\n public static final String RIGHT = \"\\u27A1\";\n public static final String LEFT = \"\\u2190\";\n public static final String UP = \"\\u2191\";\n public static final String DOWN = \"\\u2193\";\n}"
},
{
"identifier": "ToolManager",
"path": "src/main/java/nl/infcomtec/tools/ToolManager.java",
"snippet": "public abstract class ToolManager implements Runnable {\n\n private static final String NO_COMMAND_SPECIFIED = \"No command specified\";\n\n protected static void deleteAll(File fileOrDir) {\n if (fileOrDir.isDirectory()) {\n File[] files = fileOrDir.listFiles();\n if (files != null) {\n for (File file : files) {\n deleteAll(file);\n }\n }\n } else {\n fileOrDir.delete();\n }\n }\n\n private byte[] inBytes;\n private ProcessBuilder pb;\n protected File workingDir;\n protected OutputStream stdoutStream;\n protected StringBuilder stderrBuilder = new StringBuilder();\n public int exitCode;\n\n protected void setWorkingDir(File dir) {\n if (!dir.exists()) {\n if (!dir.mkdirs()) {\n throw new RuntimeException(\"Failed to create the directory\");\n }\n }\n if (dir.exists() && dir.isDirectory()) {\n this.workingDir = dir;\n } else {\n throw new RuntimeException(\"Invalid directory\");\n }\n }\n\n public void setInput(Object in) {\n if (null != in) {\n if (in instanceof byte[]) {\n this.inBytes = (byte[]) in;\n } else {\n inBytes = in.toString().getBytes(StandardCharsets.UTF_8);\n }\n }\n }\n\n public void setOutput(OutputStream out) {\n stdoutStream = out;\n }\n\n protected void setCommand(List<String> cmd) {\n this.pb = new ProcessBuilder(cmd);\n }\n\n public void setCommand(String... cmd) {\n this.pb = new ProcessBuilder(cmd);\n }\n\n public String getCommand() {\n if (null == pb) {\n return NO_COMMAND_SPECIFIED;\n }\n return pb.command().toString();\n }\n\n protected void internalRun() {\n if (null == pb) {\n throw new RuntimeException(NO_COMMAND_SPECIFIED);\n }\n if (null == workingDir) {\n try {\n Path tempDir = Files.createTempDirectory(\"ToolManagerTempDir\");\n workingDir = tempDir.toFile();\n Runtime.getRuntime().addShutdownHook(new Thread() {\n @Override\n public void run() {\n deleteAll(workingDir);\n }\n });\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n pb.directory(workingDir);\n if (null == stdoutStream) {\n stdoutStream = new ByteArrayOutputStream();\n }\n try {\n final Process p = pb.start();\n\n // Thread to handle stdout\n Thread stdoutThread = new Thread() {\n @Override\n public void run() {\n try (InputStream is = p.getInputStream()) {\n byte[] buffer = new byte[1024];\n int read;\n while ((read = is.read(buffer)) != -1) {\n stdoutStream.write(buffer, 0, read);\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n };\n\n // Thread to handle stderr\n Thread stderrThread = new Thread() {\n @Override\n public void run() {\n try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {\n String line;\n while ((line = br.readLine()) != null) {\n System.err.println(line);\n stderrBuilder.append(line).append(System.lineSeparator());\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n };\n\n stdoutThread.start();\n stderrThread.start();\n\n // Thread to handle input, if any\n if (inBytes != null) {\n // Spawn a thread to manage input\n new Thread() {\n @Override\n public void run() {\n try (OutputStream os = p.getOutputStream()) {\n os.write(inBytes);\n p.getOutputStream().close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n }.start();\n } else {\n p.getOutputStream().close();\n }\n\n // Wait for the process to complete\n exitCode = p.waitFor();\n\n // Wait for stdout and stderr threads to complete\n stdoutThread.join();\n stderrThread.join();\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n}"
}
] | import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.infcomtec.tools.ARROWS;
import nl.infcomtec.tools.ToolManager; | 3,049 | /**
* Parse and execute.
*
* @param text with markers.
* @return
*/
public String execMarked(String text) {
StringBuilder sb = new StringBuilder(text);
StringBuilder output = new StringBuilder();
int cmdStart = sb.indexOf(MARK_START);
while (cmdStart >= 0) {
int cmdEnd = sb.indexOf(MARK_END, cmdStart);
if (cmdEnd > 2) {
String cmd = sb.substring(cmdStart + 2, cmdEnd).trim(); // in case the LLM got fancy with whitespace
execOnBox(cmd, output);
sb.delete(cmdStart, cmdEnd + 2);
cmdStart = sb.indexOf(MARK_START);
}
}
// any non-whitespace left plus any output
String disp = sb.toString().trim() + System.lineSeparator() + output.toString();
return disp;
}
/**
* Execute.
*
* @param cmd command.
* @param input Optional input for the command.
* @return
*/
public String exec(String cmd, String input) {
StringBuilder output = new StringBuilder();
this.input.set(input);
execOnBox(cmd, output);
return output.toString();
}
private void execOnBox(final String cmd, final StringBuilder output) {
while (Step.running != state.get()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
log("Vagrant execute:", cmd);
final Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
((ChannelExec) channel).setErrStream(errStream);
channel.connect();
final String inp = input.getAndSet(null);
if (null != inp) {
final OutputStream outStream = channel.getOutputStream();
new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] inputBytes = inp.getBytes();
int offset = 0;
int chunkSize = 1024;
while (offset < inputBytes.length) {
int length = Math.min(chunkSize, inputBytes.length - offset);
outStream.write(inputBytes, offset, length);
doCallBack(onInputPassed, inputBytes, offset, length);
outStream.flush();
offset += length;
}
} catch (IOException e) {
log("Error writing input to channel:", e.getMessage());
} finally {
try {
outStream.close();
} catch (IOException e) {
log("Error closing output stream:", e.getMessage());
}
}
}
}).start();
}
final BufferedReader bfr;
try {
bfr = new BufferedReader(new InputStreamReader(channel.getInputStream()));
for (String line = bfr.readLine(); null != line; line = bfr.readLine()) {
doCallBack(onOutputReceived, line);
doCallBack(onOutputReceived, System.lineSeparator());
output.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, e);
}
// Append stderr to output
output.append(errStream.toString());
channel.disconnect();
log("Output:", output.toString());
} catch (Exception e) {
log("Failed to execute on Vagrant:", e.getMessage());
Step old = state.get();
state.set(Step.stopped);
doCallBack(onStateChange, old.name(), state.get().name());
}
}
private void doCallBack(AtomicReference<CallBack> cb, String s) {
CallBack get = cb.get();
if (null != get) {
get.cb(s);
}
}
private void doCallBack(AtomicReference<CallBack> cb, String f, String t) {
CallBack get = cb.get();
if (null != get) { | package nl.infcomtec.jllama;
/**
* Wrapper around Vagrant.
*
* @author walter
*/
public class Vagrant extends ToolManager {
public static final File VAGRANT_DIR = new File(System.getProperty("user.home"), "vagrant/Worker");
public static final File VAGRANT_KEY = new File(VAGRANT_DIR, ".vagrant/machines/default/virtualbox/private_key");
public static final String MARK_START = "$#";
public static final String MARK_END = "#$";
private final AtomicReference<String> input = new AtomicReference<>(null);
private com.jcraft.jsch.Session session;
public final AtomicReference<Step> state = new AtomicReference<>(Step.stopped);
public final StringBuilder log = new StringBuilder();
private final String EOLN = System.lineSeparator();
public AtomicReference<CallBack> onStateChange = new AtomicReference<>(null);
public AtomicReference<CallBack> onInputPassed = new AtomicReference<>(null);
public AtomicReference<CallBack> onOutputReceived = new AtomicReference<>(null);
public Vagrant() {
}
public void stop() {
Step old = state.get();
state.set(Step.stop);
doCallBack(onStateChange, old.name(), state.get().name());
new Thread(this).start();
}
public void start() {
Step old = state.get();
state.set(Step.start);
doCallBack(onStateChange, old.name(), state.get().name());
new Thread(this).start();
}
/**
* Internal use only, must be called within synchronized(log).
*/
private void logTimeStamp() {
log.append(String.format("%1$tF %1$tT:", System.currentTimeMillis()));
}
public void log(String... msg) {
synchronized (log) {
logTimeStamp();
if (null == msg) {
log.append(" Log called without any message.");
} else {
for (String s : msg) {
if (!Character.isWhitespace(log.charAt(log.length() - 1))) {
log.append(' ');
}
log.append(s);
}
}
log.append(EOLN);
}
}
@Override
public void run() {
switch (state.get()) {
case stopped:
log("Run was called in the ", state.get().name(), " state. That should not happen.");
break;
case start:
log("Starting Vagrant.");
setWorkingDir(VAGRANT_DIR);
setCommand("vagrant", "up");
internalRun();
if (exitCode != 0) {
log("Running vagrant failed, rc=", Integer.toString(exitCode));
}
if (stdoutStream instanceof ByteArrayOutputStream) {
log("Vagrant start up:", EOLN,
new String(((ByteArrayOutputStream) stdoutStream).toByteArray(), StandardCharsets.UTF_8));
stdoutStream = null;
} else {
log("Vagrant start up:", Objects.toString(stdoutStream));
}
if (stderrBuilder.length() > 0) {
log("Vagrant error output:" + stderrBuilder.toString());
}
stderrBuilder.setLength(0);
try {
JSch jsch = new JSch();
jsch.addIdentity(VAGRANT_KEY.getAbsolutePath());
session = jsch.getSession("vagrant", "localhost", 2222);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Step old = state.get();
state.set(Step.running);
doCallBack(onStateChange, old.name(), state.get().name());
} catch (Exception e) {
log("Failed to connect to Vagrant:", e.getMessage());
Step old = state.get();
state.set(Step.stopped);
doCallBack(onStateChange, old.name(), state.get().name());
}
break;
case stop:
log("Stopping Vagrant.");
if (null != session) {
try {
session.disconnect();
} catch (Exception any) {
// we don't care, we tried.
}
session = null;
}
setWorkingDir(VAGRANT_DIR);
setCommand("vagrant", "halt");
internalRun();
log("Vagrant should be stopped.");
break;
default:
log("Run was called in the ", state.get().name(), " state. That REALLY should not happen.");
break;
}
}
/**
* Parse and execute.
*
* @param text with markers.
* @return
*/
public String execMarked(String text) {
StringBuilder sb = new StringBuilder(text);
StringBuilder output = new StringBuilder();
int cmdStart = sb.indexOf(MARK_START);
while (cmdStart >= 0) {
int cmdEnd = sb.indexOf(MARK_END, cmdStart);
if (cmdEnd > 2) {
String cmd = sb.substring(cmdStart + 2, cmdEnd).trim(); // in case the LLM got fancy with whitespace
execOnBox(cmd, output);
sb.delete(cmdStart, cmdEnd + 2);
cmdStart = sb.indexOf(MARK_START);
}
}
// any non-whitespace left plus any output
String disp = sb.toString().trim() + System.lineSeparator() + output.toString();
return disp;
}
/**
* Execute.
*
* @param cmd command.
* @param input Optional input for the command.
* @return
*/
public String exec(String cmd, String input) {
StringBuilder output = new StringBuilder();
this.input.set(input);
execOnBox(cmd, output);
return output.toString();
}
private void execOnBox(final String cmd, final StringBuilder output) {
while (Step.running != state.get()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
log("Vagrant execute:", cmd);
final Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
final ByteArrayOutputStream errStream = new ByteArrayOutputStream();
((ChannelExec) channel).setErrStream(errStream);
channel.connect();
final String inp = input.getAndSet(null);
if (null != inp) {
final OutputStream outStream = channel.getOutputStream();
new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] inputBytes = inp.getBytes();
int offset = 0;
int chunkSize = 1024;
while (offset < inputBytes.length) {
int length = Math.min(chunkSize, inputBytes.length - offset);
outStream.write(inputBytes, offset, length);
doCallBack(onInputPassed, inputBytes, offset, length);
outStream.flush();
offset += length;
}
} catch (IOException e) {
log("Error writing input to channel:", e.getMessage());
} finally {
try {
outStream.close();
} catch (IOException e) {
log("Error closing output stream:", e.getMessage());
}
}
}
}).start();
}
final BufferedReader bfr;
try {
bfr = new BufferedReader(new InputStreamReader(channel.getInputStream()));
for (String line = bfr.readLine(); null != line; line = bfr.readLine()) {
doCallBack(onOutputReceived, line);
doCallBack(onOutputReceived, System.lineSeparator());
output.append(line).append(System.lineSeparator());
}
} catch (IOException e) {
Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, e);
}
// Append stderr to output
output.append(errStream.toString());
channel.disconnect();
log("Output:", output.toString());
} catch (Exception e) {
log("Failed to execute on Vagrant:", e.getMessage());
Step old = state.get();
state.set(Step.stopped);
doCallBack(onStateChange, old.name(), state.get().name());
}
}
private void doCallBack(AtomicReference<CallBack> cb, String s) {
CallBack get = cb.get();
if (null != get) {
get.cb(s);
}
}
private void doCallBack(AtomicReference<CallBack> cb, String f, String t) {
CallBack get = cb.get();
if (null != get) { | get.cb(f + ARROWS.RIGHT + t); | 0 | 2023-11-16 00:37:47+00:00 | 4k |
jimbro1000/DriveWire4Rebuild | src/main/java/org/thelair/dw4/drivewire/ports/serial/DWSerialPort.java | [
{
"identifier": "BasePortDef",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/BasePortDef.java",
"snippet": "public abstract class BasePortDef implements DWIPortType {\n}"
},
{
"identifier": "DWIPort",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPort.java",
"snippet": "public interface DWIPort {\n /**\n * Open target port with given definition and register with port handler.\n * @param port definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void openWith(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Modify port from definition.\n * @param port revised definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void setPortDef(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Identify port type.\n * @return port type id.\n */\n int identifyPort();\n\n /**\n * Close port and deregister with port handler.\n */\n void closePort();\n\n /**\n * Serialise port definition as String.\n *\n * @return port definition values\n */\n String getPortDefinition();\n}"
},
{
"identifier": "DWIPortManager",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortManager.java",
"snippet": "public interface DWIPortManager {\n /**\n * Provide a count of all ports recorded.\n * @return total number of ports\n */\n int getPortCount();\n\n /**\n * Provide a count of open ports.\n * @return total number of open ports\n */\n int getOpenPortCount();\n\n /**\n * Provide a count of closed ports.\n * @return total number of closed ports\n */\n int getClosedPortCount();\n /**\n * Register an unused port as open.\n * @param port generic closed port\n */\n void registerOpenPort(DWIPort port);\n\n /**\n * Register a used port as closed.\n * @param port generic open port\n */\n void registerClosedPort(DWIPort port);\n\n /**\n * Create a new port instance.\n * @param portType type of port to create\n * @return unused port\n */\n DWIPort createPortInstance(DWIPortType.DWPortTypeIdentity portType);\n\n /**\n * Dispose of unused port.\n * @param port generic closed port\n */\n void disposePort(DWIPort port);\n\n\n /**\n * Handles context shutdown event.\n * Close all open ports. Dispose of all ports\n *\n * @param event context event\n */\n void contextDestroyed(ServletContextEvent event);\n}"
},
{
"identifier": "InvalidPortTypeDefinition",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/InvalidPortTypeDefinition.java",
"snippet": "@Getter\npublic class InvalidPortTypeDefinition extends InvalidObjectException {\n /**\n * Port definition causing the exception.\n */\n private final BasePortDef sourcePortDef;\n /**\n * Constructs an {@code InvalidObjectException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n * @param portDef Causing port definition object\n * @see ObjectInputValidation\n */\n public InvalidPortTypeDefinition(final String reason,\n final BasePortDef portDef) {\n super(reason);\n sourcePortDef = portDef;\n }\n}"
},
{
"identifier": "DWISerial",
"path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/hardware/DWISerial.java",
"snippet": "public interface DWISerial {\n /**\n * Adds a SerialPortDataListener to the serial port interface.\n *\n * @param dataListener A SerialPortDataListener,\n * SerialPortDataListenerWithExceptions,\n * SerialPortPacketListener,\n * SerialPortMessageListener, or\n * SerialPortMessageListenerWithExceptions implementation\n * to be used for event-based serial port communications.\n *\n * @return Whether the listener was successfully registered with the serial\n * port\n */\n boolean addDataListener(SerialPortDataListener dataListener);\n\n /**\n * Returns the number of bytes available without blocking if\n * readBytes(byte[], int) were to be called immediately after this method\n * returns.\n *\n * @return The number of bytes currently available to be read, or -1 if the\n * port is not open\n */\n int bytesAvailable();\n\n /**\n * Returns the number of bytes still waiting to be written in the device's\n * output queue.\n *\n * @return The number of bytes currently waiting to be written, or -1 if the\n * port is not open\n */\n int bytesAwaitingWrite();\n\n /**\n * Closes this serial port.\n *\n * @return Whether the port was successfully closed\n */\n boolean closePort();\n\n /**\n * Flushes any already-received data from the registered\n * SerialPortDataListener that has not yet triggered an event.\n */\n void flushDataListener();\n\n /**\n * Flushes the serial port's Rx/Tx device buffers.\n *\n * @return Whether the IO buffers were (or will be) successfully flushed\n */\n boolean flushIOBuffers();\n\n /**\n * Gets the current baud rate of the serial port.\n *\n * @return The current baud rate of the serial port\n */\n int getBaudRate();\n\n /**\n * Gets the current number of data bits per word.\n *\n * @return The current number of data bits per word\n */\n int getDataBits();\n\n /**\n * Returns the flow control settings enabled on this serial port.\n *\n * @return The flow control settings enabled on this serial port\n */\n int getFlowControl();\n\n /**\n * Returns an InputStream object associated with this serial port.\n *\n * @return An InputStream object associated with this serial port\n */\n InputStream getInputStream();\n\n /**\n * Returns an OutputStream object associated with this serial port.\n *\n * @return An OutputStream object associated with this serial port\n */\n OutputStream getOutputStream();\n\n /**\n * Gets the current number of stop bits per word.\n *\n * @return The current number of stop bits per word.\n */\n int getStopBits();\n\n /**\n * Returns whether the port is currently open and available for communication.\n *\n * @return Whether the port is opened\n */\n boolean isOpen();\n\n /**\n * Opens this serial port for reading and writing.\n *\n * @return Whether the port was successfully opened with a valid configuration\n */\n boolean openPort();\n\n /**\n * Reads up to bytesToRead raw data bytes from the serial port and stores\n * them in the buffer.\n *\n * @param buffer The buffer into which the raw data is read\n * @param bytesToRead The number of bytes to read from the serial port\n * @return The number of bytes successfully read, or -1 if there was an error\n * reading from the port\n */\n int readBytes(byte[] buffer, int bytesToRead);\n\n /**\n * Reads up to bytesToRead raw data bytes from the serial port and stores\n * them in the buffer starting at the indicated offset.\n *\n * @param buffer The buffer into which the raw data is read\n * @param bytesToRead The number of bytes to read from the serial port\n * @param offset The read buffer index into which to begin storing data\n * @return The number of bytes successfully read, or -1 if there was an error\n * reading from the port\n */\n int readBytes(byte[] buffer, int bytesToRead, int offset);\n\n /**\n * Removes the associated SerialPortDataListener from the serial port\n * interface.\n */\n void removeDataListener();\n\n /**\n * Sets all serial port parameters at one time.\n *\n * @param newBaudRate The desired baud rate for this serial port\n * @param newDataBits The number of data bits to use per word\n * @param newStopBits The number of stop bits to use\n * @param newParity The type of parity error-checking desired\n * @return Whether the port configuration is valid or disallowed on this\n * system (only meaningful after the port is already opened)\n */\n boolean trySetCommPortParameters(\n int newBaudRate, int newDataBits, int newStopBits, int newParity\n );\n\n /**\n * Writes up to bytesToWrite raw data bytes from the buffer parameter to the\n * serial port.\n *\n * @param buffer The buffer containing the raw data to write to the\n * serial port\n * @param bytesToWrite The number of bytes to write to the serial port\n * @return The number of bytes successfully written, or -1 if there was an\n * error writing to the port\n */\n int writeBytes(byte[] buffer, int bytesToWrite);\n\n /**\n * Writes up to bytesToWrite raw data bytes from the buffer parameter to the\n * serial port starting at the indicated offset.\n *\n * @param buffer The buffer containing the raw data to write to the\n * serial port\n * @param bytesToWrite The number of bytes to write to the serial port\n * @param offset The buffer index from which to begin writing to the\n * serial port\n * @return The number of bytes successfully written, or -1 if there was an\n * error writing to the port\n */\n int writeBytes(byte[] buffer, int bytesToWrite, int offset);\n}"
}
] | import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.thelair.dw4.drivewire.ports.BasePortDef;
import org.thelair.dw4.drivewire.ports.DWIPort;
import org.thelair.dw4.drivewire.ports.DWIPortManager;
import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition;
import org.thelair.dw4.drivewire.ports.serial.hardware.DWISerial;
import java.util.Map; | 2,769 | package org.thelair.dw4.drivewire.ports.serial;
/**
* RS232 Serial port definition.
*/
public final class DWSerialPort implements DWIPort {
/**
* Log appender.
*/
private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class);
/**
* Serial port definition.
*/
private SerialPortDef portDef;
/**
* Port manager.
*/
private final DWIPortManager portManager;
/**
* concrete com port object.
*/
private DWISerial comPort;
/**
* Serial port handler.
*/
private final SerialPortHardware portHandler;
/**
* Unique port identifier.
*/
private final int portId;
/**
* Create serial port with reference to manager.
* @param manager port manager handling this port
* @param port identifier
* @param hardPorts host serial hardware
*/
public DWSerialPort(
final DWIPortManager manager,
final int port,
final SerialPortHardware hardPorts
) {
this.portManager = manager;
this.portId = port;
this.portHandler = hardPorts;
LOGGER.info("Serial port created " + port);
}
@Override
public void openWith(final BasePortDef port) | package org.thelair.dw4.drivewire.ports.serial;
/**
* RS232 Serial port definition.
*/
public final class DWSerialPort implements DWIPort {
/**
* Log appender.
*/
private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class);
/**
* Serial port definition.
*/
private SerialPortDef portDef;
/**
* Port manager.
*/
private final DWIPortManager portManager;
/**
* concrete com port object.
*/
private DWISerial comPort;
/**
* Serial port handler.
*/
private final SerialPortHardware portHandler;
/**
* Unique port identifier.
*/
private final int portId;
/**
* Create serial port with reference to manager.
* @param manager port manager handling this port
* @param port identifier
* @param hardPorts host serial hardware
*/
public DWSerialPort(
final DWIPortManager manager,
final int port,
final SerialPortHardware hardPorts
) {
this.portManager = manager;
this.portId = port;
this.portHandler = hardPorts;
LOGGER.info("Serial port created " + port);
}
@Override
public void openWith(final BasePortDef port) | throws InvalidPortTypeDefinition { | 3 | 2023-11-18 11:35:16+00:00 | 4k |
JustARandomGuyNo512/Gunscraft | src/main/java/sheridan/gunscraft/entities/EntityRegister.java | [
{
"identifier": "Gunscraft",
"path": "src/main/java/sheridan/gunscraft/Gunscraft.java",
"snippet": "@Mod(\"gunscraft\")\npublic class Gunscraft {\n\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n\n public static IProxy proxy = DistExecutor.safeRunForDist(()->ClientProxy::new, ()->CommonProxy::new);\n\n public static final String MOD_ID = \"gunscraft\";\n\n public Gunscraft() {\n // Register the setup method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);\n // Register the enqueueIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);\n // Register the processIMC method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);\n // Register the doClientStuff method for modloading\n FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(RenderEvents.class);\n MinecraftForge.EVENT_BUS.register(DebugEvents.class);\n MinecraftForge.EVENT_BUS.register(ControllerEvents.class);\n MinecraftForge.EVENT_BUS.register(ClientTickEvents.class);\n ModItems.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ModContainers.CONTAINERS.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n SoundEvents.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n private void setup(final FMLCommonSetupEvent event) {\n // some preinit code\n LOGGER.info(\"HELLO FROM PREINIT\");\n LOGGER.info(\"DIRT BLOCK >> {}\", Blocks.DIRT.getRegistryName());\n CapabilityHandler.init();\n PacketHandler.register();\n //EntityRegister.ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n EntityRegister.registerRenderer();\n proxy.commonSetUp(event);\n }\n\n private void doClientStuff(final FMLClientSetupEvent event) {\n // do something that can only be done on the client\n proxy.setUpClient(event);\n }\n\n private void enqueueIMC(final InterModEnqueueEvent event) {\n // some example code to dispatch IMC to another mod\n InterModComms.sendTo(\"gunscraft\", \"helloworld\", () -> {\n LOGGER.info(\"Hello world from the MDK\");\n return \"Hello world\";\n });\n }\n\n private void processIMC(final InterModProcessEvent event) {\n // some example code to receive and process InterModComms from other mods\n LOGGER.info(\"Got IMC {}\", event.getIMCStream().\n map(m -> m.getMessageSupplier().get()).\n collect(Collectors.toList()));\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(FMLServerStartingEvent event) {\n // do something when the server starts\n LOGGER.info(\"HELLO from server starting\");\n }\n\n // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD\n // Event bus for receiving Registry Events)\n @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)\n public static class RegistryEvents {\n @SubscribeEvent\n public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {\n // register a new block here\n LOGGER.info(\"HELLO from Register Block\");\n }\n }\n}"
},
{
"identifier": "GenericProjectile",
"path": "src/main/java/sheridan/gunscraft/entities/projectile/GenericProjectile.java",
"snippet": "public class GenericProjectile extends Entity implements IProjectile, IEntityAdditionalSpawnData {\n public static final float BASE_SPEED_INDEX = 1.4f;\n public static final float BASE_SPREAD_INDEX = 0.008f;\n public LivingEntity shooter;\n public float speed;\n public float spread;\n public float damage;\n public int lifeLength;\n\n private static final Predicate<Entity> PROJECTILE_TARGETS =\n (input) -> input != null && input.canBeCollidedWith() && !input.isSpectator();\n\n\n public GenericProjectile(EntityType<?> entityTypeIn, World worldIn) {\n super(entityTypeIn, worldIn);\n }\n\n @Override\n public void init(LivingEntity shooter, float speed, float spread, float damage, int lifeLength) {\n this.shooter = shooter;\n\n\n this.setPosition(shooter.getPosX(), shooter.getPosY() + shooter.getEyeHeight(shooter.getPose()), shooter.getPosZ());\n this.speed = speed * BASE_SPEED_INDEX;\n this.spread = spread * BASE_SPREAD_INDEX;\n\n this.setRotation(shooter.rotationYaw, shooter.rotationPitch);\n\n double sx = rand.nextGaussian() * this.spread;\n double sy = rand.nextGaussian() * this.spread;\n double sz = rand.nextGaussian() * this.spread;\n double vp = Math.cos(this.rotationPitch * 0.017453292519943295);\n Vector3d motionVec = new Vector3d(\n - Math.sin(this.rotationYaw * 0.017453292519943295) * vp + sx,\n Math.sin(-this.rotationPitch * 0.017453292519943295) + sy,\n Math.cos(this.rotationYaw * 0.017453292519943295) * vp + sz\n );\n motionVec.normalize();\n this.setMotion(motionVec.mul(this.speed, this.speed, this.speed));\n this.damage = damage;\n this.lifeLength = lifeLength;\n }\n\n\n @Override\n protected void registerData() {\n\n }\n\n @Override\n public void tick() {\n if (!this.world.isRemote) {\n if (this.ticksExisted >= lifeLength) {\n this.setDead();\n }\n Vector3d prevPos = this.getPositionVec();\n Vector3d nextPos = prevPos.add(this.getMotion());\n BlockRayTraceResult resultBlock = this.world.rayTraceBlocks(new RayTraceContext(prevPos, nextPos, RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, this));\n Vector3d tempEndPos = null;\n boolean mightHitBlock = false;\n if (resultBlock.getType() != RayTraceResult.Type.MISS) {\n tempEndPos = resultBlock.getHitVec();\n mightHitBlock = true;\n }\n EntityRayTraceResult entityResult = tempEndPos == null ? ProjectileHelper.rayTraceEntities(this.world, this, prevPos, nextPos, this.getBoundingBox().expand(this.getMotion()).grow(1.0D), PROJECTILE_TARGETS)\n : ProjectileHelper.rayTraceEntities(this.world, this, prevPos, tempEndPos, this.getBoundingBox().expand(this.getMotion()).grow(1.0D), PROJECTILE_TARGETS);\n if (entityResult != null) {\n if (onHitEntity(entityResult)) {\n this.setDead();\n }\n } else if (mightHitBlock) {\n if (onHitBlock(resultBlock)) {\n this.setDead();\n }\n }\n\n this.setPosition(nextPos.x, nextPos.y, nextPos.z);\n }\n }\n\n public boolean onHitBlock(BlockRayTraceResult result) {\n BlockState state = this.world.getBlockState(result.getPos());\n if (state.getBlock() == Blocks.BELL && this.shooter instanceof PlayerEntity) {\n BellBlock bell = (BellBlock) state.getBlock();\n bell.attemptRing(this.world, state, result, (PlayerEntity) this.shooter, true);\n }\n return !(state.getBlock() instanceof LeavesBlock);\n }\n\n public boolean onHitEntity(EntityRayTraceResult result) {\n if (result.getEntity() == this.shooter) {\n return false;\n }\n Entity entity = result.getEntity();\n entity.hurtResistantTime = 0;\n GenericProjectileDamage source = new GenericProjectileDamage(\"projectile\", this.shooter);\n source.setProjectile();\n return entity.attackEntityFrom(source,damage);\n }\n\n @Override\n public void readAdditional(CompoundNBT compound) {\n\n }\n\n @Override\n public void writeAdditional(CompoundNBT compound) {\n\n }\n\n @Override\n public IPacket<?> createSpawnPacket() {\n return NetworkHooks.getEntitySpawningPacket(this);\n }\n\n @Override\n public void writeSpawnData(PacketBuffer buffer) {\n buffer.writeInt(this.lifeLength);\n buffer.writeFloat(this.speed);\n }\n\n @Override\n public void readSpawnData(PacketBuffer additionalData) {\n this.lifeLength = additionalData.readInt();\n this.speed = additionalData.readFloat();\n }\n\n}"
},
{
"identifier": "GenericProjectileRenderer",
"path": "src/main/java/sheridan/gunscraft/render/entities/GenericProjectileRenderer.java",
"snippet": "public class GenericProjectileRenderer extends EntityRenderer<GenericProjectile> {\n public static ResourceLocation RIFLE = new ResourceLocation(\"gunscraft\",\"textures/projectile/generic_projectile.png\");\n public static final float BASE_SCALE = 0.2f;\n public static ModelRifleProjectile modelGenericProjectile = new ModelRifleProjectile();\n\n public GenericProjectileRenderer(EntityRendererManager renderManager) {\n super(renderManager);\n this.shadowSize = 0.0f;\n }\n\n @Override\n public ResourceLocation getEntityTexture(GenericProjectile entity) {\n return RIFLE;\n }\n\n\n @Override\n public void render(GenericProjectile entity, float entityYaw, float partialTicks, MatrixStack matrixStack, IRenderTypeBuffer renderTypeBuffer, int light) {\n float speed = entity.speed / BASE_SPEED_INDEX;\n if (speed > 4f) {\n if (entity.ticksExisted <= 1) {\n return;\n }\n } else {\n if (entity.ticksExisted <= 2) {\n return;\n }\n }\n matrixStack.push();\n matrixStack.scale(BASE_SCALE, BASE_SCALE, BASE_SCALE);\n matrixStack.rotate(new Quaternion(Vector3f.YP, -entityYaw, true));\n matrixStack.rotate(new Quaternion(Vector3f.XP, entity.rotationPitch, true));\n modelGenericProjectile.render(matrixStack, renderTypeBuffer.getBuffer(RenderType.getArmorCutoutNoCull(this.getEntityTexture(entity))),light,655360,1,1,1,1);\n matrixStack.pop();\n\n super.render(entity, entityYaw, partialTicks, matrixStack, renderTypeBuffer, light);\n }\n}"
}
] | import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import sheridan.gunscraft.Gunscraft;
import sheridan.gunscraft.entities.projectile.GenericProjectile;
import sheridan.gunscraft.render.entities.GenericProjectileRenderer; | 2,738 | package sheridan.gunscraft.entities;
public class EntityRegister {
public static final DeferredRegister<EntityType<?>> ENTITIES;
//public static final EntityType<GenericProjectile> GENERIC_PROJECTILE = EntityType.Builder.createGenericRecoil(GenericProjectile::new, EntityClassification.MISC).size(0.25f, 0.5f).updateInterval(1).build(new ResourceLocation(Gunscraft.MOD_ID ,"generic_projectile").toString());
public static final RegistryObject<EntityType<GenericProjectile>> GENERIC_PROJECTILE;
static { | package sheridan.gunscraft.entities;
public class EntityRegister {
public static final DeferredRegister<EntityType<?>> ENTITIES;
//public static final EntityType<GenericProjectile> GENERIC_PROJECTILE = EntityType.Builder.createGenericRecoil(GenericProjectile::new, EntityClassification.MISC).size(0.25f, 0.5f).updateInterval(1).build(new ResourceLocation(Gunscraft.MOD_ID ,"generic_projectile").toString());
public static final RegistryObject<EntityType<GenericProjectile>> GENERIC_PROJECTILE;
static { | ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Gunscraft.MOD_ID); | 0 | 2023-11-14 14:00:55+00:00 | 4k |
zpascual/5419-Arm-Example | src/main/java/com/team5419/frc2023/subsystems/Arm.java | [
{
"identifier": "Util",
"path": "src/main/java/com/team254/lib/util/Util.java",
"snippet": "public class Util {\n\n public static final double kEpsilon = 1e-12;\n\n /**\n * Prevent this class from being instantiated.\n */\n private Util() {\n }\n\n /**\n * Limits the given input to the given magnitude.\n */\n public static double limit(double v, double maxMagnitude) {\n return limit(v, -maxMagnitude, maxMagnitude);\n }\n\n public static double limit(double v, double min, double max) {\n return Math.min(max, Math.max(min, v));\n }\n \n public static boolean inRange(double v, double maxMagnitude) {\n return inRange(v, -maxMagnitude, maxMagnitude);\n }\n\n /**\n * Checks if the given input is within the range (min, max), both exclusive.\n */\n public static boolean inRange(double v, double min, double max) {\n return v > min && v < max;\n }\n\n public static double interpolate(double a, double b, double x) {\n x = limit(x, 0.0, 1.0);\n return a + (b - a) * x;\n }\n\n public static String joinStrings(final String delim, final List<?> strings) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < strings.size(); ++i) {\n sb.append(strings.get(i).toString());\n if (i < strings.size() - 1) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n public static boolean epsilonEquals(double a, double b, double epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean epsilonEquals(double a, double b) {\n return epsilonEquals(a, b, kEpsilon);\n }\n\n public static boolean epsilonEquals(int a, int b, int epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean allCloseTo(final List<Double> list, double value, double epsilon) {\n boolean result = true;\n for (Double value_in : list) {\n result &= epsilonEquals(value_in, value, epsilon);\n }\n return result;\n }\n}"
},
{
"identifier": "Constants",
"path": "src/main/java/com/team5419/frc2023/Constants.java",
"snippet": "public class Constants {\n\n // Time step for your system\n public static final double kLooperDt = 0.02;\n\n public static final class Arm {\n public static final ServoMotorSubsystemConstants kArmServoConstants = new ServoMotorSubsystemConstants();\n\n static {\n kArmServoConstants.kName = \"Arm\";\n\n kArmServoConstants.kMasterConstants.id = Ports.kArm;\n kArmServoConstants.kMasterConstants.invert_motor = false;\n kArmServoConstants.kMasterConstants.invert_sensor_phase = false;\n\n kArmServoConstants.kHomePosition = -9.598;\n kArmServoConstants.kMinUnitsLimit = -9.598;\n kArmServoConstants.kMaxUnitsLimit = 113.706;\n\n kArmServoConstants.kTicksPerUnitDistance = (2048.0 / 360.0) * 240.0; //encoder ticks per rev * gear ratio\n kArmServoConstants.kKp = 0.1; // Raw output / raw error\n kArmServoConstants.kKi = 0.0; // Raw output / sum of raw error\n kArmServoConstants.kKd = 0.0; // Raw output / (err - prevErr)\n kArmServoConstants.kKf = 0.0; // Raw output / velocity in ticks/100ms\n kArmServoConstants.kKa = 0.0; // Raw output / accel in (ticks/100ms) /\n kArmServoConstants.kMaxIntegralAccumulator = 0;\n kArmServoConstants.kIZone = 0; // Ticks\n kArmServoConstants.kDeadband = 0;\n\n kArmServoConstants.kPositionKp = 0.0;\n kArmServoConstants.kPositionKi = 0;\n kArmServoConstants.kPositionKd = 0.0;\n kArmServoConstants.kPositionKf = 0;\n kArmServoConstants.kPositionMaxIntegralAccumulator = 0;\n kArmServoConstants.kPositionIZone = 0; // Ticks\n kArmServoConstants.kPositionDeadband = 0; //\n\n kArmServoConstants.kCruiseVelocity = 25000; // Ticks / 100ms\n kArmServoConstants.kAcceleration = 250000; // Ticks / 100ms / s\n kArmServoConstants.kRampRate = 0.0; // s\n\n kArmServoConstants.kEnableSupplyCurrentLimit = true;\n kArmServoConstants.kSupplyContinuousCurrentLimit = 40; // amps\n kArmServoConstants.kSupplyPeakCurrentLimit = 40; // amps\n kArmServoConstants.kSupplyPeakCurrentDuration = 10; // milliseconds\n\n kArmServoConstants.kMaxVoltage = 12.0;\n\n kArmServoConstants.kRecoverPositionOnReset = false;\n }\n\n public static final double kAngleTolerance = 3.0;\n public static final double kWristSafeAngle = 10;\n\n }\n\n public static final class Wrist {\n public static final ServoMotorSubsystemConstants kWristServoConstants = new ServoMotorSubsystemConstants();\n\n static {\n kWristServoConstants.kName = \"Wrist\";\n\n kWristServoConstants.kMasterConstants.id = Ports.kWrist;\n kWristServoConstants.kMasterConstants.invert_motor = false;\n kWristServoConstants.kMasterConstants.invert_sensor_phase = false;\n\n kWristServoConstants.kHomePosition = -9.598;\n kWristServoConstants.kMinUnitsLimit = -9.598;\n kWristServoConstants.kMaxUnitsLimit = 113.706;\n\n kWristServoConstants.kTicksPerUnitDistance = (2048.0 / 360.0) * 40.0; //encoder ticks per rev * gear ratio\n kWristServoConstants.kKp = 0.1; // Raw output / raw error\n kWristServoConstants.kKi = 0.0; // Raw output / sum of raw error\n kWristServoConstants.kKd = 0.0; // Raw output / (err - prevErr)\n kWristServoConstants.kKf = 0.0; // Raw output / velocity in ticks/100ms\n kWristServoConstants.kKa = 0.0; // Raw output / accel in (ticks/100ms) /\n kWristServoConstants.kMaxIntegralAccumulator = 0;\n kWristServoConstants.kIZone = 0; // Ticks\n kWristServoConstants.kDeadband = 0;\n\n kWristServoConstants.kPositionKp = 0.0;\n kWristServoConstants.kPositionKi = 0;\n kWristServoConstants.kPositionKd = 0.0;\n kWristServoConstants.kPositionKf = 0;\n kWristServoConstants.kPositionMaxIntegralAccumulator = 0;\n kWristServoConstants.kPositionIZone = 0; // Ticks\n kWristServoConstants.kPositionDeadband = 0; //\n\n kWristServoConstants.kCruiseVelocity = 25000; // Ticks / 100ms\n kWristServoConstants.kAcceleration = 250000; // Ticks / 100ms / s\n kWristServoConstants.kRampRate = 0.0; // s\n\n kWristServoConstants.kEnableSupplyCurrentLimit = true;\n kWristServoConstants.kSupplyContinuousCurrentLimit = 40; // amps\n kWristServoConstants.kSupplyPeakCurrentLimit = 40; // amps\n kWristServoConstants.kSupplyPeakCurrentDuration = 10; // milliseconds\n\n kWristServoConstants.kMaxVoltage = 12.0;\n\n kWristServoConstants.kRecoverPositionOnReset = false;\n }\n\n public static final double kAngleTolerance = 3.0;\n\n }\n\n}"
},
{
"identifier": "ILooper",
"path": "src/main/java/com/team5419/frc2023/loops/ILooper.java",
"snippet": "public interface ILooper {\n void register(Loop loop);\n}"
},
{
"identifier": "Loop",
"path": "src/main/java/com/team5419/frc2023/loops/Loop.java",
"snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}"
},
{
"identifier": "Request",
"path": "src/main/java/com/team5419/lib/requests/Request.java",
"snippet": "public abstract class Request {\n\n\tpublic abstract void act();\n\t\n\tpublic boolean isFinished() {return true;}\n\n\tprivate final List<Prerequisite> prerequisites = new ArrayList<>();\n\n\tpublic Request withPrerequisites(Prerequisite... prereqs) {\n\t\tfor(Prerequisite prereq : prereqs){\n\t\t\tprerequisites.add(prereq);\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic Request withPrerequisite(Prerequisite prereq) {\n\t\tprerequisites.add(prereq);\n\t\treturn this;\n\t}\n\n\tpublic boolean allowed() {\n\t\treturn prerequisites.stream().allMatch(p -> p.met());\n\t}\n\n\tprivate LambdaRequest.VoidInterface cleanupFunction = () -> {};\n\n\tpublic Request withCleanup(LambdaRequest.VoidInterface cleanupFunction) {\n\t\tthis.cleanupFunction = cleanupFunction;\n\t\treturn this;\n\t}\n\n\tpublic void cleanup() {\n\t\tcleanupFunction.f();\n\t}\n\n}"
}
] | import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.team254.lib.util.Util;
import com.team5419.frc2023.Constants;
import com.team5419.frc2023.loops.ILooper;
import com.team5419.frc2023.loops.Loop;
import com.team5419.lib.requests.Request; | 2,524 | package com.team5419.frc2023.subsystems;
public class Arm extends ServoMotorSubsystem {
private static Arm mInstance;
public static Arm getInstance(){
if (mInstance == null) {
mInstance = new Arm(kArmConstants);
}
return mInstance;
}
| package com.team5419.frc2023.subsystems;
public class Arm extends ServoMotorSubsystem {
private static Arm mInstance;
public static Arm getInstance(){
if (mInstance == null) {
mInstance = new Arm(kArmConstants);
}
return mInstance;
}
| private static final ServoMotorSubsystemConstants kArmConstants = Constants.Arm.kArmServoConstants; | 1 | 2023-11-14 06:44:40+00:00 | 4k |
Ouest-France/querydsl-postgrest | src/test/java/fr/ouestfrance/querydsl/postgrest/PostgrestRepositoryGetMockTest.java | [
{
"identifier": "Page",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Page.java",
"snippet": "public interface Page<T> extends Iterable<T> {\n\n /**\n * Create simple page from items\n *\n * @param items items\n * @param <T> type of items\n * @return one page of items\n */\n @SafeVarargs\n static <T> Page<T> of(T... items) {\n return new PageImpl<>(Arrays.asList(items), Pageable.unPaged(), items.length, 1);\n }\n\n /**\n * Create an empty page\n *\n * @param <T> type of items\n * @return empty page\n */\n static <T> Page<T> empty() {\n return new PageImpl<>(List.of(), Pageable.unPaged(), 0, 0);\n }\n\n /**\n * Get data for a page\n *\n * @return data for a page\n */\n List<T> getData();\n\n /**\n * Get page request infomations\n *\n * @return Pageable information with number of elements, number of the page and sort options\n */\n Pageable getPageable();\n\n /**\n * Get size of page\n *\n * @return size of the data for the current page\n */\n default int size() {\n return getData().size();\n }\n\n /**\n * Get total elements from the datasource\n *\n * @return total elements\n */\n long getTotalElements();\n\n /**\n * Get the total pages\n *\n * @return total pages\n */\n int getTotalPages();\n\n /**\n * Streaming from the page\n *\n * @return stream\n */\n default Stream<T> stream() {\n return getData().stream();\n }\n\n @Override\n default Iterator<T> iterator() {\n return getData().iterator();\n }\n\n /**\n * Convert a page\n *\n * @param converter function that convert type to another\n * @param <U> type of returned object\n * @return page converted\n */\n default <U> Page<U> map(Function<T, U> converter) {\n return new PageImpl<>(stream().map(converter).toList(), getPageable(), getTotalElements(), getTotalPages());\n }\n}"
},
{
"identifier": "Pageable",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Pageable.java",
"snippet": "public interface Pageable {\n\n /**\n * Create a simple pageRequest with size and no declarative sort\n * @param pageSize number of element in one page\n * @return pageable object\n */\n static Pageable ofSize(int pageSize) {\n return ofSize(pageSize, null);\n }\n\n /**\n * Create a simple pageRequest with size and declarative sort\n * @param pageSize number of element in one page\n * @param sort sort information\n * @return pageable object\n */\n static Pageable ofSize(int pageSize, Sort sort) {\n return new PageRequest(0, pageSize, sort);\n }\n\n /**\n * Create an un paged\n * @return pageable object\n */\n static Pageable unPaged() {\n return new PageRequest(0, 0, null);\n }\n\n /**\n * Request page size\n * @return page size\n */\n int getPageSize();\n\n /**\n * Request page number\n * @return page number\n */\n int getPageNumber();\n\n /**\n * Request sort\n * @return sort\n */\n Sort getSort();\n\n /**\n * Transform a Pageable to range representation\n * @return transform a pagination item to range value\n */\n default String toRange() {\n return pageOffset() + \"-\" + pageLimit();\n }\n\n\n /**\n * Calculate the page offset (index of the first item)\n *\n * @return page offset\n */\n default int pageOffset() {\n return getPageNumber() * getPageSize();\n }\n\n /**\n * Calculate the page limit (index of the last item)\n *\n * @return page limit\n */\n default int pageLimit() {\n return pageOffset() + getPageSize() - 1;\n }\n\n\n}"
},
{
"identifier": "Sort",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Sort.java",
"snippet": "@Getter\n@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Sort {\n\n /**\n * List of orders queries\n */\n private final List<Order> orders;\n\n /**\n * Create sort from list of properties\n *\n * @param properties list of ordered keys to sort\n * @return Sort object with ascending direction\n */\n public static Sort by(String... properties) {\n return by(Direction.ASC, properties);\n }\n\n /**\n * Create sort from list of properties and direction\n *\n * @param direction direction (ASC, DESC)\n * @param properties list of ordered keys to sort\n * @return Sort object with specified direction\n */\n public static Sort by(Direction direction, String... properties) {\n return new Sort(Arrays.stream(properties)\n .map(x -> new Order(x, direction, NullHandling.NATIVE))\n .toList());\n }\n\n /**\n * Create sort from list of Order\n *\n * @param orders list of orders\n * @return Sort object with specified orders\n */\n public static Sort by(Sort.Order... orders) {\n return new Sort(Arrays.stream(orders).toList());\n }\n\n\n /**\n * Transform a sort to ascending sort\n *\n * @return ascending sort\n */\n public Sort ascending() {\n orders.forEach(x -> x.direction = Direction.ASC);\n return this;\n }\n\n /**\n * Transform a sort to descending sort\n *\n * @return descending sort\n */\n public Sort descending() {\n orders.forEach(x -> x.direction = Direction.DESC);\n return this;\n }\n\n /**\n * Sort direction\n */\n public enum Direction {\n /**\n * Ascending : from A to Z\n */\n ASC,\n /**\n * Descending : from Z to A\n */\n DESC\n }\n\n /**\n * Null Handling sort gesture\n */\n public enum NullHandling {\n /**\n * No null handling\n */\n NATIVE,\n /**\n * get nulls on top positions\n */\n NULLS_FIRST,\n /**\n * get nulls on last position\n */\n NULLS_LAST\n }\n\n /**\n * Order representation\n */\n @Getter\n @AllArgsConstructor(access = AccessLevel.PRIVATE)\n public static class Order {\n /**\n * property to filter\n */\n private final String property;\n /**\n * sort direction\n */\n private Direction direction;\n /**\n * Null Handling gesture\n */\n private NullHandling nullHandling;\n\n /**\n * Create ascending sort on property\n *\n * @param property property to sort\n * @return ascending sort\n */\n public static Order asc(String property) {\n return new Order(property, Direction.ASC, NullHandling.NATIVE);\n }\n\n /**\n * Create descending sort on property\n *\n * @param property property to sort\n * @return descending sort\n */\n public static Order desc(String property) {\n return new Order(property, Direction.DESC, NullHandling.NATIVE);\n }\n\n /**\n * Allow to retrieve nulls values first\n *\n * @return order\n */\n public Order nullsFirst() {\n nullHandling = NullHandling.NULLS_FIRST;\n return this;\n }\n\n /**\n * Allow to retrieve nulls values last\n *\n * @return order\n */\n public Order nullsLast() {\n nullHandling = NullHandling.NULLS_LAST;\n return this;\n }\n\n }\n\n}"
},
{
"identifier": "PostgrestRequestException",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/exceptions/PostgrestRequestException.java",
"snippet": "public class PostgrestRequestException extends RuntimeException {\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n */\n public PostgrestRequestException(String resourceName, String message) {\n this(resourceName, message, null);\n }\n\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n * @param cause exception raised\n */\n\n public PostgrestRequestException(String resourceName, String message, Throwable cause) {\n this(\"Error on querying \" + resourceName + \" cause by \" + message, cause);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n */\n public PostgrestRequestException(String message) {\n super(message);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n * @param cause exception raised\n */\n public PostgrestRequestException(String message, Throwable cause) {\n super(message, cause);\n }\n}"
},
{
"identifier": "QueryStringUtils",
"path": "src/main/java/fr/ouestfrance/querydsl/postgrest/utils/QueryStringUtils.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class QueryStringUtils {\n\n /**\n * Allow to transform a Multimap value to queryString\n * @param multimap multimap to transform\n * @return query string representation\n */\n public static String toQueryString(MultiValueMap<String, String> multimap){\n List<String> queryList = new ArrayList<>();\n multimap.forEach((key,values)-> values.forEach(value-> queryList.add(key+\"=\"+value)));\n return String.join(\"&\", queryList);\n }\n\n}"
}
] | import fr.ouestfrance.querydsl.postgrest.app.*;
import fr.ouestfrance.querydsl.postgrest.model.Page;
import fr.ouestfrance.querydsl.postgrest.model.Pageable;
import fr.ouestfrance.querydsl.postgrest.model.Sort;
import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException;
import fr.ouestfrance.querydsl.postgrest.utils.QueryStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.util.MultiValueMapAdapter;
import java.time.LocalDate;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when; | 3,551 | package fr.ouestfrance.querydsl.postgrest;
@Slf4j
class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest {
@Mock
private PostgrestWebClient webClient;
private PostgrestRepository<Post> repository;
@BeforeEach
void beforeEach() {
repository = new PostRepository(webClient);
}
@Test
void shouldSearchAllPosts() {
when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(null);
assertNotNull(search);
assertNotNull(search.iterator());
assertEquals(2, search.size());
}
private ResponseEntity<List<Object>> ok(List<Object> data) {
MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size())));
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
@Test
void shouldSearchWithPaginate() {
PostRequest request = new PostRequest();
request.setUserId(1);
request.setId(1);
request.setTitle("Test*");
request.setCodes(List.of("a", "b", "c"));
request.setExcludes(List.of("z"));
request.setValidDate(LocalDate.of(2023, 11, 10));
ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor();
ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor();
when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast())));
assertNotNull(search);
assertEquals(2, search.size());
// Assert query captors
MultiValueMap<String, String> queries = queryArgs.getValue();
log.info("queries {}", queries);
assertEquals("eq.1", queries.getFirst("userId"));
assertEquals("neq.1", queries.getFirst("id"));
assertEquals("lte.2023-11-10", queries.getFirst("startDate"));
assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or"));
assertEquals("like.Test*", queries.getFirst("title"));
assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order"));
assertEquals("*,authors(*)", queries.getFirst("select"));
assertEquals(2, queries.get("status").size());
// Assert headers captors
MultiValueMap<String, String> value = headerArgs.getValue();
assertEquals("0-9", value.getFirst("Range"));
assertEquals("items", value.getFirst("Range-Unit"));
}
@Test
void shouldSearchWithoutOrder() {
PostRequest request = new PostRequest();
ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor();
ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor();
when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(request, Pageable.ofSize(10));
assertNotNull(search);
assertEquals(2, search.size());
// Assert query captors
MultiValueMap<String, String> queries = queryArgs.getValue();
log.info("queries {}", queries);
assertNull(queries.getFirst("order"));
// Assert headers captors
MultiValueMap<String, String> value = headerArgs.getValue();
assertEquals("0-9", value.getFirst("Range"));
assertEquals("items", value.getFirst("Range-Unit"));
}
@Test
void shouldRaiseExceptionOnMultipleOne() {
when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); | package fr.ouestfrance.querydsl.postgrest;
@Slf4j
class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest {
@Mock
private PostgrestWebClient webClient;
private PostgrestRepository<Post> repository;
@BeforeEach
void beforeEach() {
repository = new PostRepository(webClient);
}
@Test
void shouldSearchAllPosts() {
when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(null);
assertNotNull(search);
assertNotNull(search.iterator());
assertEquals(2, search.size());
}
private ResponseEntity<List<Object>> ok(List<Object> data) {
MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size())));
return new ResponseEntity<>(data, headers, HttpStatus.OK);
}
@Test
void shouldSearchWithPaginate() {
PostRequest request = new PostRequest();
request.setUserId(1);
request.setId(1);
request.setTitle("Test*");
request.setCodes(List.of("a", "b", "c"));
request.setExcludes(List.of("z"));
request.setValidDate(LocalDate.of(2023, 11, 10));
ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor();
ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor();
when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast())));
assertNotNull(search);
assertEquals(2, search.size());
// Assert query captors
MultiValueMap<String, String> queries = queryArgs.getValue();
log.info("queries {}", queries);
assertEquals("eq.1", queries.getFirst("userId"));
assertEquals("neq.1", queries.getFirst("id"));
assertEquals("lte.2023-11-10", queries.getFirst("startDate"));
assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or"));
assertEquals("like.Test*", queries.getFirst("title"));
assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order"));
assertEquals("*,authors(*)", queries.getFirst("select"));
assertEquals(2, queries.get("status").size());
// Assert headers captors
MultiValueMap<String, String> value = headerArgs.getValue();
assertEquals("0-9", value.getFirst("Range"));
assertEquals("items", value.getFirst("Range-Unit"));
}
@Test
void shouldSearchWithoutOrder() {
PostRequest request = new PostRequest();
ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor();
ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor();
when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
Page<Post> search = repository.search(request, Pageable.ofSize(10));
assertNotNull(search);
assertEquals(2, search.size());
// Assert query captors
MultiValueMap<String, String> queries = queryArgs.getValue();
log.info("queries {}", queries);
assertNull(queries.getFirst("order"));
// Assert headers captors
MultiValueMap<String, String> value = headerArgs.getValue();
assertEquals("0-9", value.getFirst("Range"));
assertEquals("items", value.getFirst("Range-Unit"));
}
@Test
void shouldRaiseExceptionOnMultipleOne() {
when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); | assertThrows(PostgrestRequestException.class, () -> repository.findOne(null)); | 3 | 2023-11-14 10:45:54+00:00 | 4k |
threethan/QuestAudioPatcher | app/src/main/java/com/threethan/questpatcher/utils/dialogs/SigningOptionsDialog.java | [
{
"identifier": "APKSignActivity",
"path": "app/src/main/java/com/threethan/questpatcher/activities/APKSignActivity.java",
"snippet": "public class APKSignActivity extends AppCompatActivity {\n\n private AppCompatImageButton mClearKey, mClearCert;\n private MaterialTextView mKeySummary, mCertSummary;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_apksign);\n\n AppCompatImageButton mBack = findViewById(R.id.back);\n mClearKey = findViewById(R.id.clear_key);\n mClearCert = findViewById(R.id.clear_cert);\n MaterialTextView mInfo = findViewById(R.id.info);\n mKeySummary = findViewById(R.id.key_summary);\n mCertSummary = findViewById(R.id.cert_summary);\n FrameLayout mKey = findViewById(R.id.private_key);\n FrameLayout mCert = findViewById(R.id.cert);\n\n mInfo.setOnClickListener(v -> {\n Intent documentation = new Intent(this, DocumentationActivity.class);\n startActivity(documentation);\n });\n\n setStatus();\n\n mKey.setOnClickListener(v -> {\n if (Build.VERSION.SDK_INT >= 29) {\n Intent keyPicker = new Intent(Intent.ACTION_GET_CONTENT);\n keyPicker.setType(\"*/*\");\n keyPickerResultLauncher.launch(keyPicker);\n } else {\n Common.setPrivateKeyStatus(true);\n Intent filePicker = new Intent(this, FilePickerActivity.class);\n startActivity(filePicker);\n }\n });\n\n mCert.setOnClickListener(v -> {\n if (Build.VERSION.SDK_INT >= 29) {\n Intent certPicker = new Intent(Intent.ACTION_GET_CONTENT);\n certPicker.setType(\"*/*\");\n certPickerResultLauncher.launch(certPicker);\n } else {\n Common.setRSATemplateStatus(true);\n Intent filePicker = new Intent(this, FilePickerActivity.class);\n startActivity(filePicker);\n }\n });\n\n mBack.setOnClickListener(v -> finish());\n }\n\n private void setStatus() {\n if (sCommonUtils.getString(\"PrivateKey\", null, this) != null) {\n mKeySummary.setText(sCommonUtils.getString(\"PrivateKey\", null, this));\n mClearKey.setColorFilter(Color.RED);\n mClearKey.setVisibility(View.VISIBLE);\n mClearKey.setOnClickListener(v -> {\n sCommonUtils.saveString(\"PrivateKey\", null, this);\n sFileUtils.delete(new File(getFilesDir(), \"signing/APKEditor.pk8\"));\n mKeySummary.setText(getString(R.string.private_key_summary));\n mClearKey.setVisibility(View.GONE);\n });\n } else {\n mClearKey.setVisibility(View.GONE);\n }\n\n if (sCommonUtils.getString(\"X509Certificate\", null, this) != null) {\n mCertSummary.setText(sCommonUtils.getString(\"X509Certificate\", null, this));\n mClearCert.setColorFilter(Color.RED);\n mClearCert.setVisibility(View.VISIBLE);\n mClearCert.setOnClickListener(v -> {\n sCommonUtils.saveString(\"X509Certificate\", null, this);\n sFileUtils.delete(new File(getFilesDir(), \"signing/APKEditorCert\"));\n mCertSummary.setText(getString(R.string.x509_certificate_summary));\n mClearCert.setVisibility(View.GONE);\n });\n } else {\n mClearCert.setVisibility(View.GONE);\n }\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n ActivityResultLauncher<Intent> certPickerResultLauncher = registerForActivityResult(\n new ActivityResultContracts.StartActivityForResult(),\n result -> {\n if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {\n Intent data = result.getData();\n Uri uriFile = data.getData();\n\n if (uriFile != null) {\n new MaterialAlertDialogBuilder(this)\n .setMessage(getString(R.string.signing_select_question, getString(R.string.x509_certificate)))\n .setNegativeButton(R.string.cancel, (dialog, id) -> {\n })\n .setPositiveButton(R.string.select, (dialog, id) -> {\n sCommonUtils.saveString(\"X509Certificate\", new File(getFilesDir(), \"signing/APKEditorCert\").getAbsolutePath(), this);\n sFileUtils.copy(uriFile, new File(getFilesDir(), \"signing/APKEditorCert\"), this);\n setStatus();\n }).show();\n }\n }\n }\n );\n\n ActivityResultLauncher<Intent> keyPickerResultLauncher = registerForActivityResult(\n new ActivityResultContracts.StartActivityForResult(),\n result -> {\n if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {\n Intent data = result.getData();\n Uri uriFile = data.getData();\n\n if (uriFile != null) {\n new MaterialAlertDialogBuilder(this)\n .setMessage(getString(R.string.signing_select_question, getString(R.string.private_key)))\n .setNegativeButton(R.string.cancel, (dialog, id) -> {\n })\n .setPositiveButton(R.string.select, (dialog, id) -> {\n sCommonUtils.saveString(\"PrivateKey\", new File(getFilesDir(), \"signing/APKEditor.pk8\").getAbsolutePath(), this);\n sFileUtils.copy(uriFile, new File(getFilesDir(), \"signing/APKEditor.pk8\"), this);\n setStatus();\n }).show();\n }\n }\n }\n );\n\n @Override\n public void onResume() {\n super.onResume();\n\n setStatus();\n }\n\n @Override\n public void onStart() {\n super.onStart();\n\n if (Common.hasPrivateKey()) Common.setPrivateKeyStatus(false);\n if (Common.hasRASATemplate()) Common.setRSATemplateStatus(false);\n }\n\n}"
},
{
"identifier": "ResignAPKs",
"path": "app/src/main/java/com/threethan/questpatcher/utils/tasks/ResignAPKs.java",
"snippet": "public class ResignAPKs extends sExecutor {\n\n private final Activity mActivity;\n private final boolean mExit, mInstall;\n private final String mPackageName;\n private File mParent = null;\n private ProgressDialog mProgressDialog;\n private String mDetectedPackageName = null;\n\n public ResignAPKs(String packageName, boolean install, boolean exit, Activity activity) {\n mPackageName = packageName;\n mInstall = install;\n mExit = exit;\n mActivity = activity;\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPreExecute() {\n mProgressDialog = new ProgressDialog(mActivity);\n mProgressDialog.setMessage(mPackageName != null ? mActivity.getString(R.string.signing, sPackageUtils.getAppName(\n mPackageName, mActivity)) : mActivity.getString(R.string.resigning_apks));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIcon(R.mipmap.ic_launcher);\n mProgressDialog.setTitle(R.string.app_name);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n\n mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n }\n\n @Override\n public void doInBackground() {\n if (mPackageName == null) {\n // Find package name from the selected APKs\n mDetectedPackageName = APKData.findPackageName(mActivity);\n }\n\n if (mPackageName != null) {\n Common.getAPKList().clear();\n if (APKData.isAppBundle(sPackageUtils.getSourceDir(mPackageName, mActivity))) {\n Common.getAPKList().addAll(APKData.splitApks(sPackageUtils.getSourceDir(mPackageName, mActivity)));\n } else {\n Common.getAPKList().add(sPackageUtils.getSourceDir(mPackageName, mActivity));\n }\n }\n if (mDetectedPackageName != null || mPackageName != null) {\n String apkNameString;\n if (mPackageName != null) {\n apkNameString = mPackageName;\n } else {\n apkNameString = mDetectedPackageName;\n }\n if (Common.getAPKList().size() > 1) {\n if (mInstall) {\n mParent = new File(mActivity.getExternalCacheDir(), \"aee-signed\");\n } else {\n mParent = new File(APKData.getExportAPKsPath(mActivity), apkNameString + \"_aee-signed\");\n }\n if (mParent.exists()) {\n sFileUtils.delete(mParent);\n }\n sFileUtils.mkdir(mParent);\n for (String mSplits : Common.getAPKList()) {\n APKData.signApks(new File(mSplits), new File(mParent, new File(mSplits).getName()), mActivity);\n }\n } else {\n if (mInstall) {\n mParent = new File(mActivity.getCacheDir(), \"aee-signed.apk\");\n } else {\n mParent = new File(APKData.getExportAPKsPath(mActivity), apkNameString + \"_aee-signed.apk\");\n }\n if (mParent.exists()) {\n sFileUtils.delete(mParent);\n }\n APKData.signApks(new File(Common.getAPKList().get(0)), mParent, mActivity);\n }\n }\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPostExecute() {\n try {\n mProgressDialog.dismiss();\n } catch (IllegalArgumentException ignored) {\n }\n if (mDetectedPackageName == null && mPackageName == null) {\n sCommonUtils.snackBar(mActivity.findViewById(android.R.id.content), mActivity.getString(R.string.installation_status_bad_apks)).show();\n } else {\n if (mPackageName == null) {\n mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);\n if (mInstall) {\n if (Common.getAPKList().size() > 1) {\n List<String> signedAPKs = new ArrayList<>();\n for (File apkFile : Objects.requireNonNull(mParent.listFiles())) {\n signedAPKs.add(apkFile.getAbsolutePath());\n }\n SplitAPKInstaller.installSplitAPKs(mExit, signedAPKs, null, mActivity);\n } else {\n SplitAPKInstaller.installAPK(mExit, mParent, mActivity);\n }\n } else {\n new MaterialAlertDialogBuilder(mActivity)\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.app_name)\n .setMessage(mActivity.getString(R.string.resigned_apks_path, mParent.getAbsolutePath()))\n .setCancelable(false)\n .setPositiveButton(R.string.cancel, (dialog, id) -> {\n Common.isReloading(true);\n if (mExit) {\n mActivity.finish();\n }\n }\n ).show();\n }\n }\n }\n if (!Common.isFinished()) {\n Common.setFinishStatus(true);\n }\n }\n\n}"
}
] | import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import com.threethan.questpatcher.R;
import com.threethan.questpatcher.activities.APKSignActivity;
import com.threethan.questpatcher.utils.tasks.ResignAPKs;
import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils;
import in.sunilpaulmathew.sCommon.Dialog.sSingleItemDialog; | 2,738 | package com.threethan.questpatcher.utils.dialogs;
/*
* Created by APK Explorer & Editor <[email protected]> on January 30, 2023
*/
public class SigningOptionsDialog extends sSingleItemDialog {
private final Context mContext;
private final boolean mExit;
private final String mPackageName;
public SigningOptionsDialog(String packageName, boolean exit, Context context) {
super(0, null, new String[] {
context.getString(R.string.signing_default),
context.getString(R.string.signing_custom)
}, context);
mPackageName = packageName;
mExit = exit;
mContext = context;
}
@Override
public void onItemSelected(int position) {
sCommonUtils.saveBoolean("firstSigning", true, mContext);
if (position == 0) { | package com.threethan.questpatcher.utils.dialogs;
/*
* Created by APK Explorer & Editor <[email protected]> on January 30, 2023
*/
public class SigningOptionsDialog extends sSingleItemDialog {
private final Context mContext;
private final boolean mExit;
private final String mPackageName;
public SigningOptionsDialog(String packageName, boolean exit, Context context) {
super(0, null, new String[] {
context.getString(R.string.signing_default),
context.getString(R.string.signing_custom)
}, context);
mPackageName = packageName;
mExit = exit;
mContext = context;
}
@Override
public void onItemSelected(int position) {
sCommonUtils.saveBoolean("firstSigning", true, mContext);
if (position == 0) { | new ResignAPKs(mPackageName,false, mExit, (Activity) mContext).execute(); | 1 | 2023-11-18 15:13:30+00:00 | 4k |
jenkinsci/harbor-plugin | src/main/java/io/jenkins/plugins/harbor/client/HarborClient.java | [
{
"identifier": "HarborException",
"path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java",
"snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public HarborException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "Artifact",
"path": "src/main/java/io/jenkins/plugins/harbor/client/models/Artifact.java",
"snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class Artifact {\n private long id;\n private String type;\n private String mediaType;\n private String manifestMediaType;\n private String projectId;\n private String repositoryId;\n private String repositoryName;\n private String digest;\n private long size;\n private String icon;\n private Date pushTime;\n private Date pullTime;\n private HashMap<String, Object> extraAttrs;\n private String annotations;\n private String references;\n\n @JsonIgnore\n private String tags;\n\n @JsonIgnore\n private HashMap<String, AdditionLink> additionLinks;\n\n private String labels;\n\n @SuppressWarnings(\"lgtm[jenkins/plaintext-storage]\")\n private String accessories;\n\n private HashMap<String, NativeReportSummary> scanOverview;\n\n public String getMediaType() {\n return mediaType;\n }\n\n @JsonProperty(\"media_type\")\n public void setMediaType(String mediaType) {\n this.mediaType = mediaType;\n }\n\n public long getSize() {\n return size;\n }\n\n public void setSize(long size) {\n this.size = size;\n }\n\n public Date getPushTime() {\n return pushTime;\n }\n\n @JsonProperty(\"push_time\")\n public void setPushTime(Date pushTime) {\n this.pushTime = pushTime;\n }\n\n public String getTags() {\n return tags;\n }\n\n public void setTags(String tags) {\n this.tags = tags;\n }\n\n public HashMap<String, NativeReportSummary> getScanOverview() {\n return scanOverview;\n }\n\n @JsonProperty(\"scan_overview\")\n public void setScanOverview(HashMap<String, NativeReportSummary> scanOverview) {\n this.scanOverview = scanOverview;\n }\n\n public Date getPullTime() {\n return pullTime;\n }\n\n @JsonProperty(\"pull_time\")\n public void setPullTime(Date pullTime) {\n this.pullTime = pullTime;\n }\n\n public String getLabels() {\n return labels;\n }\n\n public void setLabels(String labels) {\n this.labels = labels;\n }\n\n public String getAccessories() {\n return accessories;\n }\n\n public void setAccessories(String accessories) {\n this.accessories = accessories;\n }\n\n public String getReferences() {\n return references;\n }\n\n public void setReferences(String references) {\n this.references = references;\n }\n\n public String getManifestMediaType() {\n return manifestMediaType;\n }\n\n @JsonProperty(\"manifest_media_type\")\n public void setManifestMediaType(String manifestMediaType) {\n this.manifestMediaType = manifestMediaType;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public String getRepositoryId() {\n return repositoryId;\n }\n\n @JsonProperty(\"repository_id\")\n public void setRepositoryId(String repositoryId) {\n this.repositoryId = repositoryId;\n }\n\n public HashMap<String, AdditionLink> getAdditionLinks() {\n return additionLinks;\n }\n\n @JsonProperty(\"addition_links\")\n public void setAdditionLinks(HashMap<String, AdditionLink> additionLinks) {\n this.additionLinks = additionLinks;\n }\n\n public String getProjectId() {\n return projectId;\n }\n\n @JsonProperty(\"project_id\")\n public void setProjectId(String projectId) {\n this.projectId = projectId;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getAnnotations() {\n return annotations;\n }\n\n public void setAnnotations(String annotations) {\n this.annotations = annotations;\n }\n\n public HashMap<String, Object> getExtraAttrs() {\n return extraAttrs;\n }\n\n @JsonProperty(\"extra_attrs\")\n public void setExtraAttrs(HashMap<String, Object> extraAttrs) {\n this.extraAttrs = extraAttrs;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n @JsonProperty(\"repository_name\")\n public void setRepositoryName(String repositoryName) {\n this.repositoryName = repositoryName;\n }\n}"
},
{
"identifier": "NativeReportSummary",
"path": "src/main/java/io/jenkins/plugins/harbor/client/models/NativeReportSummary.java",
"snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class NativeReportSummary {\n private String reportId;\n\n private VulnerabilityScanStatus ScanStatus;\n\n private Severity severity;\n\n private long duration;\n\n private VulnerabilitySummary summary;\n\n private ArrayList<String> cvebypassed;\n\n private Date StartTime;\n\n private Date EndTime;\n\n private Scanner scanner;\n\n private int completePercent;\n\n @JsonIgnore\n private int totalCount;\n\n @JsonIgnore\n private int completeCount;\n\n @JsonIgnore\n private VulnerabilityItemList vulnerabilityItemList;\n\n public String getReportId() {\n return reportId;\n }\n\n @JsonProperty(\"report_id\")\n public void setReportId(String reportId) {\n this.reportId = reportId;\n }\n\n public VulnerabilityScanStatus getScanStatus() {\n return ScanStatus;\n }\n\n @JsonProperty(\"scan_status\")\n public void setScanStatus(VulnerabilityScanStatus scanStatus) {\n ScanStatus = scanStatus;\n }\n\n public Severity getSeverity() {\n return severity;\n }\n\n public void setSeverity(Severity severity) {\n this.severity = severity;\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n public VulnerabilitySummary getSummary() {\n return summary;\n }\n\n public void setSummary(VulnerabilitySummary summary) {\n this.summary = summary;\n }\n\n public ArrayList<String> getCvebypassed() {\n return cvebypassed;\n }\n\n @JsonIgnore\n public void setCvebypassed(ArrayList<String> cvebypassed) {\n this.cvebypassed = cvebypassed;\n }\n\n public Date getStartTime() {\n return StartTime;\n }\n\n @JsonProperty(\"start_time\")\n public void setStartTime(Date startTime) {\n StartTime = startTime;\n }\n\n public Date getEndTime() {\n return EndTime;\n }\n\n @JsonProperty(\"end_time\")\n public void setEndTime(Date endTime) {\n EndTime = endTime;\n }\n\n public Scanner getScanner() {\n return scanner;\n }\n\n public void setScanner(Scanner scanner) {\n this.scanner = scanner;\n }\n\n public int getCompletePercent() {\n return completePercent;\n }\n\n @JsonProperty(\"complete_percent\")\n public void setCompletePercent(int completePercent) {\n this.completePercent = completePercent;\n }\n\n public int getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(int totalCount) {\n this.totalCount = totalCount;\n }\n\n public int getCompleteCount() {\n return completeCount;\n }\n\n public void setCompleteCount(int completeCount) {\n this.completeCount = completeCount;\n }\n\n public VulnerabilityItemList getVulnerabilityItemList() {\n return vulnerabilityItemList;\n }\n\n public void setVulnerabilityItemList(VulnerabilityItemList vulnerabilityItemList) {\n this.vulnerabilityItemList = vulnerabilityItemList;\n }\n}"
},
{
"identifier": "Repository",
"path": "src/main/java/io/jenkins/plugins/harbor/client/models/Repository.java",
"snippet": "public class Repository {\n private Integer id;\n private String name;\n\n @JsonProperty(\"artifact_count\")\n private Integer artifactCount;\n\n @JsonProperty(\"project_id\")\n private Integer projectId;\n\n @JsonProperty(\"pull_count\")\n private Integer pullCount;\n\n @JsonProperty(\"creation_time\")\n private String creationTime;\n\n @JsonProperty(\"update_time\")\n private String updateTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getArtifactCount() {\n return artifactCount;\n }\n\n public void setArtifactCount(Integer artifactCount) {\n this.artifactCount = artifactCount;\n }\n\n public String getCreationTime() {\n return creationTime;\n }\n\n public void setCreationTime(String creationTime) {\n this.creationTime = creationTime;\n }\n\n public Integer getProjectId() {\n return projectId;\n }\n\n public void setProjectId(Integer projectId) {\n this.projectId = projectId;\n }\n\n public Integer getPullCount() {\n return pullCount;\n }\n\n public void setPullCount(Integer pullCount) {\n this.pullCount = pullCount;\n }\n\n public String getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(String updateTime) {\n this.updateTime = updateTime;\n }\n}"
}
] | import edu.umd.cs.findbugs.annotations.Nullable;
import io.jenkins.plugins.harbor.HarborException;
import io.jenkins.plugins.harbor.client.models.Artifact;
import io.jenkins.plugins.harbor.client.models.NativeReportSummary;
import io.jenkins.plugins.harbor.client.models.Repository;
import java.io.IOException;
import java.util.Map; | 2,914 | package io.jenkins.plugins.harbor.client;
public interface HarborClient {
/**
* Get the vulnerabilities addition of the specific artifact
* <p>
* Get the vulnerabilities addition of the artifact specified by the reference under the project and repository.
*
* @param projectName The project name of Harbor
* @param repositoryName The name of
* @param reference The reference can be digest or tag.
*/
NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference);
/**
* Ping Harbor to check if it's alive.
* <p>
* This API simply replies a pong to indicate the process to handle API is up,
* disregarding the health status of dependent components.
*
* @return If the request succeeds, the 'Pong' string is returned
* @throws IOException The HTTP request failed
* @throws HarborException httpUrl is null
*/
String getPing() throws IOException;
/**
* List all authorized repositories
*
* @return Return to the list of repositories
*/
Repository[] listAllRepositories() throws IOException;
| package io.jenkins.plugins.harbor.client;
public interface HarborClient {
/**
* Get the vulnerabilities addition of the specific artifact
* <p>
* Get the vulnerabilities addition of the artifact specified by the reference under the project and repository.
*
* @param projectName The project name of Harbor
* @param repositoryName The name of
* @param reference The reference can be digest or tag.
*/
NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference);
/**
* Ping Harbor to check if it's alive.
* <p>
* This API simply replies a pong to indicate the process to handle API is up,
* disregarding the health status of dependent components.
*
* @return If the request succeeds, the 'Pong' string is returned
* @throws IOException The HTTP request failed
* @throws HarborException httpUrl is null
*/
String getPing() throws IOException;
/**
* List all authorized repositories
*
* @return Return to the list of repositories
*/
Repository[] listAllRepositories() throws IOException;
| Artifact[] listArtifacts(String projectName, String repositoryName, @Nullable Map<String, String> extraParams) | 1 | 2023-11-11 14:54:53+00:00 | 4k |
someElseIsHere/potato-golem | common/src/main/java/org/theplaceholder/potatogolem/PotatoGolemEntity.java | [
{
"identifier": "PotatoOwnerHurtByTargetGoal",
"path": "common/src/main/java/org/theplaceholder/potatogolem/goal/PotatoOwnerHurtByTargetGoal.java",
"snippet": "public class PotatoOwnerHurtByTargetGoal extends TargetGoal {\n private final PotatoGolemEntity tameAnimal;\n private LivingEntity ownerLastHurtBy;\n private int timestamp;\n\n public PotatoOwnerHurtByTargetGoal(PotatoGolemEntity tamableAnimal) {\n super(tamableAnimal, false);\n this.tameAnimal = tamableAnimal;\n this.setFlags(EnumSet.of(Flag.TARGET));\n }\n\n public boolean canUse() {\n if (this.tameAnimal.isTamed()) {\n LivingEntity livingEntity = this.tameAnimal.getOwner();\n if (livingEntity == null) {\n return false;\n } else {\n this.ownerLastHurtBy = livingEntity.getLastHurtByMob();\n int i = livingEntity.getLastHurtByMobTimestamp();\n return i != this.timestamp && ownerLastHurtBy != null && ownerLastHurtBy.isAlive() && ownerLastHurtBy != tameAnimal;\n }\n } else {\n return false;\n }\n }\n\n public void start() {\n this.mob.setTarget(this.ownerLastHurtBy);\n LivingEntity livingEntity = this.tameAnimal.getOwner();\n if (livingEntity != null) {\n this.timestamp = livingEntity.getLastHurtByMobTimestamp();\n }\n\n super.start();\n }\n}"
},
{
"identifier": "PotatoOwnerHurtTargetGoal",
"path": "common/src/main/java/org/theplaceholder/potatogolem/goal/PotatoOwnerHurtTargetGoal.java",
"snippet": "public class PotatoOwnerHurtTargetGoal extends TargetGoal {\n private final PotatoGolemEntity tameAnimal;\n private LivingEntity ownerLastHurt;\n private int timestamp;\n\n public PotatoOwnerHurtTargetGoal(PotatoGolemEntity tamableAnimal) {\n super(tamableAnimal, false);\n this.tameAnimal = tamableAnimal;\n this.setFlags(EnumSet.of(Flag.TARGET));\n }\n\n public boolean canUse() {\n if (this.tameAnimal.isTamed()) {\n LivingEntity livingEntity = this.tameAnimal.getOwner();\n if (livingEntity == null) {\n return false;\n } else {\n this.ownerLastHurt = livingEntity.getLastHurtMob();\n int i = livingEntity.getLastHurtMobTimestamp();\n return i != this.timestamp && ownerLastHurt != null && ownerLastHurt.isAlive() && ownerLastHurt != tameAnimal;\n }\n } else {\n return false;\n }\n }\n\n public void start() {\n this.mob.setTarget(this.ownerLastHurt);\n LivingEntity livingEntity = this.tameAnimal.getOwner();\n if (livingEntity != null) {\n this.timestamp = livingEntity.getLastHurtMobTimestamp();\n }\n\n super.start();\n }\n}"
}
] | import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.server.players.OldUsersConverter;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.goal.*;
import net.minecraft.world.entity.ai.goal.target.*;
import net.minecraft.world.entity.animal.IronGolem;
import net.minecraft.world.entity.monster.Creeper;
import net.minecraft.world.entity.monster.Enemy;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.theplaceholder.potatogolem.goal.PotatoOwnerHurtByTargetGoal;
import org.theplaceholder.potatogolem.goal.PotatoOwnerHurtTargetGoal;
import java.util.Optional;
import java.util.UUID; | 1,998 | package org.theplaceholder.potatogolem;
public class PotatoGolemEntity extends IronGolem implements OwnableEntity {
protected static final EntityDataAccessor<Optional<UUID>> DATA_OWNERUUID_ID = SynchedEntityData.defineId(PotatoGolemEntity.class, EntityDataSerializers.OPTIONAL_UUID);;
public PotatoGolemEntity(EntityType<PotatoGolemEntity> entityType, Level level) {
super(entityType, level);
}
@Override
protected void playStepSound(BlockPos blockPos, BlockState blockState) {
this.playSound(PotatoGolemSounds.STEP.get(), 1.0F, 1.0F);
}
@Override
public boolean hurt(DamageSource damageSource, float f) {
Crackiness crackiness = this.getCrackiness();
boolean bl = super.hurt(damageSource, f);
if (bl && this.getCrackiness() != crackiness) {
this.playSound(PotatoGolemSounds.DAMAGE.get(), 1.0F, 1.0F);
}
return bl;
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(DATA_OWNERUUID_ID, Optional.empty());
}
@Override
public boolean doHurtTarget(Entity entity) {
this.attackAnimationTick = 17;
this.level().broadcastEntityEvent(this, (byte)4);
float f = this.getAttackDamage();
float g = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f;
boolean bl = entity.hurt(this.damageSources().mobAttack(this), g);
if (bl) {
double d;
if (entity instanceof LivingEntity livingEntity) {
d = livingEntity.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE);
} else {
d = 0.0;
}
double e = Math.max(0.0, 1.0 - d);
entity.setDeltaMovement(entity.getDeltaMovement().add(0.0, 0.4000000059604645 * e, 0.0));
this.doEnchantDamageEffects(this, entity);
}
this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);
return bl;
}
@Override
protected @NotNull InteractionResult mobInteract(Player player, InteractionHand interactionHand) {
ItemStack itemStack = player.getItemInHand(interactionHand);
if (itemStack.is(Items.DIRT) && !isTamed()) {
setOwnerUUID(player.getUUID());
if(!player.isCreative())
itemStack.shrink(1);
spawnTamingParticles();
}
if (!itemStack.is(Items.POTATO)) {
return InteractionResult.PASS;
} else {
float f = this.getHealth();
this.heal(25.0F);
if (this.getHealth() == f) {
return InteractionResult.PASS;
} else {
float g = 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F;
this.playSound(PotatoGolemSounds.REPAIR.get(), 1.0F, g);
if (!player.getAbilities().instabuild) {
itemStack.shrink(1);
}
return InteractionResult.sidedSuccess(this.level().isClientSide);
}
}
}
@Override
public void handleEntityEvent(byte b) {
if (b == 4) {
this.attackAnimationTick = 17;
this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);
} else {
super.handleEntityEvent(b);
}
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0, true));
this.goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.9, 32.0F));
this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F));
this.goalSelector.addGoal(8, new RandomLookAroundGoal(this));
this.targetSelector.addGoal(2, new HurtByTargetGoal(this));
this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, false, false, (livingEntity) -> livingEntity instanceof Enemy && !(livingEntity instanceof Creeper)));
this.targetSelector.addGoal(5, new PotatoOwnerHurtByTargetGoal(this)); | package org.theplaceholder.potatogolem;
public class PotatoGolemEntity extends IronGolem implements OwnableEntity {
protected static final EntityDataAccessor<Optional<UUID>> DATA_OWNERUUID_ID = SynchedEntityData.defineId(PotatoGolemEntity.class, EntityDataSerializers.OPTIONAL_UUID);;
public PotatoGolemEntity(EntityType<PotatoGolemEntity> entityType, Level level) {
super(entityType, level);
}
@Override
protected void playStepSound(BlockPos blockPos, BlockState blockState) {
this.playSound(PotatoGolemSounds.STEP.get(), 1.0F, 1.0F);
}
@Override
public boolean hurt(DamageSource damageSource, float f) {
Crackiness crackiness = this.getCrackiness();
boolean bl = super.hurt(damageSource, f);
if (bl && this.getCrackiness() != crackiness) {
this.playSound(PotatoGolemSounds.DAMAGE.get(), 1.0F, 1.0F);
}
return bl;
}
@Override
protected void defineSynchedData() {
super.defineSynchedData();
this.entityData.define(DATA_OWNERUUID_ID, Optional.empty());
}
@Override
public boolean doHurtTarget(Entity entity) {
this.attackAnimationTick = 17;
this.level().broadcastEntityEvent(this, (byte)4);
float f = this.getAttackDamage();
float g = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f;
boolean bl = entity.hurt(this.damageSources().mobAttack(this), g);
if (bl) {
double d;
if (entity instanceof LivingEntity livingEntity) {
d = livingEntity.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE);
} else {
d = 0.0;
}
double e = Math.max(0.0, 1.0 - d);
entity.setDeltaMovement(entity.getDeltaMovement().add(0.0, 0.4000000059604645 * e, 0.0));
this.doEnchantDamageEffects(this, entity);
}
this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);
return bl;
}
@Override
protected @NotNull InteractionResult mobInteract(Player player, InteractionHand interactionHand) {
ItemStack itemStack = player.getItemInHand(interactionHand);
if (itemStack.is(Items.DIRT) && !isTamed()) {
setOwnerUUID(player.getUUID());
if(!player.isCreative())
itemStack.shrink(1);
spawnTamingParticles();
}
if (!itemStack.is(Items.POTATO)) {
return InteractionResult.PASS;
} else {
float f = this.getHealth();
this.heal(25.0F);
if (this.getHealth() == f) {
return InteractionResult.PASS;
} else {
float g = 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F;
this.playSound(PotatoGolemSounds.REPAIR.get(), 1.0F, g);
if (!player.getAbilities().instabuild) {
itemStack.shrink(1);
}
return InteractionResult.sidedSuccess(this.level().isClientSide);
}
}
}
@Override
public void handleEntityEvent(byte b) {
if (b == 4) {
this.attackAnimationTick = 17;
this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F);
} else {
super.handleEntityEvent(b);
}
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0, true));
this.goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.9, 32.0F));
this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F));
this.goalSelector.addGoal(8, new RandomLookAroundGoal(this));
this.targetSelector.addGoal(2, new HurtByTargetGoal(this));
this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, false, false, (livingEntity) -> livingEntity instanceof Enemy && !(livingEntity instanceof Creeper)));
this.targetSelector.addGoal(5, new PotatoOwnerHurtByTargetGoal(this)); | this.targetSelector.addGoal(6, new PotatoOwnerHurtTargetGoal(this)); | 1 | 2023-11-12 10:44:12+00:00 | 4k |
mike1226/SpringMVCExample-01 | src/main/java/com/example/servingwebcontent/repository/CustomerMapper.java | [
{
"identifier": "CustomerDynamicSqlSupport",
"path": "src/main/java/com/example/servingwebcontent/repository/CustomerDynamicSqlSupport.java",
"snippet": "public final class CustomerDynamicSqlSupport {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.555884+09:00\", comments = \"Source Table: public.customer\")\n\tpublic static final Customer customer = new Customer();\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556123+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic static final SqlColumn<String> id = customer.id;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556374+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic static final SqlColumn<String> username = customer.username;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556444+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic static final SqlColumn<String> email = customer.email;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556486+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic static final SqlColumn<String> phoneNumber = customer.phoneNumber;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556527+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic static final SqlColumn<String> postCode = customer.postCode;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.556047+09:00\", comments = \"Source Table: public.customer\")\n\tpublic static final class Customer extends AliasableSqlTable<Customer> {\n\t\tpublic final SqlColumn<String> id = column(\"id\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> username = column(\"username\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> email = column(\"email\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> phoneNumber = column(\"phone_number\", JDBCType.VARCHAR);\n\t\tpublic final SqlColumn<String> postCode = column(\"post_code\", JDBCType.VARCHAR);\n\n\t\tpublic Customer() {\n\t\t\tsuper(\"public.customer\", Customer::new);\n\t\t}\n\t}\n}"
},
{
"identifier": "Customer",
"path": "src/main/java/com/example/servingwebcontent/entity/Customer.java",
"snippet": "public class Customer {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.550902+09:00\", comments = \"Source field: public.customer.id\")\n\tprivate String id;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552784+09:00\", comments = \"Source field: public.customer.username\")\n\tprivate String username;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552893+09:00\", comments = \"Source field: public.customer.email\")\n\tprivate String email;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552994+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tprivate String phoneNumber;\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553138+09:00\", comments = \"Source field: public.customer.post_code\")\n\tprivate String postCode;\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.55244+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552729+09:00\", comments = \"Source field: public.customer.id\")\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552823+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552861+09:00\", comments = \"Source field: public.customer.username\")\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552927+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.552962+09:00\", comments = \"Source field: public.customer.email\")\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553027+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic String getPhoneNumber() {\n\t\treturn phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553091+09:00\", comments = \"Source field: public.customer.phone_number\")\n\tpublic void setPhoneNumber(String phoneNumber) {\n\t\tthis.phoneNumber = phoneNumber;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553186+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic String getPostCode() {\n\t\treturn postCode;\n\t}\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.553235+09:00\", comments = \"Source field: public.customer.post_code\")\n\tpublic void setPostCode(String postCode) {\n\t\tthis.postCode = postCode;\n\t}\n}"
}
] | import static com.example.servingwebcontent.repository.CustomerDynamicSqlSupport.*;
import static org.mybatis.dynamic.sql.SqlBuilder.*;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.dynamic.sql.BasicColumn;
import org.mybatis.dynamic.sql.delete.DeleteDSLCompleter;
import org.mybatis.dynamic.sql.select.CountDSLCompleter;
import org.mybatis.dynamic.sql.select.SelectDSLCompleter;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.dynamic.sql.update.UpdateDSL;
import org.mybatis.dynamic.sql.update.UpdateDSLCompleter;
import org.mybatis.dynamic.sql.update.UpdateModel;
import org.mybatis.dynamic.sql.util.SqlProviderAdapter;
import org.mybatis.dynamic.sql.util.mybatis3.CommonCountMapper;
import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper;
import org.mybatis.dynamic.sql.util.mybatis3.CommonInsertMapper;
import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper;
import org.mybatis.dynamic.sql.util.mybatis3.MyBatis3Utils;
import com.example.servingwebcontent.entity.Customer;
import jakarta.annotation.Generated; | 1,918 | package com.example.servingwebcontent.repository;
@Mapper
public interface CustomerMapper | package com.example.servingwebcontent.repository;
@Mapper
public interface CustomerMapper | extends CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<Customer>, CommonUpdateMapper { | 1 | 2023-11-12 08:22:27+00:00 | 4k |
thewaterfall/fluent-request | src/main/java/com/thewaterfall/request/FluentRequest.java | [
{
"identifier": "FluentHttpMethod",
"path": "src/main/java/com/thewaterfall/request/misc/FluentHttpMethod.java",
"snippet": "public enum FluentHttpMethod {\n GET,\n HEAD,\n POST,\n PUT,\n PATCH,\n DELETE,\n OPTIONS,\n TRACE\n}"
},
{
"identifier": "FluentIOException",
"path": "src/main/java/com/thewaterfall/request/misc/FluentIOException.java",
"snippet": "public class FluentIOException extends RuntimeException {\n /**\n * Constructs a FluentIOException with no specified detail message.\n */\n public FluentIOException() {\n }\n\n /**\n * Constructs a FluentIOException with the specified detail message.\n *\n * @param message The detail message.\n */\n public FluentIOException(String message) {\n super(message);\n }\n\n /**\n * Constructs a FluentIOException with the specified detail message and cause.\n *\n * @param message The detail message.\n * @param cause The cause of the exception.\n */\n public FluentIOException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a FluentIOException with the specified cause.\n *\n * @param cause The cause of the exception.\n */\n public FluentIOException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "FluentMappingException",
"path": "src/main/java/com/thewaterfall/request/misc/FluentMappingException.java",
"snippet": "public class FluentMappingException extends RuntimeException {\n /**\n * Constructs a FluentMappingException with no specified detail message.\n */\n public FluentMappingException() {\n }\n\n /**\n * Constructs a FluentMappingException with the specified detail message.\n *\n * @param message The detail message.\n */\n public FluentMappingException(String message) {\n super(message);\n }\n\n /**\n * Constructs a FluentMappingException with the specified detail message and cause.\n *\n * @param message The detail message.\n * @param cause The cause of the exception.\n */\n public FluentMappingException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Constructs a FluentMappingException with the specified cause.\n *\n * @param cause The cause of the exception.\n */\n public FluentMappingException(Throwable cause) {\n super(cause);\n }\n}"
},
{
"identifier": "FluentResponse",
"path": "src/main/java/com/thewaterfall/request/misc/FluentResponse.java",
"snippet": "public class FluentResponse<T> {\n private final T body;\n private final Response response;\n\n /**\n * Constructs a FluentResponse with the specified body and response.\n *\n * @param body The typed body of the response.\n * @param response The raw HTTP response.\n */\n public FluentResponse(T body, Response response) {\n this.body = body;\n this.response = response;\n }\n\n /**\n * Gets the typed body of the response.\n *\n * @return The typed body of the response.\n */\n public T getBody() {\n return body;\n }\n\n /**\n * Gets the raw OkHttp response.\n *\n * @return The raw HTTP response.\n */\n public Response getResponse() {\n return response;\n }\n}"
}
] | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thewaterfall.request.misc.FluentHttpMethod;
import com.thewaterfall.request.misc.FluentIOException;
import com.thewaterfall.request.misc.FluentMappingException;
import com.thewaterfall.request.misc.FluentResponse;
import okhttp3.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit; | 2,928 | package com.thewaterfall.request;
/**
* <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface
* for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods,
* request body types, headers, and authentication methods.</p>
*
* <p>It uses a predefined OkHttpClient and if it needs to be customized and configured,
* use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper,
* use {@link FluentRequest#overrideMapper(ObjectMapper)}</p>
*
* <p>Example usage:</p>
* <pre>{@code FluentRequest.request("https://api.example.com", Example.class)
* .bearer(EXAMPLE_TOKEN)
* .body(body)
* .post();}</pre>
*/
public class FluentRequest {
private static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
private static ObjectMapper mapper = new ObjectMapper();
/**
* Overrides the default OkHttpClient used for making HTTP requests.
*
* @param newClient The OkHttpClient to use for HTTP requests.
*/
private static void overrideClient(OkHttpClient newClient) {
client = newClient;
}
/**
* Overrides the default ObjectMapper used for JSON serialization and deserialization.
*
* @param newMapper The ObjectMapper to use for JSON processing.
*/
private static void overrideMapper(ObjectMapper newMapper) {
mapper = newMapper;
}
/**
* Initiates a new HTTP request builder with the specified URL and response type.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param client The OkHttpClient to use for this specific request.
* @param <T> The type of the expected response.
* @return A Builder instance for configuring the request.
*/
public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) {
return new Builder<>(url, responseType, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and default response type (Object).
*
* @param url The URL for the HTTP request.
* @param client The OkHttpClient to use for this specific request.
* @return A Builder instance for configuring the request.
*/
public static Builder<Object> request(String url, OkHttpClient client) {
return new Builder<>(url, Object.class, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and response type,
* using the default OkHttpClient.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param <T> The type of the expected response.
* @return A Builder instance for configuring the request.
*/
public static <T> Builder<T> request(String url, Class<T> responseType) {
return new Builder<>(url, responseType, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and default response type (Object),
* using the default OkHttpClient.
*
* @param url The URL for the HTTP request.
* @return A Builder instance for configuring the request.
*/
public static Builder<Object> request(String url) {
return new Builder<>(url, Object.class, client);
}
/**
* The Builder class is an inner class of FluentRequest and represents the actual builder
* for constructing FluentRequest instances with specific configurations.
*
* @param <T> The type of the expected response.
*/
public static class Builder<T> {
private OkHttpClient client;
private final String url;
private final Class<T> responseType;
private final Map<String, String> headers;
private final Map<String, Object> urlVariables;
private final Map<String, Object> queryParameters;
private RequestBody body;
public Builder(String url, Class<T> responseType) {
this.url = url;
this.responseType = responseType;
this.urlVariables = new HashMap<>();
this.queryParameters = new HashMap<>();
this.headers = new HashMap<>();
}
/**
* Constructs a new Builder instance with the specified URL, response type, and OkHttpClient.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param client The OkHttpClient to use for this specific request.
*/
public Builder(String url, Class<T> responseType, OkHttpClient client) {
this.client = client;
this.url = url;
this.responseType = responseType;
this.urlVariables = new HashMap<>();
this.queryParameters = new HashMap<>();
this.headers = new HashMap<>();
}
/**
* Sets the request body for the HTTP request.
*
* @param body The request body object.
* @return The Builder instance for method chaining.
* @throws FluentMappingException If there is an issue with mapping the body object to JSON.
*/
public Builder<T> body(Object body) throws FluentMappingException {
this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json"));
return this;
}
/**
* Sets the request body for the HTTP request using key-value pairs.
*
* @param body The map representing the request body.
* @return The Builder instance for method chaining.
* @throws FluentMappingException If there is an issue with mapping the body map to JSON.
*/
public Builder<T> body(Map<String, String> body) throws FluentMappingException {
this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json"));
return this;
}
/**
* Sets the request body for the HTTP request using a custom RequestBody. Use
* {@link FluentRequest.Builder#multipart()} to build multipart body and
* {@link FluentRequest.Builder#form()} to build form body.
*
* @param body The custom RequestBody.
* @return The Builder instance for method chaining.
* @see FluentRequest.Builder#multipart()
* @see FluentRequest.Builder#form()
*/
public Builder<T> body(RequestBody body) {
this.body = body;
return this;
}
/**
* Adds a URL variable to the request.
*
* @param name The name of the URL variable.
* @param value The value of the URL variable.
* @return The Builder instance for method chaining.
*/
public Builder<T> variable(String name, Object value) {
if (Objects.nonNull(value)) {
this.urlVariables.put(name, String.valueOf(value));
}
return this;
}
/**
* Adds multiple URL variables to the request.
*
* @param variables The map of URL variables.
* @return The Builder instance for method chaining.
*/
public Builder<T> variables(Map<String, Object> variables) {
this.urlVariables.putAll(variables);
return this;
}
/**
* Adds a query parameter to the request.
*
* @param name The name of the query parameter.
* @param value The value of the query parameter.
* @return The Builder instance for method chaining.
*/
public Builder<T> parameter(String name, Object value) {
if (Objects.nonNull(value)) {
this.queryParameters.put(name, Collections.singletonList(String.valueOf(value)));
}
return this;
}
/**
* Adds multiple query parameters to the request.
*
* @param parameters The map of query parameters.
* @return The Builder instance for method chaining.
*/
public Builder<T> parameters(Map<String, Object> parameters) {
this.queryParameters.putAll(parameters);
return this;
}
/**
* Adds a header to the request.
*
* @param name The name of the header.
* @param value The value of the header.
* @return The Builder instance for method chaining.
*/
public Builder<T> header(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Adds a bearer token to the request for bearer authentication.
*
* @param token The bearer token.
* @return The Builder instance for method chaining.
*/
public Builder<T> bearer(String token) {
this.headers.put("Authorization", "Bearer " + token);
return this;
}
/**
* Adds basic authentication to the request.
*
* @param name The username for basic authentication.
* @param password The password for basic authentication.
* @return The Builder instance for method chaining.
*/
public Builder<T> basic(String name, String password) {
this.headers.put("Authorization", Credentials.basic(name, password));
return this;
}
/**
* Initiates a multipart form data request.
*
* @return A FluentMultipartBody instance for configuring multipart form data.
* @see FluentMultipartBody
*/
public FluentMultipartBody<T> multipart() {
return new FluentMultipartBody<>(this);
}
/**
* Initiates a form-urlencoded request.
*
* @return A FluentFormBody instance for configuring form-urlencoded parameters.
* @see FluentFormBody
*/
public FluentFormBody<T> form() {
return new FluentFormBody<>(this);
}
/**
* Sends a GET request synchronously and returns the response.
*
* @return The FluentResponse containing the response body and HTTP response details.
*/ | package com.thewaterfall.request;
/**
* <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface
* for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods,
* request body types, headers, and authentication methods.</p>
*
* <p>It uses a predefined OkHttpClient and if it needs to be customized and configured,
* use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper,
* use {@link FluentRequest#overrideMapper(ObjectMapper)}</p>
*
* <p>Example usage:</p>
* <pre>{@code FluentRequest.request("https://api.example.com", Example.class)
* .bearer(EXAMPLE_TOKEN)
* .body(body)
* .post();}</pre>
*/
public class FluentRequest {
private static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
private static ObjectMapper mapper = new ObjectMapper();
/**
* Overrides the default OkHttpClient used for making HTTP requests.
*
* @param newClient The OkHttpClient to use for HTTP requests.
*/
private static void overrideClient(OkHttpClient newClient) {
client = newClient;
}
/**
* Overrides the default ObjectMapper used for JSON serialization and deserialization.
*
* @param newMapper The ObjectMapper to use for JSON processing.
*/
private static void overrideMapper(ObjectMapper newMapper) {
mapper = newMapper;
}
/**
* Initiates a new HTTP request builder with the specified URL and response type.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param client The OkHttpClient to use for this specific request.
* @param <T> The type of the expected response.
* @return A Builder instance for configuring the request.
*/
public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) {
return new Builder<>(url, responseType, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and default response type (Object).
*
* @param url The URL for the HTTP request.
* @param client The OkHttpClient to use for this specific request.
* @return A Builder instance for configuring the request.
*/
public static Builder<Object> request(String url, OkHttpClient client) {
return new Builder<>(url, Object.class, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and response type,
* using the default OkHttpClient.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param <T> The type of the expected response.
* @return A Builder instance for configuring the request.
*/
public static <T> Builder<T> request(String url, Class<T> responseType) {
return new Builder<>(url, responseType, client);
}
/**
* Initiates a new HTTP request builder with the specified URL and default response type (Object),
* using the default OkHttpClient.
*
* @param url The URL for the HTTP request.
* @return A Builder instance for configuring the request.
*/
public static Builder<Object> request(String url) {
return new Builder<>(url, Object.class, client);
}
/**
* The Builder class is an inner class of FluentRequest and represents the actual builder
* for constructing FluentRequest instances with specific configurations.
*
* @param <T> The type of the expected response.
*/
public static class Builder<T> {
private OkHttpClient client;
private final String url;
private final Class<T> responseType;
private final Map<String, String> headers;
private final Map<String, Object> urlVariables;
private final Map<String, Object> queryParameters;
private RequestBody body;
public Builder(String url, Class<T> responseType) {
this.url = url;
this.responseType = responseType;
this.urlVariables = new HashMap<>();
this.queryParameters = new HashMap<>();
this.headers = new HashMap<>();
}
/**
* Constructs a new Builder instance with the specified URL, response type, and OkHttpClient.
*
* @param url The URL for the HTTP request.
* @param responseType The class type of the expected response.
* @param client The OkHttpClient to use for this specific request.
*/
public Builder(String url, Class<T> responseType, OkHttpClient client) {
this.client = client;
this.url = url;
this.responseType = responseType;
this.urlVariables = new HashMap<>();
this.queryParameters = new HashMap<>();
this.headers = new HashMap<>();
}
/**
* Sets the request body for the HTTP request.
*
* @param body The request body object.
* @return The Builder instance for method chaining.
* @throws FluentMappingException If there is an issue with mapping the body object to JSON.
*/
public Builder<T> body(Object body) throws FluentMappingException {
this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json"));
return this;
}
/**
* Sets the request body for the HTTP request using key-value pairs.
*
* @param body The map representing the request body.
* @return The Builder instance for method chaining.
* @throws FluentMappingException If there is an issue with mapping the body map to JSON.
*/
public Builder<T> body(Map<String, String> body) throws FluentMappingException {
this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json"));
return this;
}
/**
* Sets the request body for the HTTP request using a custom RequestBody. Use
* {@link FluentRequest.Builder#multipart()} to build multipart body and
* {@link FluentRequest.Builder#form()} to build form body.
*
* @param body The custom RequestBody.
* @return The Builder instance for method chaining.
* @see FluentRequest.Builder#multipart()
* @see FluentRequest.Builder#form()
*/
public Builder<T> body(RequestBody body) {
this.body = body;
return this;
}
/**
* Adds a URL variable to the request.
*
* @param name The name of the URL variable.
* @param value The value of the URL variable.
* @return The Builder instance for method chaining.
*/
public Builder<T> variable(String name, Object value) {
if (Objects.nonNull(value)) {
this.urlVariables.put(name, String.valueOf(value));
}
return this;
}
/**
* Adds multiple URL variables to the request.
*
* @param variables The map of URL variables.
* @return The Builder instance for method chaining.
*/
public Builder<T> variables(Map<String, Object> variables) {
this.urlVariables.putAll(variables);
return this;
}
/**
* Adds a query parameter to the request.
*
* @param name The name of the query parameter.
* @param value The value of the query parameter.
* @return The Builder instance for method chaining.
*/
public Builder<T> parameter(String name, Object value) {
if (Objects.nonNull(value)) {
this.queryParameters.put(name, Collections.singletonList(String.valueOf(value)));
}
return this;
}
/**
* Adds multiple query parameters to the request.
*
* @param parameters The map of query parameters.
* @return The Builder instance for method chaining.
*/
public Builder<T> parameters(Map<String, Object> parameters) {
this.queryParameters.putAll(parameters);
return this;
}
/**
* Adds a header to the request.
*
* @param name The name of the header.
* @param value The value of the header.
* @return The Builder instance for method chaining.
*/
public Builder<T> header(String name, String value) {
headers.put(name, value);
return this;
}
/**
* Adds a bearer token to the request for bearer authentication.
*
* @param token The bearer token.
* @return The Builder instance for method chaining.
*/
public Builder<T> bearer(String token) {
this.headers.put("Authorization", "Bearer " + token);
return this;
}
/**
* Adds basic authentication to the request.
*
* @param name The username for basic authentication.
* @param password The password for basic authentication.
* @return The Builder instance for method chaining.
*/
public Builder<T> basic(String name, String password) {
this.headers.put("Authorization", Credentials.basic(name, password));
return this;
}
/**
* Initiates a multipart form data request.
*
* @return A FluentMultipartBody instance for configuring multipart form data.
* @see FluentMultipartBody
*/
public FluentMultipartBody<T> multipart() {
return new FluentMultipartBody<>(this);
}
/**
* Initiates a form-urlencoded request.
*
* @return A FluentFormBody instance for configuring form-urlencoded parameters.
* @see FluentFormBody
*/
public FluentFormBody<T> form() {
return new FluentFormBody<>(this);
}
/**
* Sends a GET request synchronously and returns the response.
*
* @return The FluentResponse containing the response body and HTTP response details.
*/ | public FluentResponse<T> get() throws FluentIOException { | 3 | 2023-11-14 12:53:50+00:00 | 4k |
wangxianhui111/xuechengzaixian | xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/service/impl/MediaFileProcessServiceImpl.java | [
{
"identifier": "MediaFilesMapper",
"path": "xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/mapper/MediaFilesMapper.java",
"snippet": "public interface MediaFilesMapper extends BaseMapper<MediaFiles> {\n\n}"
},
{
"identifier": "MediaProcessHistoryMapper",
"path": "xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/mapper/MediaProcessHistoryMapper.java",
"snippet": "public interface MediaProcessHistoryMapper extends BaseMapper<MediaProcessHistory> {\n\n}"
},
{
"identifier": "MediaProcessMapper",
"path": "xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/mapper/MediaProcessMapper.java",
"snippet": "public interface MediaProcessMapper extends BaseMapper<MediaProcess> {\n\n /**\n * 根据分片参数获取待处理任务\n *\n * @param shardTotal 分片总数\n * @param shardIndex 分片序号\n * @param count 任务数\n * @return {@link java.util.List}<{@link com.xuecheng.media.model.po.MediaProcess}>\n * @author Mr.M\n * @since 2022/9/14 8:54\n */\n @Select(\"SELECT * FROM media_process t where t.id % #{shardTotal} = #{shardIndex} LIMIT #{count};\")\n List<MediaProcess> selectListByShardIndex(@Param(\"shardTotal\") int shardTotal, @Param(\"shardIndex\") int shardIndex, @Param(\"count\") int count);\n\n}"
},
{
"identifier": "MediaFiles",
"path": "xuecheng-plus-media/xuecheng-plus-media-model/src/main/java/com/xuecheng/media/model/po/MediaFiles.java",
"snippet": "@Data\n@TableName(\"media_files\")\npublic class MediaFiles implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private String id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 机构名称\n */\n private String companyName;\n\n /**\n * 文件名称\n */\n private String filename;\n\n /**\n * 文件类型(文档,音频,视频)\n */\n private String fileType;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 存储目录\n */\n private String bucket;\n\n /**\n * 存储路径 <=> objectName(minio)\n */\n private String filePath;\n\n /**\n * 文件标识\n */\n private String fileId;\n\n /**\n * 媒资文件访问地址\n */\n private String url;\n\n /**\n * 上传人\n */\n private String username;\n\n /**\n * 上传时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 修改时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime changeDate;\n\n /**\n * 状态,1:正常,0:不展示\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 审核状态\n */\n private String auditStatus;\n\n /**\n * 审核意见\n */\n private String auditMind;\n\n /**\n * 文件大小\n */\n private Long fileSize;\n\n}"
},
{
"identifier": "MediaProcess",
"path": "xuecheng-plus-media/xuecheng-plus-media-model/src/main/java/com/xuecheng/media/model/po/MediaProcess.java",
"snippet": "@Data\n@TableName(\"media_process\")\npublic class MediaProcess implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 文件标识\n */\n private String fileId;\n\n /**\n * 文件名称\n */\n private String filename;\n\n /**\n * 存储源\n */\n private String bucket;\n\n /**\n * 处理状态字段,1:未处理,2:处理完成更,3:处理失败\n */\n private String status;\n\n /**\n * 文件路径 <=> objectName(minio)\n */\n private String filePath;\n\n /**\n * 上传时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 完成时间\n */\n private LocalDateTime finishDate;\n\n /**\n * 媒资文件访问地址\n */\n private String url;\n\n /**\n * 失败原因\n */\n private String errormsg;\n}"
},
{
"identifier": "MediaProcessHistory",
"path": "xuecheng-plus-media/xuecheng-plus-media-model/src/main/java/com/xuecheng/media/model/po/MediaProcessHistory.java",
"snippet": "@Data\n@TableName(\"media_process_history\")\npublic class MediaProcessHistory implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private Long id;\n\n /**\n * 文件标识\n */\n private String fileId;\n\n /**\n * 文件名称\n */\n private String filename;\n\n /**\n * 存储源\n */\n private String bucket;\n\n /**\n * 状态,1:未处理,视频处理完成更新为2\n */\n private String status;\n\n /**\n * 上传时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 完成时间\n */\n private LocalDateTime finishDate;\n\n /**\n * 媒资文件访问地址\n */\n private String url;\n\n /**\n * 文件路径\n */\n private String filePath;\n\n /**\n * 失败原因\n */\n private String errormsg;\n\n}"
},
{
"identifier": "MediaFileProcessService",
"path": "xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/service/MediaFileProcessService.java",
"snippet": "public interface MediaFileProcessService {\n\n /**\n * 获取待处理任务\n *\n * @param shardIndex 分片序号\n * @param shardTotal 分片总数\n * @param count 获取数量\n * @return {@link java.util.List}<{@link com.xuecheng.media.model.po.MediaProcess}>\n */\n List<MediaProcess> getMediaProcessList(int shardIndex, int shardTotal, int count);\n\n\n /**\n * 将 url 存储至数据,并更新状态为成功,并将待处理视频记录删除存入历史\n *\n * @param status 处理结果,2:成功 3 失败\n * @param fileId 文件 id\n * @param url 文件访问 url\n * @param errorMsg 失败原因\n * @author Mr.M\n * @since 2022/9/14 14:45\n */\n void saveProcessFinishStatus(String status, String fileId, String url, String errorMsg);\n\n}"
}
] | import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessHistoryMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.MediaProcessHistory;
import com.xuecheng.media.service.MediaFileProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects; | 2,037 | package com.xuecheng.media.service.impl;
/**
* 视频处理服务实现类
*
* @author Wuxy
* @version 1.0
* @ClassName MediaFileProcessServiceImpl
* @since 2023/1/25 16:09
*/
@Slf4j
@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {
@Resource
private MediaFilesMapper mediaFilesMapper;
@Resource | package com.xuecheng.media.service.impl;
/**
* 视频处理服务实现类
*
* @author Wuxy
* @version 1.0
* @ClassName MediaFileProcessServiceImpl
* @since 2023/1/25 16:09
*/
@Slf4j
@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {
@Resource
private MediaFilesMapper mediaFilesMapper;
@Resource | private MediaProcessMapper mediaProcessMapper; | 2 | 2023-11-13 11:39:35+00:00 | 4k |
dynatrace-research/ShuffleBench | shuffle-hzcast/src/main/java/com/dynatrace/research/shufflebench/HazelcastShuffle.java | [
{
"identifier": "AdvancedStateConsumer",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/AdvancedStateConsumer.java",
"snippet": "public class AdvancedStateConsumer implements StatefulConsumer {\n\n private static final long serialVersionUID = 0L;\n\n private static final int DEFAULT_STATE_SIZE = 4 * Long.BYTES;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AdvancedStateConsumer.class);\n\n private final String name;\n\n private final int outputRate;\n\n private final int stateSizeInBytes;\n\n private final boolean initCountRandom;\n\n private final Hasher64 hasher;\n\n public AdvancedStateConsumer(String name, int outputRate) {\n this(name, outputRate, DEFAULT_STATE_SIZE);\n }\n\n public AdvancedStateConsumer(String name, int outputRate, int stateSizeInBytes) {\n this(name, outputRate, stateSizeInBytes, false, 0);\n }\n\n public AdvancedStateConsumer(String name, int outputRate, int stateSizeInBytes, boolean initCountRandom, long seed) {\n this.name = requireNonNull(name);\n this.outputRate = outputRate;\n this.stateSizeInBytes = requireStateSizeGteDefault(stateSizeInBytes);\n this.initCountRandom = initCountRandom;\n this.hasher = Hashing.komihash4_3(seed);\n }\n\n @Override\n public ConsumerResult accept(TimestampedRecord record, State state) {\n if (state == null) {\n state = new State();\n }\n\n byte[] data = state.getData();\n long countInit = -1; // No count init per default\n if (data == null) {\n data = new byte[stateSizeInBytes];\n state.setData(data);\n\n if (initCountRandom) {\n // Take first 32 bytes of record (or less if record is smaller) as seed for random\n final long seedForRandom = hasher.hashBytesToLong(record.getData(), 0, Math.min(record.getData().length, 32));\n final SplittableRandom random = new SplittableRandom(seedForRandom);\n countInit = random.nextInt(outputRate);\n }\n\n }\n\n final ByteBuffer stateBuffer = ByteBuffer.wrap(data);\n final long count = ((countInit == -1) ? stateBuffer.getLong() : countInit) + 1;\n final long sum = stateBuffer.getLong();\n\n stateBuffer.rewind();\n stateBuffer.putLong(count);\n stateBuffer.putLong(sum + ByteBuffer.wrap(record.getData()).getLong()); // Is allowed to overflow\n if (count == 1) {\n stateBuffer.putLong(record.getTimestamp()); // start timestamp\n } else {\n stateBuffer.position(stateBuffer.position() + Long.BYTES); // start timestamp\n }\n stateBuffer.putLong(record.getTimestamp()); // end timestamp\n final int bytesToCopy = Math.min(stateBuffer.remaining(), record.getData().length);\n stateBuffer.put(record.getData(), 0, bytesToCopy); // fill with data from record\n\n LOGGER.debug(\"{}: count = {}\", name, count);\n\n if (count == this.outputRate) {\n final ConsumerEvent event = new ConsumerEvent(Arrays.copyOf(data, data.length));\n Arrays.fill(data, (byte) 0); // reset the state byte buffer to 0s\n return new ConsumerResult(state, event);\n } else {\n return new ConsumerResult(state);\n }\n }\n\n private static int requireStateSizeGteDefault(int stateSize) {\n if (stateSize < DEFAULT_STATE_SIZE) {\n throw new IllegalArgumentException(\"State size must be at least \" + DEFAULT_STATE_SIZE + \".\");\n }\n return stateSize;\n }\n\n}"
},
{
"identifier": "State",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/State.java",
"snippet": "public class State {\n private byte[] data;\n\n public State() {\n }\n\n public State(byte[] data) {\n this.data = data;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public void setData(byte[] data) {\n this.data = data;\n }\n\n}"
},
{
"identifier": "StatefulConsumer",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/StatefulConsumer.java",
"snippet": "@FunctionalInterface\npublic interface StatefulConsumer extends Serializable {\n\n /**\n * @param record a new data record\n * @param state the current state\n * @return the updated state\n */\n ConsumerResult accept(TimestampedRecord record, State state);\n}"
},
{
"identifier": "MatcherService",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/matcher/MatcherService.java",
"snippet": "public interface MatcherService<T extends Record> {\n\n /**\n * Adds a new matching rule\n *\n * @param id an ID for the matching rule\n * @param matchingRule the matching rule\n */\n void addMatchingRule(String id, MatchingRule matchingRule);\n\n /**\n * Removes a matching rule\n *\n * @param id the ID of the matching rule to be deleted\n * @return true if a round was found deleted, false otherwise\n */\n boolean removeMatchingRule(String id);\n\n /**\n * Finds the IDs of all corresponding consumers for this record.\n *\n * @param record The record to be matched\n */\n Collection<Map.Entry<String, T>> match(T record);\n}"
},
{
"identifier": "SimpleMatcherService",
"path": "commons/src/main/java/com/dynatrace/research/shufflebench/matcher/SimpleMatcherService.java",
"snippet": "public class SimpleMatcherService<T extends Record> implements MatcherService<T> {\n\n private final Map<String, MatchingRule> matchingRuleEntries = new HashMap<>();\n\n private final RangeBasedMatchingRuleIndex rangeBasedMatchingRuleIndex = new RangeBasedMatchingRuleIndex();\n\n\n @Override\n public void addMatchingRule(String id, MatchingRule matchingRule) {\n if (matchingRule instanceof RangeBasedMatchingRule) {\n matchingRuleEntries.remove(id);\n rangeBasedMatchingRuleIndex.add(id, (RangeBasedMatchingRule) matchingRule);\n } else {\n rangeBasedMatchingRuleIndex.remove(id);\n matchingRuleEntries.put(id, matchingRule);\n }\n }\n\n @Override\n public boolean removeMatchingRule(String id) {\n return (matchingRuleEntries.remove(id) != null) || rangeBasedMatchingRuleIndex.remove(id);\n }\n\n @Override\n public Collection<Map.Entry<String, T>> match(T record) {\n List<Map.Entry<String, T>> result = new ArrayList<>();\n\n rangeBasedMatchingRuleIndex.forEachMatchingConsumer(record, id -> result.add(Map.entry(id, record)));\n\n for (Map.Entry<String, MatchingRule> entry : matchingRuleEntries.entrySet()) {\n if (entry.getValue().test(record)) {\n result.add(Map.entry(entry.getKey(), record));\n }\n }\n\n return result;\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromZipf(\n final int numRules,\n final double totalSelectivity,\n final double s,\n final long seed\n ) {\n double weightsTotal = 0.0;\n final double[] weigths = new double[numRules];\n for (int k = 1; k <= numRules; k++) {\n weigths[k - 1] = 1 / Math.pow(k, s);\n weightsTotal += weigths[k - 1];\n }\n final double finalWeightsTotal = weightsTotal;\n final Stream<Map.Entry<Double, Integer>> frequencyStream = IntStream.range(0, numRules)\n .mapToObj(ruleId -> Map.entry(\n (weigths[ruleId] / finalWeightsTotal) * totalSelectivity, // selectivity\n 1 // frequency\n ));\n return createFromFrequencyStream(frequencyStream, seed);\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromFrequencyMap(Map<Double, Integer> selectivities, final long seed) {\n return createFromFrequencyStream(selectivities.entrySet().stream(), seed);\n }\n\n public static <T extends Record> SimpleMatcherService<T> createFromFrequencyStream(Stream<Map.Entry<Double, Integer>> selectivities, final long seed) {\n final SimpleMatcherService<T> matcherService = new SimpleMatcherService<>();\n final AtomicInteger ruleCounter = new AtomicInteger(0);\n selectivities.forEach(entry -> {\n final int numRules = entry.getValue();\n final double selectivity = entry.getKey();\n for (int i = 0; i < numRules; i++) {\n final int ruleNumber = ruleCounter.getAndIncrement();\n matcherService.addMatchingRule(\n \"consumer_\" + ruleNumber,\n new RangeBasedMatchingRule(Hashing.komihash4_3().hashStream().putLong(seed).putInt(ruleNumber).getAsLong(), selectivity));\n }\n });\n return matcherService;\n }\n\n}"
}
] | import com.dynatrace.research.shufflebench.consumer.AdvancedStateConsumer;
import com.dynatrace.research.shufflebench.consumer.State;
import com.dynatrace.research.shufflebench.consumer.StatefulConsumer;
import com.dynatrace.research.shufflebench.matcher.MatcherService;
import com.dynatrace.research.shufflebench.matcher.SimpleMatcherService;
import com.dynatrace.research.shufflebench.record.*;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.Traversers;
import com.hazelcast.jet.Util;
import com.hazelcast.jet.config.EdgeConfig;
import com.hazelcast.jet.config.JobConfig;
import com.hazelcast.jet.config.ProcessingGuarantee;
import com.hazelcast.jet.kafka.KafkaSinks;
import com.hazelcast.jet.kafka.KafkaSources;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.ServiceFactory;
import com.hazelcast.spi.properties.ClusterProperty;
import io.smallrye.config.SmallRyeConfig;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.hazelcast.jet.pipeline.ServiceFactories.nonSharedService; | 3,127 | package com.dynatrace.research.shufflebench;
public class HazelcastShuffle {
private static final String APPLICATION_ID = "shufflebench-hzcast";
private static final Logger LOGGER = LoggerFactory.getLogger(HazelcastShuffle.class);
private final Pipeline pipeline;
private HazelcastInstance hazelcast;
public HazelcastShuffle() {
final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class);
final Properties kafkaProps = new Properties();
kafkaProps.put(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
config.getValue("kafka.bootstrap.servers", String.class));
final Properties kafkaConsumerProps = new Properties();
kafkaConsumerProps.putAll(kafkaProps);
kafkaConsumerProps.put(
ConsumerConfig.GROUP_ID_CONFIG,
APPLICATION_ID);
// props.put(
// ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,
// true);
kafkaConsumerProps.put(
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
ByteArrayDeserializer.class);
kafkaConsumerProps.put(
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
RecordSerde.RecordDeserializer.class);
kafkaConsumerProps.putAll(
config.getOptionalValues("kafka.consumer", String.class, String.class).orElse(Map.of()));
final Properties kafkaProducerProps = new Properties();
kafkaProducerProps.putAll(kafkaProps);
kafkaProducerProps.put(
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class);
kafkaProducerProps.put(
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
ConsumerEventSerde.ConsumerEventSerializer.class);
kafkaProducerProps.putAll(
config.getOptionalValues("kafka.producer", String.class, String.class).orElse(Map.of()));
final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class);
final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class);
final SmallRyeConfig smallRyeConfig = config.unwrap(SmallRyeConfig.class);
final Map<Double, Integer> selectivities =
smallRyeConfig.getOptionalValues("matcher.selectivities", Double.class, Integer.class).orElse(null);
final double totalSelectivity = config.getValue("matcher.zipf.total.selectivity", Double.class);
final int numRules = config.getValue("matcher.zipf.num.rules", Integer.class);
final double s = config.getValue("matcher.zipf.s", Double.class);
final int outputRate = config.getValue("consumer.output.rate", Integer.class);
final int stateSizeBytes = config.getValue("consumer.state.size.bytes", Integer.class);
final boolean initCountRandom = config.getValue("consumer.init.count.random", Boolean.class);
final long initCountSeed = config.getValue("consumer.init.count.seed", Long.class);
ServiceFactory<?, MatcherService<TimestampedRecord>> matcherServiceFactory = nonSharedService(
pctx -> {
if (selectivities != null) {
return SimpleMatcherService.createFromFrequencyMap(selectivities, 0x2e3fac4f58fc98b4L);
} else {
return SimpleMatcherService.createFromZipf(
numRules,
totalSelectivity,
s,
0x2e3fac4f58fc98b4L);
}
});
| package com.dynatrace.research.shufflebench;
public class HazelcastShuffle {
private static final String APPLICATION_ID = "shufflebench-hzcast";
private static final Logger LOGGER = LoggerFactory.getLogger(HazelcastShuffle.class);
private final Pipeline pipeline;
private HazelcastInstance hazelcast;
public HazelcastShuffle() {
final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class);
final Properties kafkaProps = new Properties();
kafkaProps.put(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
config.getValue("kafka.bootstrap.servers", String.class));
final Properties kafkaConsumerProps = new Properties();
kafkaConsumerProps.putAll(kafkaProps);
kafkaConsumerProps.put(
ConsumerConfig.GROUP_ID_CONFIG,
APPLICATION_ID);
// props.put(
// ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,
// true);
kafkaConsumerProps.put(
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
ByteArrayDeserializer.class);
kafkaConsumerProps.put(
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
RecordSerde.RecordDeserializer.class);
kafkaConsumerProps.putAll(
config.getOptionalValues("kafka.consumer", String.class, String.class).orElse(Map.of()));
final Properties kafkaProducerProps = new Properties();
kafkaProducerProps.putAll(kafkaProps);
kafkaProducerProps.put(
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class);
kafkaProducerProps.put(
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
ConsumerEventSerde.ConsumerEventSerializer.class);
kafkaProducerProps.putAll(
config.getOptionalValues("kafka.producer", String.class, String.class).orElse(Map.of()));
final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class);
final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class);
final SmallRyeConfig smallRyeConfig = config.unwrap(SmallRyeConfig.class);
final Map<Double, Integer> selectivities =
smallRyeConfig.getOptionalValues("matcher.selectivities", Double.class, Integer.class).orElse(null);
final double totalSelectivity = config.getValue("matcher.zipf.total.selectivity", Double.class);
final int numRules = config.getValue("matcher.zipf.num.rules", Integer.class);
final double s = config.getValue("matcher.zipf.s", Double.class);
final int outputRate = config.getValue("consumer.output.rate", Integer.class);
final int stateSizeBytes = config.getValue("consumer.state.size.bytes", Integer.class);
final boolean initCountRandom = config.getValue("consumer.init.count.random", Boolean.class);
final long initCountSeed = config.getValue("consumer.init.count.seed", Long.class);
ServiceFactory<?, MatcherService<TimestampedRecord>> matcherServiceFactory = nonSharedService(
pctx -> {
if (selectivities != null) {
return SimpleMatcherService.createFromFrequencyMap(selectivities, 0x2e3fac4f58fc98b4L);
} else {
return SimpleMatcherService.createFromZipf(
numRules,
totalSelectivity,
s,
0x2e3fac4f58fc98b4L);
}
});
| final StatefulConsumer consumer = new AdvancedStateConsumer("counter", outputRate, stateSizeBytes, initCountRandom, initCountSeed); | 2 | 2023-11-17 08:53:15+00:00 | 4k |
KafeinDev/InteractiveNpcs | src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java | [
{
"identifier": "Command",
"path": "src/main/java/dev/kafein/interactivenpcs/command/Command.java",
"snippet": "public interface Command {\n CommandProperties getProperties();\n\n String getName();\n\n List<String> getAliases();\n\n boolean isAlias(@NotNull String alias);\n\n String getDescription();\n\n String getUsage();\n\n @Nullable String getPermission();\n\n List<Command> getSubCommands();\n\n Command findSubCommand(@NotNull String sub);\n\n Command findSubCommand(@NotNull String... subs);\n\n int findSubCommandIndex(@NotNull String... subs);\n\n List<RegisteredTabCompletion> getTabCompletions();\n\n List<RegisteredTabCompletion> getTabCompletions(int index);\n\n void execute(@NotNull CommandSender sender, @NotNull String[] args);\n}"
},
{
"identifier": "InteractionCommand",
"path": "src/main/java/dev/kafein/interactivenpcs/commands/InteractionCommand.java",
"snippet": "public final class InteractionCommand extends AbstractCommand {\n private final InteractiveNpcs plugin;\n\n public InteractionCommand(InteractiveNpcs plugin) {\n super(CommandProperties.newBuilder()\n .name(\"interaction\")\n .usage(\"/interaction\")\n .description(\"Command for InteractiveNpcs plugin\")\n .permission(\"interactions.admin\")\n .build(),\n ImmutableList.of(\n new ReloadCommand(plugin)\n ));\n this.plugin = plugin;\n }\n\n @Override\n public void execute(@NotNull CommandSender sender, @NotNull String[] args) {\n\n }\n}"
},
{
"identifier": "Compatibility",
"path": "src/main/java/dev/kafein/interactivenpcs/compatibility/Compatibility.java",
"snippet": "public interface Compatibility {\n void initialize();\n}"
},
{
"identifier": "CompatibilityFactory",
"path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityFactory.java",
"snippet": "public final class CompatibilityFactory {\n private CompatibilityFactory() {\n }\n\n public static Compatibility createCompatibility(@NotNull CompatibilityType type, @NotNull InteractiveNpcs plugin) {\n switch (type) {\n case VAULT:\n return new VaultCompatibility(plugin);\n case CITIZENS:\n return new CitizensCompatibility(plugin);\n default:\n return null;\n }\n }\n}"
},
{
"identifier": "CompatibilityType",
"path": "src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityType.java",
"snippet": "public enum CompatibilityType {\n VAULT(\"Vault\"),\n PLACEHOLDER_API(\"PlaceholderAPI\"),\n CITIZENS(\"Citizens\");\n\n private final String pluginName;\n\n CompatibilityType(String pluginName) {\n this.pluginName = pluginName;\n }\n\n public String getPluginName() {\n return this.pluginName;\n }\n}"
},
{
"identifier": "Config",
"path": "src/main/java/dev/kafein/interactivenpcs/configuration/Config.java",
"snippet": "public final class Config {\n private final ConfigType type;\n private final ConfigurationNode node;\n private final @Nullable Path path;\n\n public Config(ConfigType type, ConfigurationNode node, @Nullable Path path) {\n this.node = node;\n this.type = type;\n this.path = path;\n }\n\n public ConfigType getType() {\n return this.type;\n }\n\n public ConfigurationNode getNode() {\n return this.node;\n }\n\n public @Nullable Path getPath() {\n return this.path;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Config)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n\n Config config = (Config) obj;\n return Objects.equals(this.type, config.type)\n && Objects.equals(this.node, config.node)\n && Objects.equals(this.path, config.path);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.type, this.node, this.path);\n }\n\n @Override\n public String toString() {\n return \"Config{\" +\n \"type=\" + this.type +\n \", node=\" + this.node +\n \", path=\" + this.path +\n '}';\n }\n}"
},
{
"identifier": "ConfigVariables",
"path": "src/main/java/dev/kafein/interactivenpcs/configuration/ConfigVariables.java",
"snippet": "public final class ConfigVariables {\n private ConfigVariables() {}\n\n public static final ConfigKey<String> OFFSET_SYMBOL = ConfigKey.of(\"%img_offset_-1%\", \"offset-symbol\");\n\n public static final ConfigKey<List<String>> SPEECH_BUBBLE_LINES_FONTS = ConfigKey.of(ImmutableList.of(), \"speech\", \"bubble-lines\", \"fonts\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_COLOR = ConfigKey.of(\"<black>\", \"speech\", \"bubble-lines\", \"default-color\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_OFFSET = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"default-offset\");\n public static final ConfigKey<String> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_SYMBOL = ConfigKey.of(\"%img_bubble%\", \"speech\", \"bubble-lines\", \"image\", \"default-symbol\");\n public static final ConfigKey<Integer> SPEECH_BUBBLE_LINES_DEFAULT_IMAGE_WIDTH = ConfigKey.of(0, \"speech\", \"bubble-lines\", \"image\", \"default-width\");\n}"
},
{
"identifier": "ConversationManager",
"path": "src/main/java/dev/kafein/interactivenpcs/conversation/ConversationManager.java",
"snippet": "public final class ConversationManager {\n private final InteractiveNpcs plugin;\n\n private final Cache<Integer, InteractiveEntity> interactiveEntities;\n private final Cache<UUID, Conversation> conversations;\n\n public ConversationManager(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.interactiveEntities = CacheBuilder.newBuilder()\n .build();\n this.conversations = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n\n }\n\n public void interact(@NotNull UUID interactantUniqueId) {\n Player player = Bukkit.getPlayer(interactantUniqueId);\n if (player != null) {\n this.interact(player);\n }\n }\n\n public void interact(@NotNull Player player) {\n\n }\n\n public void interact(@NotNull Conversation conversation) {\n\n }\n\n public Cache<Integer, InteractiveEntity> getInteractiveEntities() {\n return this.interactiveEntities;\n }\n\n public InteractiveEntity getInteractiveEntity(int name) {\n return this.interactiveEntities.getIfPresent(name);\n }\n\n public void putInteractiveEntity(@NotNull InteractiveEntity interactiveEntity) {\n this.interactiveEntities.put(interactiveEntity.getId(), interactiveEntity);\n }\n\n public void removeInteractiveEntity(int name) {\n this.interactiveEntities.invalidate(name);\n }\n\n public Cache<UUID, Conversation> getConversations() {\n return this.conversations;\n }\n\n public Conversation getConversation(@NotNull UUID uuid) {\n return this.conversations.getIfPresent(uuid);\n }\n\n public void putConversation(@NotNull Conversation conversation) {\n this.conversations.put(conversation.getInteractantUniqueId(), conversation);\n }\n\n public void removeConversation(@NotNull UUID uuid) {\n this.conversations.invalidate(uuid);\n }\n}"
},
{
"identifier": "CharWidthMap",
"path": "src/main/java/dev/kafein/interactivenpcs/conversation/text/font/CharWidthMap.java",
"snippet": "public final class CharWidthMap {\n public static final int DEFAULT_WIDTH = 3;\n\n private final InteractiveNpcs plugin;\n private final Cache<Character, Integer> widths;\n\n public CharWidthMap(InteractiveNpcs plugin) {\n this.plugin = plugin;\n this.widths = CacheBuilder.newBuilder()\n .build();\n }\n\n public void initialize() {\n CharWidth[] values = CharWidth.values();\n for (CharWidth value : values) {\n this.widths.put(value.getCharacter(), value.getWidth());\n }\n\n //load from configs\n\n this.plugin.getLogger().info(\"CharWidthMap initialized.\");\n }\n\n public Cache<Character, Integer> getWidths() {\n return this.widths;\n }\n\n public int get(Character character) {\n return Optional.ofNullable(this.widths.getIfPresent(character))\n .orElse(DEFAULT_WIDTH);\n }\n\n public void put(Character character, int width) {\n this.widths.put(character, width);\n }\n\n public void remove(Character character) {\n this.widths.invalidate(character);\n }\n}"
},
{
"identifier": "AbstractBukkitPlugin",
"path": "src/main/java/dev/kafein/interactivenpcs/plugin/AbstractBukkitPlugin.java",
"snippet": "public abstract class AbstractBukkitPlugin implements BukkitPlugin {\n private final Plugin plugin;\n\n private ConfigManager configManager;\n private CommandManager commandManager;\n private BukkitAudiences bukkitAudiences;\n private ProtocolManager protocolManager;\n\n protected AbstractBukkitPlugin(Plugin plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void load() {\n onLoad();\n }\n\n public abstract void onLoad();\n\n @Override\n public void enable() {\n getLogger().info(\"Loading configs...\");\n this.configManager = new ConfigManager(getDataPath());\n loadConfigs();\n\n onEnable();\n\n this.bukkitAudiences = BukkitAudiences.create(this.plugin);\n\n getLogger().info(\"Starting tasks...\");\n startTasks();\n\n getLogger().info(\"Registering commands...\");\n this.commandManager = new CommandManager(this.plugin);\n registerCommands();\n\n getLogger().info(\"Registering listeners...\");\n registerListeners();\n\n this.protocolManager = ProtocolLibrary.getProtocolManager();\n }\n\n public abstract void onEnable();\n\n @Override\n public void disable() {\n onDisable();\n\n this.bukkitAudiences.close();\n }\n\n public abstract void onDisable();\n\n @Override\n public void registerCommands() {\n getCommands().forEach(command -> getCommandManager().registerCommand(command));\n }\n\n public abstract Set<Command> getCommands();\n\n @Override\n public void registerListeners() {\n ListenerRegistrar.register(this, getListeners());\n }\n\n public abstract Set<Class<?>> getListeners();\n\n @Override\n public Plugin getPlugin() {\n return this.plugin;\n }\n\n @Override\n public Path getDataPath() {\n return this.plugin.getDataFolder().toPath().toAbsolutePath();\n }\n\n @Override\n public Logger getLogger() {\n return this.plugin.getLogger();\n }\n\n @Override\n public ConfigManager getConfigManager() {\n return this.configManager;\n }\n\n @Override\n public CommandManager getCommandManager() {\n return this.commandManager;\n }\n\n @Override\n public BukkitAudiences getBukkitAudiences() {\n return this.bukkitAudiences;\n }\n\n @Override\n public ProtocolManager getProtocolManager() {\n return this.protocolManager;\n }\n}"
},
{
"identifier": "MovementControlTask",
"path": "src/main/java/dev/kafein/interactivenpcs/tasks/MovementControlTask.java",
"snippet": "public final class MovementControlTask implements Runnable {\n private final InteractiveNpcs plugin;\n\n public MovementControlTask(InteractiveNpcs plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void run() {\n/* Cache<UUID, Interaction> interactionCache = this.plugin.getInteractionManager().getInteractions();\n interactionCache.asMap().forEach((uuid, interact) -> {\n Player player = Bukkit.getPlayer(uuid);\n if (player == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n NpcProperties npcProperties = interact.getNpcProperties();\n\n InteractiveNpc interactiveNpc = this.plugin.getInteractionManager().getNpcs().getIfPresent(npcProperties.getId());\n if (interactiveNpc == null) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Focus focus = interactiveNpc.getFocus();\n Location playerLocation = player.getLocation().clone();\n if (playerLocation.distance(interact.getFirstLocation()) > focus.getMaxDistance()) {\n this.plugin.getInteractionManager().invalidate(uuid);\n return;\n }\n\n Location playerLastLocation = interact.getLastLocation();\n interact.setLastLocation(playerLocation);\n if (playerLocation.distance(playerLastLocation) > 0.1\n || playerLastLocation.getYaw() != playerLocation.getYaw()\n || playerLastLocation.getPitch() != playerLocation.getPitch()) {\n return;\n }\n\n if (player.hasMetadata(\"npc-interaction\")) {\n return;\n }\n\n Location npcEyeLocation = npcProperties.getEyeLocation().clone();\n Direction direction = new Direction(playerLocation);\n Direction targetDirection = new Direction(playerLocation, npcEyeLocation);\n\n if (!targetDirection.isNearly(direction)) {\n player.setMetadata(\"npc-interaction\", new FixedMetadataValue(this.plugin.getPlugin(), true));\n\n BukkitRunnable bukkitRunnable = new DirectionAdjuster(this.plugin.getPlugin(), player, targetDirection, focus.getSpeed());\n bukkitRunnable.runTaskTimer(this.plugin.getPlugin(), 0L, 1L);\n }\n });*/\n }\n}"
}
] | import com.google.common.collect.ImmutableSet;
import dev.kafein.interactivenpcs.command.Command;
import dev.kafein.interactivenpcs.commands.InteractionCommand;
import dev.kafein.interactivenpcs.compatibility.Compatibility;
import dev.kafein.interactivenpcs.compatibility.CompatibilityFactory;
import dev.kafein.interactivenpcs.compatibility.CompatibilityType;
import dev.kafein.interactivenpcs.configuration.Config;
import dev.kafein.interactivenpcs.configuration.ConfigVariables;
import dev.kafein.interactivenpcs.conversation.ConversationManager;
import dev.kafein.interactivenpcs.conversation.text.font.CharWidthMap;
import dev.kafein.interactivenpcs.plugin.AbstractBukkitPlugin;
import dev.kafein.interactivenpcs.tasks.MovementControlTask;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import java.util.Set; | 3,544 | package dev.kafein.interactivenpcs;
public final class InteractiveNpcs extends AbstractBukkitPlugin {
private ConversationManager conversationManager;
private CharWidthMap charWidthMap;
public InteractiveNpcs(Plugin plugin) {
super(plugin);
}
@Override
public void onLoad() {}
@Override
public void onEnable() {
this.charWidthMap = new CharWidthMap(this);
this.charWidthMap.initialize();
this.conversationManager = new ConversationManager(this);
this.conversationManager.initialize();
PluginManager pluginManager = Bukkit.getPluginManager();
for (CompatibilityType compatibilityType : CompatibilityType.values()) {
if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) {
continue;
}
Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this);
if (compatibility != null) {
compatibility.initialize();
}
}
}
@Override
public void onDisable() {
}
@Override
public Set<Command> getCommands() {
return ImmutableSet.of( | package dev.kafein.interactivenpcs;
public final class InteractiveNpcs extends AbstractBukkitPlugin {
private ConversationManager conversationManager;
private CharWidthMap charWidthMap;
public InteractiveNpcs(Plugin plugin) {
super(plugin);
}
@Override
public void onLoad() {}
@Override
public void onEnable() {
this.charWidthMap = new CharWidthMap(this);
this.charWidthMap.initialize();
this.conversationManager = new ConversationManager(this);
this.conversationManager.initialize();
PluginManager pluginManager = Bukkit.getPluginManager();
for (CompatibilityType compatibilityType : CompatibilityType.values()) {
if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) {
continue;
}
Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this);
if (compatibility != null) {
compatibility.initialize();
}
}
}
@Override
public void onDisable() {
}
@Override
public Set<Command> getCommands() {
return ImmutableSet.of( | new InteractionCommand(this) | 1 | 2023-11-18 10:12:16+00:00 | 4k |
ZhiQinIsZhen/dubbo-springboot3 | dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/provider/RemoteStaffRoleServiceImpl.java | [
{
"identifier": "BeanUtil",
"path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java",
"snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier) {\n return copyProperties(source, targetSupplier, null);\n }\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标对象\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> T copyProperties(S source, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(source)) {\n return null;\n }\n T target = targetSupplier.get();\n BeanUtils.copyProperties(source, target);\n if (Objects.nonNull(ext)) {\n ext.accept(source, target);\n }\n return target;\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier) {\n return copyList(sources, targetSupplier, null);\n }\n\n /**\n * 数组对象拷贝\n *\n * @param sources 原数组\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标数组\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> List<T> copyList(List<S> sources, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (CollectionUtils.isEmpty(sources)) {\n return List.of();\n }\n return sources\n .stream()\n .map(source -> copyProperties(source, targetSupplier, ext))\n .collect(Collectors.toList());\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier) {\n return copyRemotePage(pageSource, targetSupplier, null);\n }\n\n /**\n * 分页对象拷贝\n *\n * @param pageSource 原对象\n * @param targetSupplier 目标对象\n * @param ext 目标对象函数接口\n * @return 目标分页\n * @param <S> 原对象泛型\n * @param <T> 目标对象泛型\n */\n public static <S, T> RemotePage<T> copyRemotePage(RemotePage<S> pageSource, Supplier<T> targetSupplier, BiConsumer<S, T> ext) {\n if (Objects.isNull(pageSource)) {\n return RemotePage.of();\n }\n return new RemotePage<>(\n copyList(pageSource.getList(), targetSupplier, ext),\n pageSource.getTotal(),\n pageSource.getPageNum(),\n pageSource.getPageSize()\n );\n }\n}"
},
{
"identifier": "StaffRoleBO",
"path": "dubbo-service/dubbo-service-staff/staff-remote/src/main/java/com/liyz/boot3/service/staff/bo/StaffRoleBO.java",
"snippet": "@Getter\n@Setter\npublic class StaffRoleBO implements Serializable {\n @Serial\n private static final long serialVersionUID = -5019855188001537438L;\n\n /**\n * 员工ID\n */\n private Long staffId;\n\n /**\n * 角色ID\n */\n private Integer roleId;\n}"
},
{
"identifier": "StaffRoleDO",
"path": "dubbo-service/dubbo-service-staff/staff-dao/src/main/java/com/liyz/boot3/service/staff/model/StaffRoleDO.java",
"snippet": "@Getter\n@Setter\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(\"staff_role\")\npublic class StaffRoleDO extends BaseDO implements Serializable {\n @Serial\n private static final long serialVersionUID = -1600563077499546530L;\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n private Long staffId;\n\n /**\n * 角色ID\n */\n private Integer roleId;\n\n}"
},
{
"identifier": "RemoteStaffRoleService",
"path": "dubbo-service/dubbo-service-staff/staff-remote/src/main/java/com/liyz/boot3/service/staff/remote/RemoteStaffRoleService.java",
"snippet": "public interface RemoteStaffRoleService {\n\n /**\n * 给员工绑定一个角色\n *\n * @param staffRoleBO 员工角色参数\n * @return 员工角色\n */\n StaffRoleBO bindRole(@NotNull StaffRoleBO staffRoleBO);\n\n /**\n * 查询员工拥有的角色\n *\n * @param staffId 员工ID\n * @return 员工角色\n */\n List<StaffRoleBO> listByStaffId(@NotNull Long staffId);\n}"
},
{
"identifier": "StaffRoleService",
"path": "dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/service/StaffRoleService.java",
"snippet": "public interface StaffRoleService extends IService<StaffRoleDO> {\n}"
}
] | import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liyz.boot3.common.service.util.BeanUtil;
import com.liyz.boot3.service.staff.bo.StaffRoleBO;
import com.liyz.boot3.service.staff.model.StaffRoleDO;
import com.liyz.boot3.service.staff.remote.RemoteStaffRoleService;
import com.liyz.boot3.service.staff.service.StaffRoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List; | 1,823 | package com.liyz.boot3.service.staff.provider;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/3/13 13:44
*/
@DubboService
public class RemoteStaffRoleServiceImpl implements RemoteStaffRoleService {
@Resource
private StaffRoleService staffRoleService;
/**
* 给员工绑定一个角色
*
* @param staffRoleBO 员工角色参数
* @return 员工角色
*/
@Override
@Transactional(rollbackFor = Exception.class)
public StaffRoleBO bindRole(StaffRoleBO staffRoleBO) { | package com.liyz.boot3.service.staff.provider;
/**
* Desc:
*
* @author lyz
* @version 1.0.0
* @date 2023/3/13 13:44
*/
@DubboService
public class RemoteStaffRoleServiceImpl implements RemoteStaffRoleService {
@Resource
private StaffRoleService staffRoleService;
/**
* 给员工绑定一个角色
*
* @param staffRoleBO 员工角色参数
* @return 员工角色
*/
@Override
@Transactional(rollbackFor = Exception.class)
public StaffRoleBO bindRole(StaffRoleBO staffRoleBO) { | staffRoleService.save(BeanUtil.copyProperties(staffRoleBO, StaffRoleDO::new)); | 0 | 2023-11-13 01:28:21+00:00 | 4k |
glowingstone124/QAPI3 | src/main/java/org/qo/UserProcess.java | [
{
"identifier": "AvatarCache",
"path": "src/main/java/org/qo/server/AvatarCache.java",
"snippet": "public class AvatarCache {\n public static final String CachePath = \"avatars/\";\n public static void init() throws IOException {\n if (!Files.exists(Path.of(CachePath))){\n Files.createDirectory(Path.of(CachePath));\n }\n }\n public static boolean has(String name){\n return Files.exists(Path.of(CachePath + name + \".png\"));\n }\n public static void cache(String url, String name) throws Exception{\n Request.Download(url,CachePath + name);\n }\n}"
},
{
"identifier": "LogLevel",
"path": "src/main/java/org/qo/Logger.java",
"snippet": "public enum LogLevel {\n INFO, WARNING, ERROR, UNKNOWN\n}"
},
{
"identifier": "hashSHA256",
"path": "src/main/java/org/qo/Algorithm.java",
"snippet": "public static String hashSHA256(String input) {\n try {\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));\n\n StringBuilder hexString = new StringBuilder();\n for (byte hashByte : hashBytes) {\n String hex = Integer.toHexString(0xff & hashByte);\n if (hex.length() == 1) hexString.append('0');\n hexString.append(hex);\n }\n\n return hexString.toString();\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n return null;\n }\n}"
}
] | import jakarta.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.qo.server.AvatarCache;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;
import java.util.Calendar;
import java.util.Objects;
import static org.qo.Logger.LogLevel.*;
import static org.qo.Algorithm.hashSHA256; | 2,419 | result.put("error", e.getMessage());
}
return result;
}
public static boolean SQLAvliable() {
boolean success = true;
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){
} catch (SQLException e){
success = false;
}
return success;
}
public static boolean queryForum(String username) throws Exception {
boolean resultExists = false;
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {
String selectQuery = "SELECT * FROM forum WHERE username = ?";
Logger.log(selectQuery, INFO);
try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {
preparedStatement.setString(1, username);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
resultExists = resultSet.next();
}
}
}
return resultExists;
}
public static String queryHash(String hash) throws Exception {
String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8);
JSONObject codeObject = new JSONObject(jsonContent);
if (codeObject.has(hash)) {
String username = codeObject.getString(hash);
String finalOutput = username;
// codeObject.remove(hash);
Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8));
System.out.println(username);
return finalOutput;
} else {
System.out.println("mismatched");
return null;
}
}
public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception {
String ArticleSheet;
switch (ArticleSheets){
case 0:
ArticleSheet = "serverArticles";
break;
case 1:
ArticleSheet = "commandArticles";
break;
case 2:
ArticleSheet = "attractionsArticles";
break;
case 3:
ArticleSheet = "noticeArticles";
break;
default:
ArticleSheet = null;
break;
}
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {
String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {
preparedStatement.setInt(1, ArticleID);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
String resultName = resultSet.getString("Name");
return resultName;
} else {
return null;
}
}
}
}
}
public static String queryReg(String name) throws Exception{
try {
Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Long uid = resultSet.getLong("uid");
Boolean frozen = resultSet.getBoolean("frozen");
int eco = resultSet.getInt("economy");
JSONObject responseJson = new JSONObject();
responseJson.put("code", 0);
responseJson.put("frozen", frozen);
responseJson.put("qq", uid);
responseJson.put("economy", eco);
return responseJson.toString();
}
resultSet.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject responseJson = new JSONObject();
responseJson.put("code", 1);
responseJson.put("qq", -1);
return responseJson.toString();
}
public static void regforum(String username, String password) throws Exception{
// 解析JSON数据为JSONArray
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的
int day = calendar.get(Calendar.DAY_OF_MONTH);
String date = year + "-" + month + "-" + day; | package org.qo;
public class UserProcess {
public static final String CODE = "users/recoverycode/index.json";
private static final String FILE_PATH = "usermap.json";
private static final String SERVER_FILE_PATH = "playermap.json";
public static final String SQL_CONFIGURATION = "data/sql/info.json";
public static String jdbcUrl = getDatabaseInfo("url");
public static String sqlusername = getDatabaseInfo("username");
public static String sqlpassword = getDatabaseInfo("password");
public static String firstLoginSearch(String name, HttpServletRequest request) {
try {
Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);
String query = "SELECT * FROM forum WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Boolean first = resultSet.getBoolean("firstLogin");
JSONObject responseJson = new JSONObject();
responseJson.put("code", 0);
responseJson.put("first", first);
resultSet.close();
preparedStatement.close();
return responseJson.toString();
}
String updateQuery = "UPDATE forum SET firstLogin = ? WHERE username = ?";
PreparedStatement apreparedStatement = connection.prepareStatement(updateQuery);
apreparedStatement.setBoolean(1, false);
apreparedStatement.setString(2, name);
Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin.", INFO);
int rowsAffected = apreparedStatement.executeUpdate();
apreparedStatement.close();
connection.close();
resultSet.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject responseJson = new JSONObject();
responseJson.put("code", 1);
responseJson.put("first", -1);
Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin but unsuccessful.", INFO);
return responseJson.toString();
}
public static String fetchMyinfo(String name, HttpServletRequest request) throws Exception {
String date;
Boolean premium;
Boolean donate;
if (name.isEmpty()) {
}
try {
Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);
String query = "SELECT * FROM forum WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
date = resultSet.getString("date");
premium = resultSet.getBoolean("premium");
donate = resultSet.getBoolean("donate");
String linkto = resultSet.getString("linkto");
JSONObject responseJson = new JSONObject();
responseJson.put("date", date);
responseJson.put("premium", premium);
responseJson.put("donate", donate);
responseJson.put("code", 0);
responseJson.put("linkto", linkto);
responseJson.put("username", name);
Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo.", INFO);
return responseJson.toString();
} else {
// No rows found for the given username
JSONObject responseJson = new JSONObject();
responseJson.put("code", -1);
Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo, but unsuccessful.", INFO);
return responseJson.toString();
}
} catch (SQLException e) {
e.printStackTrace();
JSONObject responseJson = new JSONObject();
Logger.log("username " + name + " qureied myinfo, but unsuccessful.", INFO);
responseJson.put("code", -1);
return responseJson.toString();
}
}
public static String getDatabaseInfo(String type) {
JSONObject sqlObject = null;
try {
sqlObject = new JSONObject(Files.readString(Path.of(SQL_CONFIGURATION)));
} catch (IOException e) {
Logger.log("ERROR: SQL CONFIG NOT FOUND",ERROR);
}
switch (type){
case "password":
return sqlObject.getString("password");
case "username":
return sqlObject.getString("username");
case "url":
return sqlObject.getString("url");
default:
return null;
}
}
public static void handleTime(String name, int time){
try {
Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);
String query = "INSERT INTO timeTables (name, time) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, time);
preparedStatement.executeUpdate();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static JSONObject getTime(String username) {
JSONObject result = null;
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {
result = new JSONObject();
String query = "SELECT * FROM timeTables WHERE name = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, username);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
int time = resultSet.getInt("time");
result.put("name", username);
result.put("time", time);
} else {
result.put("error", -1);
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
result.put("error", e.getMessage());
}
return result;
}
public static boolean SQLAvliable() {
boolean success = true;
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){
} catch (SQLException e){
success = false;
}
return success;
}
public static boolean queryForum(String username) throws Exception {
boolean resultExists = false;
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {
String selectQuery = "SELECT * FROM forum WHERE username = ?";
Logger.log(selectQuery, INFO);
try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {
preparedStatement.setString(1, username);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
resultExists = resultSet.next();
}
}
}
return resultExists;
}
public static String queryHash(String hash) throws Exception {
String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8);
JSONObject codeObject = new JSONObject(jsonContent);
if (codeObject.has(hash)) {
String username = codeObject.getString(hash);
String finalOutput = username;
// codeObject.remove(hash);
Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8));
System.out.println(username);
return finalOutput;
} else {
System.out.println("mismatched");
return null;
}
}
public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception {
String ArticleSheet;
switch (ArticleSheets){
case 0:
ArticleSheet = "serverArticles";
break;
case 1:
ArticleSheet = "commandArticles";
break;
case 2:
ArticleSheet = "attractionsArticles";
break;
case 3:
ArticleSheet = "noticeArticles";
break;
default:
ArticleSheet = null;
break;
}
try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) {
String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?";
try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) {
preparedStatement.setInt(1, ArticleID);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
String resultName = resultSet.getString("Name");
return resultName;
} else {
return null;
}
}
}
}
}
public static String queryReg(String name) throws Exception{
try {
Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword);
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
Long uid = resultSet.getLong("uid");
Boolean frozen = resultSet.getBoolean("frozen");
int eco = resultSet.getInt("economy");
JSONObject responseJson = new JSONObject();
responseJson.put("code", 0);
responseJson.put("frozen", frozen);
responseJson.put("qq", uid);
responseJson.put("economy", eco);
return responseJson.toString();
}
resultSet.close();
preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject responseJson = new JSONObject();
responseJson.put("code", 1);
responseJson.put("qq", -1);
return responseJson.toString();
}
public static void regforum(String username, String password) throws Exception{
// 解析JSON数据为JSONArray
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的
int day = calendar.get(Calendar.DAY_OF_MONTH);
String date = year + "-" + month + "-" + day; | String EncryptedPswd = hashSHA256(password); | 2 | 2023-11-15 13:38:53+00:00 | 4k |
RaniAgus/java-docker-tutorial | src/main/java/io/github/raniagus/example/Application.java | [
{
"identifier": "Bootstrap",
"path": "src/main/java/io/github/raniagus/example/bootstrap/Bootstrap.java",
"snippet": "public class Bootstrap implements Runnable, WithSimplePersistenceUnit {\n private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);\n\n public static void main(String[] args) {\n Application.startDatabaseConnection();\n new Bootstrap().run();\n }\n\n @Override\n public void run() {\n log.info(\"Iniciando reinicio de base de datos...\");\n try (var reader = new CsvReader<>(UserDto.class, \"/data/users.csv\")){\n var users = reader.readAll().stream().map(UserDto::toEntity).toList();\n\n withTransaction(() -> {\n RepositorioDeUsuarios.INSTANCE.eliminarTodos();\n users.forEach(RepositorioDeUsuarios.INSTANCE::guardar);\n });\n\n users.forEach(user -> log.info(\"Usuario insertado: {}\", user));\n }\n }\n}"
},
{
"identifier": "Routes",
"path": "src/main/java/io/github/raniagus/example/constants/Routes.java",
"snippet": "public abstract class Routes {\n public static final String HOME = \"/\";\n public static final String LOGIN = \"/login\";\n public static final String LOGOUT = \"/logout\";\n\n private Routes() {}\n}"
},
{
"identifier": "ErrorController",
"path": "src/main/java/io/github/raniagus/example/controller/ErrorController.java",
"snippet": "public enum ErrorController {\n INSTANCE;\n\n public void handleShouldLogin(Context ctx) {\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, ctx.path())\n ));\n }\n\n public void handleNotFound(Context ctx) {\n new ErrorView(\"404\", \"No pudimos encontrar la página que estabas buscando.\").render(ctx);\n }\n\n public void handleError(Context ctx) {\n new ErrorView(\"¡Oops!\", \"Algo salió mal. Vuelve a intentarlo más tarde.\").render(ctx);\n }\n}"
},
{
"identifier": "HomeController",
"path": "src/main/java/io/github/raniagus/example/controller/HomeController.java",
"snippet": "public enum HomeController {\n INSTANCE;\n\n public void renderHome(Context ctx) {\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n new HomeView(usuario.getNombre(), usuario.getApellido()).render(ctx);\n }\n}"
},
{
"identifier": "LoginController",
"path": "src/main/java/io/github/raniagus/example/controller/LoginController.java",
"snippet": "public enum LoginController {\n INSTANCE;\n\n public void handleSession(Context ctx) {\n if (ctx.routeRoles().isEmpty()) {\n return;\n }\n\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n if (usuario == null) {\n throw new ShouldLoginException();\n } else if (!ctx.routeRoles().contains(usuario.getRol())) {\n throw new UserNotAuthorizedException();\n }\n }\n\n public void renderLogin(Context ctx) {\n var email = ctx.queryParamAsClass(Params.EMAIL, String.class).getOrDefault(\"\");\n var origin = ctx.queryParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n var errors = ctx.queryParamAsClass(Params.ERRORS, String.class).getOrDefault(\"\");\n\n if (ctx.sessionAttribute(Session.USER) != null) {\n ctx.redirect(origin);\n return;\n }\n\n new LoginView(email, origin, errors.isEmpty() ? Set.of() : Set.of(errors.split(\",\"))).render(ctx);\n }\n\n public void performLogin(Context ctx) {\n var email = ctx.formParamAsClass(Params.EMAIL, String.class)\n .check(s -> s.matches(\".+@.+\\\\..+\"), \"INVALID_EMAIL\");\n var password = ctx.formParamAsClass(Params.PASSWORD, String.class)\n .check(s -> s.length() >= 8, \"INVALID_PASSWORD\");\n var origin = ctx.formParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n\n try {\n RepositorioDeUsuarios.INSTANCE.buscarPorEmail(email.get())\n .filter(u -> u.getPassword().matches(password.get()))\n .ifPresentOrElse(usuario -> {\n ctx.sessionAttribute(Session.USER, usuario);\n ctx.redirect(origin);\n }, () ->\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.get()),\n HtmlUtil.encode(Params.ERRORS, String.join(\",\", Params.EMAIL, Params.PASSWORD))\n ))\n );\n } catch (ValidationException e) {\n var errors = Validation.collectErrors(email, password);\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.errors().isEmpty() ? email.get() : \"\"),\n HtmlUtil.encode(Params.ERRORS, errors.keySet())\n ));\n }\n }\n\n public void performLogout(Context ctx) {\n ctx.consumeSessionAttribute(Session.USER);\n ctx.redirect(Routes.HOME);\n }\n}"
},
{
"identifier": "ShouldLoginException",
"path": "src/main/java/io/github/raniagus/example/exception/ShouldLoginException.java",
"snippet": "public class ShouldLoginException extends RuntimeException {\n}"
},
{
"identifier": "UserNotAuthorizedException",
"path": "src/main/java/io/github/raniagus/example/exception/UserNotAuthorizedException.java",
"snippet": "public class UserNotAuthorizedException extends RuntimeException {\n}"
},
{
"identifier": "Rol",
"path": "src/main/java/io/github/raniagus/example/model/Rol.java",
"snippet": "public enum Rol implements RouteRole {\n ADMIN,\n USER\n}"
}
] | import gg.jte.ContentType;
import gg.jte.TemplateEngine;
import gg.jte.output.StringOutput;
import gg.jte.resolve.DirectoryCodeResolver;
import io.github.flbulgarelli.jpa.extras.simple.WithSimplePersistenceUnit;
import io.github.raniagus.example.bootstrap.Bootstrap;
import io.github.raniagus.example.constants.Routes;
import io.github.raniagus.example.controller.ErrorController;
import io.github.raniagus.example.controller.HomeController;
import io.github.raniagus.example.controller.LoginController;
import io.github.raniagus.example.exception.ShouldLoginException;
import io.github.raniagus.example.exception.UserNotAuthorizedException;
import io.github.raniagus.example.model.Rol;
import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import java.nio.file.Path;
import java.time.LocalDate; | 1,670 | package io.github.raniagus.example;
public class Application {
public static final Config config = Config.create();
public static void main(String[] args) {
startDatabaseConnection();
if (config.databaseHbm2ddlAuto().equals("create-drop")) {
new Bootstrap().run();
}
startServer();
}
public static void startDatabaseConnection() {
WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties()));
WithSimplePersistenceUnit.dispose();
}
@SuppressWarnings("java:S2095")
public static void startServer() {
var app = Javalin.create(config -> {
var templateEngine = createTemplateEngine();
config.fileRenderer((filePath, model, ctx) -> {
var output = new StringOutput();
templateEngine.render(filePath, model.get("view"), output);
return output.toString();
});
config.staticFiles.add("public", Location.CLASSPATH);
config.validation.register(LocalDate.class, LocalDate::parse);
});
app.beforeMatched(LoginController.INSTANCE::handleSession);
app.get(Routes.HOME, HomeController.INSTANCE::renderHome, Rol.USER, Rol.ADMIN);
app.get(Routes.LOGIN, LoginController.INSTANCE::renderLogin);
app.post(Routes.LOGIN, LoginController.INSTANCE::performLogin);
app.post(Routes.LOGOUT, LoginController.INSTANCE::performLogout);
| package io.github.raniagus.example;
public class Application {
public static final Config config = Config.create();
public static void main(String[] args) {
startDatabaseConnection();
if (config.databaseHbm2ddlAuto().equals("create-drop")) {
new Bootstrap().run();
}
startServer();
}
public static void startDatabaseConnection() {
WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties()));
WithSimplePersistenceUnit.dispose();
}
@SuppressWarnings("java:S2095")
public static void startServer() {
var app = Javalin.create(config -> {
var templateEngine = createTemplateEngine();
config.fileRenderer((filePath, model, ctx) -> {
var output = new StringOutput();
templateEngine.render(filePath, model.get("view"), output);
return output.toString();
});
config.staticFiles.add("public", Location.CLASSPATH);
config.validation.register(LocalDate.class, LocalDate::parse);
});
app.beforeMatched(LoginController.INSTANCE::handleSession);
app.get(Routes.HOME, HomeController.INSTANCE::renderHome, Rol.USER, Rol.ADMIN);
app.get(Routes.LOGIN, LoginController.INSTANCE::renderLogin);
app.post(Routes.LOGIN, LoginController.INSTANCE::performLogin);
app.post(Routes.LOGOUT, LoginController.INSTANCE::performLogout);
| app.exception(ShouldLoginException.class, (e, ctx) -> ErrorController.INSTANCE.handleShouldLogin(ctx)); | 2 | 2023-11-12 15:14:24+00:00 | 4k |
innogames/flink-real-time-crm-ui | src/main/java/com/innogames/analytics/rtcrmui/controller/IndexController.java | [
{
"identifier": "Campaign",
"path": "src/main/java/com/innogames/analytics/rtcrmui/entity/Campaign.java",
"snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Campaign {\n\n\tprivate int campaignId;\n\tprivate boolean enabled;\n\tprivate String game;\n\tprivate String eventName;\n\tprivate String startDate;\n\tprivate String endDate;\n\tprivate String filter;\n\n\tpublic Campaign() {\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn enabled;\n\t}\n\n\tpublic void setEnabled(final boolean enabled) {\n\t\tthis.enabled = enabled;\n\t}\n\n\tpublic int getCampaignId() {\n\t\treturn campaignId;\n\t}\n\n\tpublic void setCampaignId(final int campaignId) {\n\t\tthis.campaignId = campaignId;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tpublic void setStartDate(final String startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\tpublic String getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tpublic void setEndDate(final String endDate) {\n\t\tthis.endDate = endDate;\n\t}\n\n\tpublic String getFilter() {\n\t\treturn filter;\n\t}\n\n\tpublic void setFilter(final String filter) {\n\t\tthis.filter = filter;\n\t}\n\n}"
},
{
"identifier": "TrackingEvent",
"path": "src/main/java/com/innogames/analytics/rtcrmui/entity/TrackingEvent.java",
"snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class TrackingEvent {\n\n\tprivate String schemaVersion;\n\tprivate String eventId;\n\tprivate String systemType;\n\tprivate String systemName;\n\tprivate String game;\n\tprivate String market;\n\tprivate Integer playerId;\n\tprivate String eventType;\n\tprivate String eventName;\n\tprivate String eventScope;\n\tprivate String createdAt;\n\tprivate String receivedAt;\n\tprivate String hostname;\n\n\tprivate Map<String, Object> context;\n\n\tprivate Map<String, Object> data;\n\n\tpublic TrackingEvent() {\n\t}\n\n\tpublic String getSchemaVersion() {\n\t\treturn schemaVersion;\n\t}\n\n\tpublic void setSchemaVersion(final String schemaVersion) {\n\t\tthis.schemaVersion = schemaVersion;\n\t}\n\n\tpublic String getEventId() {\n\t\treturn eventId;\n\t}\n\n\tpublic void setEventId(final String eventId) {\n\t\tthis.eventId = eventId;\n\t}\n\n\tpublic String getSystemType() {\n\t\treturn systemType;\n\t}\n\n\tpublic void setSystemType(final String systemType) {\n\t\tthis.systemType = systemType;\n\t}\n\n\tpublic String getSystemName() {\n\t\treturn systemName;\n\t}\n\n\tpublic void setSystemName(final String systemName) {\n\t\tthis.systemName = systemName;\n\t}\n\n\tpublic String getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(final String game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic String getMarket() {\n\t\treturn market;\n\t}\n\n\tpublic void setMarket(final String market) {\n\t\tthis.market = market;\n\t}\n\n\tpublic Integer getPlayerId() {\n\t\treturn playerId;\n\t}\n\n\tpublic void setPlayerId(final Integer playerId) {\n\t\tthis.playerId = playerId;\n\t}\n\n\tpublic String getEventType() {\n\t\treturn eventType;\n\t}\n\n\tpublic void setEventType(final String eventType) {\n\t\tthis.eventType = eventType;\n\t}\n\n\tpublic String getEventName() {\n\t\treturn eventName;\n\t}\n\n\tpublic void setEventName(final String eventName) {\n\t\tthis.eventName = eventName;\n\t}\n\n\tpublic String getEventScope() {\n\t\treturn eventScope;\n\t}\n\n\tpublic void setEventScope(final String eventScope) {\n\t\tthis.eventScope = eventScope;\n\t}\n\n\tpublic String getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(final String createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic String getReceivedAt() {\n\t\treturn receivedAt;\n\t}\n\n\tpublic void setReceivedAt(final String receivedAt) {\n\t\tthis.receivedAt = receivedAt;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic void setHostname(final String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\tpublic Map<String, Object> getContext() {\n\t\treturn context;\n\t}\n\n\tpublic void setContext(final Map<String, Object> context) {\n\t\tthis.context = context;\n\t}\n\n\tpublic Map<String, Object> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(final Map<String, Object> data) {\n\t\tthis.data = data;\n\t}\n\n}"
},
{
"identifier": "StringProducer",
"path": "src/main/java/com/innogames/analytics/rtcrmui/kafka/StringProducer.java",
"snippet": "@Component\npublic class StringProducer {\n\n\tprivate final Properties properties;\n\tprivate Producer<String, String> producer;\n\n\tpublic StringProducer(@Value(\"${spring.kafka.bootstrap-servers}\") final String kafkaBootstrapServers) {\n\t\tthis.properties = new Properties();\n\n\t\tthis.properties.put(\"bootstrap.servers\", kafkaBootstrapServers);\n\t\tthis.properties.put(\"acks\", \"all\");\n\t\tthis.properties.put(\"buffer.memory\", 33554432);\n\t\tthis.properties.put(\"compression.type\", \"snappy\");\n\t\tthis.properties.put(\"retries\", 3);\n\t\tthis.properties.put(\"batch.size\", 16384);\n\t\tthis.properties.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\t\tthis.properties.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n\n\t\tthis.producer = new KafkaProducer<>(this.properties);\n\t}\n\n\t@PreDestroy\n\tpublic void destroy() {\n\t\tthis.flush();\n\t\tthis.producer.close();\n\t}\n\n\tpublic void flush() {\n\t\tthis.producer.flush();\n\t}\n\n\tpublic Future<RecordMetadata> send(ProducerRecord<String, String> record) {\n\t\treturn this.producer.send(record);\n\t}\n\n\tpublic Future<RecordMetadata> send(String topic, String message) {\n\t\treturn this.send(new ProducerRecord<>(topic, message));\n\t}\n\n}"
}
] | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.innogames.analytics.rtcrmui.entity.Campaign;
import com.innogames.analytics.rtcrmui.entity.TrackingEvent;
import com.innogames.analytics.rtcrmui.kafka.StringProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.view.RedirectView; | 1,869 | package com.innogames.analytics.rtcrmui.controller;
@Controller
public class IndexController {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private StringProducer stringProducer;
@Autowired
private SimpMessagingTemplate template;
@GetMapping("/")
public String home(final Model model) {
model.addAttribute("module", "index");
return "index";
}
@PostMapping("/event")
public RedirectView sendEvent(@RequestBody final String eventJson) {
try { | package com.innogames.analytics.rtcrmui.controller;
@Controller
public class IndexController {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private StringProducer stringProducer;
@Autowired
private SimpMessagingTemplate template;
@GetMapping("/")
public String home(final Model model) {
model.addAttribute("module", "index");
return "index";
}
@PostMapping("/event")
public RedirectView sendEvent(@RequestBody final String eventJson) {
try { | final TrackingEvent trackingEvent = objectMapper.readValue(eventJson, TrackingEvent.class); | 1 | 2023-11-12 18:07:20+00:00 | 4k |
heldermartins4/RPG_Pokemon | src/main/java/interfaces/GamePanel.java | [
{
"identifier": "KeyHandler",
"path": "src/main/java/controllers/controls/KeyHandler.java",
"snippet": "public class KeyHandler implements KeyListener {\n\n public boolean up, down, left, right;\n\n public KeyHandler() {\n up = down = left = right = false;\n }\n\n @Override\n public void keyTyped(KeyEvent e) {\n \n // char keyChar = e.getKeyChar();\n // System.out.println(\"Key Typed: \" + keyChar);\n } \n\n @Override\n public void keyPressed(KeyEvent e) {\n\n int code = e.getKeyCode();\n\n switch (code) {\n case KeyEvent.VK_W:\n up = true;\n break;\n case KeyEvent.VK_A:\n left = true;\n break;\n case KeyEvent.VK_S:\n down = true;\n break;\n case KeyEvent.VK_D:\n right = true;\n break;\n \n default:\n break;\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n\n int code = e.getKeyCode();\n\n switch (code) {\n case KeyEvent.VK_W:\n up = false;\n break;\n case KeyEvent.VK_A:\n left = false;\n break;\n case KeyEvent.VK_S:\n down = false;\n break;\n case KeyEvent.VK_D:\n right = false;\n break;\n \n default:\n break;\n }\n }\n}"
},
{
"identifier": "Player",
"path": "src/main/java/controllers/entity/Player.java",
"snippet": "public class Player extends Entity {\n\n GamePanel gp;\n KeyHandler key;\n Map map;\n Start start_panel;\n\n Sprites[] player_sprite;\n Sprites player_direction = new Sprites();\n\n // private int player_sprites_amount;\n // private int player_direction_indexes;\n // private String player_sprites_path;\n\n int sprite_timer = 0;\n\n int next_x, next_y;\n\n private boolean is_walking = false;\n\n public Player(GamePanel gp, KeyHandler key) {\n\n this.gp = gp;\n this.key = key;\n this.start_panel = gp.getStartPanel();\n\n // this.player_sprites_amount = 12;\n // this.player_direction_indexes = 3;\n\n player_sprite = new Sprites[12]; // inicializa o array\n\n getImagePlayer(this.start_panel.getPlayer().getCharater());\n }\n\n public void setDefaultValues(int x, int y, int width, int height, int speed) {\n \n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n this.speed = speed;\n this.sprite = 3;\n \n this.sprite_counting = 0;\n \n // define a limiter for the next position\n this.next_x = x;\n this.next_y = y;\n player_direction.direction = \"down\";\n \n // Define a posição inicial aleatória\n // setRandomInitialPosition();\n }\n\n public void setMapToPlayer(Map map) {\n this.map = map;\n }\n\n public void getImagePlayer(String player_chosen) {\n\n final String relative_path = player_chosen; // path to the image folder\n\n try {\n for (int i = 0; i < 12; i++) {\n\n player_sprite[i] = new Sprites(); // initialize each element\n\n if (i < 3)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/u\" + (i + 1) + \".png\"));\n else if (i < 6)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/d\" + (i - 2) + \".png\"));\n else if (i < 9)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/l\" + (i - 5) + \".png\"));\n else if (i < 12)\n player_sprite[i].sprite_img = ImageIO.read(getClass().getResource(relative_path + \"/r\" + (i - 8) + \".png\"));\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public void setRandomInitialPosition() {\n // Loop até encontrar uma posição válida\n do {\n // Gere coordenadas aleatórias\n int randomX = (int) (Math.random() * map.map_x);\n int randomY = (int) (Math.random() * map.map_y);\n \n // Converta as coordenadas do array para as coordenadas do mapa\n int mapX = randomX * map.tile_size;\n int mapY = randomY * map.tile_size;\n \n // Verifique se a posição é válida\n if (isValidPosition(mapX, mapY)) {\n // Defina a posição do jogador\n setDefaultValues(mapX, mapY, map.tile_size, map.tile_size, speed);\n return;\n }\n // Se a posição não for válida, tente novamente\n } while (true);\n }\n \n private boolean isValidPosition(int x, int y) {\n // Converte as coordenadas do mapa para as coordenadas do array\n int arrayX = x / map.tile_size;\n int arrayY = y / map.tile_size;\n \n // Verifica se as coordenadas estão dentro dos limites do mapa\n if (arrayX >= 0 && arrayX < map.map_x && arrayY >= 0 && arrayY < map.map_y) {\n // Verifica se a célula correspondente no mapa não é colisiva\n return map.map_data[arrayX][arrayY] == 0;\n }\n \n // Se as coordenadas estão fora dos limites do mapa, considera como posição inválida\n return false;\n }\n\n public void update() {\n\n if (!is_walking) {\n if (key.up) {\n\n next_y = y - map.tile_size;\n player_direction.direction = \"up\";\n is_walking = true;\n\n } else if (key.down) {\n\n next_y = y + map.tile_size;\n player_direction.direction = \"down\";\n is_walking = true;\n\n } else if (key.left) {\n\n next_x = x - map.tile_size;\n player_direction.direction = \"left\";\n is_walking = true;\n\n } else if (key.right) {\n\n next_x = x + map.tile_size;\n player_direction.direction = \"right\";\n is_walking = true;\n\n }\n\n this.sprite_counting = 0;\n } else {\n \n if (isValidMove(next_x, next_y)) {\n if (y != next_y) {\n y += speed * Integer.signum(next_y - y);\n }\n else if (x != next_x) {\n x += speed * Integer.signum(next_x - x);\n }\n else if (x == next_x && y == next_y) {\n is_walking = false;\n }\n\n if (sprite_timer >= sprite) { // Ajuste o valor 10 conforme necessário para definir a velocidade da animação\n this.sprite_counting++;\n if (this.sprite_counting >= this.sprite) {\n this.sprite_counting = 0;\n }\n sprite_timer = 0;\n } else {\n sprite_timer++;\n }\n } else {\n is_walking = false;\n if (player_direction.direction == \"up\") {\n next_y = y;\n } else if (player_direction.direction == \"down\") {\n next_y = y;\n } else if (player_direction.direction == \"left\") {\n next_x = x;\n } else if (player_direction.direction == \"right\") {\n next_x = x;\n }\n }\n }\n }\n\n private boolean isValidMove(int nextX, int nextY) {\n // Converte as coordenadas do mapa para as coordenadas do array\n int arrayX = nextX / map.tile_size;\n int arrayY = nextY / map.tile_size;\n \n // Verifica se as coordenadas estão dentro dos limites do mapa\n if (arrayX >= 0 && arrayX < map.map_x && arrayY >= 0 && arrayY < map.map_y) {\n // Verifica se a célula correspondente no mapa não é colisiva\n return map.map_data[arrayX][arrayY] == 0;\n }\n \n // Se as coordenadas estão fora dos limites do mapa, considera como movimento inválido\n return false;\n }\n\n public void draw(Graphics2D g2d) {\n\n // g2d.setColor(java.awt.Color.white);\n // g2d.fillRect(x, y, map.tile_size, map.tile_size);\n\n BufferedImage img = null; // set default image\n\n // set image based on direction\n switch (player_direction.direction) {\n case \"up\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[0].sprite_img;\n break;\n case 1:\n img = player_sprite[1].sprite_img;\n break;\n case 2:\n img = player_sprite[2].sprite_img;\n break;\n }\n break;\n case \"down\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[3].sprite_img;\n break;\n case 1:\n img = player_sprite[4].sprite_img;\n break;\n case 2:\n img = player_sprite[5].sprite_img;\n break;\n }\n break;\n case \"left\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[6].sprite_img;\n break;\n case 1:\n img = player_sprite[7].sprite_img;\n break;\n case 2:\n img = player_sprite[8].sprite_img;\n break;\n }\n break;\n case \"right\":\n switch (this.sprite_counting) {\n case 0:\n img = player_sprite[9].sprite_img;\n break;\n case 1:\n img = player_sprite[10].sprite_img;\n break;\n case 2:\n img = player_sprite[11].sprite_img;\n break;\n }\n break;\n }\n\n g2d.drawImage(img, x, y, map.tile_size, map.tile_size, null);\n }\n}"
},
{
"identifier": "Map",
"path": "src/main/java/interfaces/map/Map.java",
"snippet": "public class Map extends MapDataManager {\n\n TileManager tm;\n\n final int scale = 3;\n\n public int max_screen_col = 16;\n public int max_screen_row = 12;\n\n private int original_tile_size = 16;\n public int tile_size = original_tile_size * scale; \n\n public int screen_width = tile_size * max_screen_col;\n public int screen_height = tile_size * max_screen_row;\n public BufferedImage map;\n\n public Map(String mapName) {\n\n super(mapName);\n tm = new TileManager(this); // Passa a instância atual de Map para TileManager\n }\n\n public void loadMap(Graphics2D g2d) {\n try {\n map = ImageIO.read(getClass().getResource(\"/sprites/map/map.png\"));\n } catch (IOException e) {\n e.printStackTrace();\n };\n\n g2d.drawImage(map, 0, 0, null);\n }\n}"
},
{
"identifier": "Start",
"path": "src/main/java/interfaces/start/Start.java",
"snippet": "public class Start extends JPanel {\n\n private GamePanel screen;\n private Trainer player;\n private Trainer rival;\n private ChooseSkin ChooseSkin;\n\n public Start(GamePanel screen) {\n this.screen = screen;\n this.player = new Trainer(null, null);\n this.rival = new Trainer(null, null);\n this.ChooseSkin = new ChooseSkin();\n add(ChooseSkin);\n }\n\n public void runStartSequence() {\n\n namePlayer();\n nameRival();\n chooseCharacter();\n }\n\n public void namePlayer() {\n \n String playerName = JOptionPane.showInputDialog(screen, \"Enter your name:\");\n player.setNome(playerName);\n }\n\n public void nameRival() {\n\n String rivalName = JOptionPane.showInputDialog(screen, \"Enter your rival's name:\");\n rival.setNome(rivalName);\n }\n\n public void chooseCharacter() {\n\n JOptionPane.showMessageDialog(screen, ChooseSkin, \"Who are you?\", JOptionPane.PLAIN_MESSAGE);\n\n String selectedSkin = ChooseSkin.getSelectedSkin();\n\n player.setCharacter(selectedSkin);\n rival.setCharacter(selectedSkin.equals(\"/sprites/characters/zeze/\") ? \"/sprites/characters/heldin/\" : \"/sprites/characters/zeze/\");\n }\n\n public Trainer getPlayer() {\n return player;\n }\n\n public Trainer getRival() {\n return rival;\n }\n}"
}
] | import javax.swing.JPanel;
import controllers.controls.KeyHandler;
import controllers.entity.Player;
import interfaces.map.Map;
import interfaces.start.Start;
import java.awt.*; | 3,230 | package interfaces;
public class GamePanel extends JPanel implements Runnable {
Map map = new Map("map_1");
public KeyHandler key = new KeyHandler();
Player player;
| package interfaces;
public class GamePanel extends JPanel implements Runnable {
Map map = new Map("map_1");
public KeyHandler key = new KeyHandler();
Player player;
| Start start_panel; | 3 | 2023-11-12 16:44:00+00:00 | 4k |
kigangka/iotdb-server | src/main/java/com/kit/iotdb/controller/WeatherController.java | [
{
"identifier": "Constant",
"path": "src/main/java/com/kit/iotdb/common/utils/Constant.java",
"snippet": "public class Constant {\n\n /**\n * 空气质量选项\n */\n public final static String[] QUALITY_OPTIONS = new String[]{\"优\", \"良\", \"中\", \"差\"};\n}"
},
{
"identifier": "Rst",
"path": "src/main/java/com/kit/iotdb/common/utils/Rst.java",
"snippet": "public class Rst extends LinkedHashMap<String, Object> implements Serializable {\n\n private static final long serialVersionUID = 1L; // 序列化版本号\n public static final int CODE_SUCCESS = 200;\n public static final int CODE_ERROR = 500;\n\n public Rst() {\n }\n\n public Rst(int code, String msg, Object data) {\n this.setCode(code);\n this.setMsg(msg);\n this.setData(data);\n }\n\n /**\n * 获取code\n *\n * @return code\n */\n public Integer getCode() {\n return (Integer) this.get(\"code\");\n }\n\n /**\n * 获取msg\n *\n * @return msg\n */\n public String getMsg() {\n return (String) this.get(\"msg\");\n }\n\n /**\n * 获取data\n *\n * @return data\n */\n public Object getData() {\n return (Object) this.get(\"data\");\n }\n\n /**\n * 给code赋值,连缀风格\n *\n * @param code code\n * @return 对象自身\n */\n public Rst setCode(int code) {\n this.put(\"code\", code);\n return this;\n }\n\n /**\n * 给msg赋值,连缀风格\n *\n * @param msg msg\n * @return 对象自身\n */\n public Rst setMsg(String msg) {\n this.put(\"msg\", msg);\n return this;\n }\n\n /**\n * 给data赋值,连缀风格\n *\n * @param data data\n * @return 对象自身\n */\n public Rst setData(Object data) {\n this.put(\"data\", data);\n return this;\n }\n\n // 构建成功\n public static Rst ok() {\n return new Rst(CODE_SUCCESS, \"ok\", null);\n }\n\n public static Rst ok(String msg) {\n return new Rst(CODE_SUCCESS, msg, null);\n }\n\n public static Rst code(int code) {\n return new Rst(code, null, null);\n }\n\n public static Rst data(Object data) {\n return new Rst(CODE_SUCCESS, \"ok\", data);\n }\n\n // 构建失败\n public static Rst error() {\n return new Rst(CODE_ERROR, \"error\", null);\n }\n\n public static Rst error(String msg) {\n return new Rst(CODE_ERROR, msg, null);\n }\n\n @Override\n public String toString() {\n return \"{\"\n + \"\\\"code\\\": \" + this.getCode()\n + \", \\\"msg\\\": \" + transValue(this.getMsg())\n + \", \\\"data\\\": \" + transValue(this.getData())\n + \"}\";\n }\n\n private String transValue(Object value) {\n if (value instanceof String) {\n return \"\\\"\" + value + \"\\\"\";\n }\n return String.valueOf(value);\n }\n}"
},
{
"identifier": "WeatherEntity",
"path": "src/main/java/com/kit/iotdb/entity/WeatherEntity.java",
"snippet": "@Data\n@Builder\npublic class WeatherEntity {\n /**\n * 固定对应Time字段\n */\n private long timestamp;\n\n /**\n * 采样时间时间戳\n */\n private long samplingTime;\n\n /**\n * 采样时间字符\n */\n private String samplingTimeStr;\n\n /**\n * 城市编码\n */\n private Integer cityKey;\n\n /**\n * 城市\n */\n private String city;\n\n /**\n * 温度 ℃\n */\n private float temperature;\n\n /**\n * 湿度 %\n */\n private float humidity;\n\n /**\n * pm10\n */\n private float pm10;\n\n /**\n * pm10\n */\n private float pm25;\n\n /**\n * 空气质量\n */\n private String quality;\n\n /**\n * 天气描述\n */\n private String remark;\n}"
},
{
"identifier": "WeatherService",
"path": "src/main/java/com/kit/iotdb/service/WeatherService.java",
"snippet": "public interface WeatherService {\n\n Integer addWeather(WeatherEntity weatherEntity);\n\n List<WeatherEntity> pageWeather(Integer page, Integer pageSize);\n\n Integer deleteWeather(String startTime, String endTime);\n}"
}
] | import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.kit.iotdb.common.utils.Constant;
import com.kit.iotdb.common.utils.Rst;
import com.kit.iotdb.entity.WeatherEntity;
import com.kit.iotdb.service.WeatherService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.Date; | 1,697 | package com.kit.iotdb.controller;
/**
* 添加说明
*
* @author kit
* @version 1.0
* @date 2023/11/7 16:50
*/
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Resource
WeatherService weatherService;
/**
* 新增
*
* @return
*/
@GetMapping("add")
public Rst add() {
Date date = new Date();
// 模拟数据
// 此处涉及到的字符串的,必须前后加',如下面的city字段,quality字段, remark字段
WeatherEntity testEntity = WeatherEntity.builder()
.samplingTime(date.getTime())
.samplingTimeStr("'" + DateUtil.format(date, "yyyy-MM-dd HH:mm:ss") + "'")
.cityKey(101190101)
.city("'南京'")
.temperature(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(-18.2, 30.5, 1, RoundingMode.HALF_UP))))
.humidity(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(1, 100, 1, RoundingMode.HALF_UP))))
.pm10(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 0, RoundingMode.HALF_UP))))
.pm25(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 1, RoundingMode.HALF_UP)))) | package com.kit.iotdb.controller;
/**
* 添加说明
*
* @author kit
* @version 1.0
* @date 2023/11/7 16:50
*/
@RestController
@RequestMapping("/weather")
public class WeatherController {
@Resource
WeatherService weatherService;
/**
* 新增
*
* @return
*/
@GetMapping("add")
public Rst add() {
Date date = new Date();
// 模拟数据
// 此处涉及到的字符串的,必须前后加',如下面的city字段,quality字段, remark字段
WeatherEntity testEntity = WeatherEntity.builder()
.samplingTime(date.getTime())
.samplingTimeStr("'" + DateUtil.format(date, "yyyy-MM-dd HH:mm:ss") + "'")
.cityKey(101190101)
.city("'南京'")
.temperature(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(-18.2, 30.5, 1, RoundingMode.HALF_UP))))
.humidity(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(1, 100, 1, RoundingMode.HALF_UP))))
.pm10(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 0, RoundingMode.HALF_UP))))
.pm25(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 1, RoundingMode.HALF_UP)))) | .quality("'" + Constant.QUALITY_OPTIONS[RandomUtil.randomInt(0, 3)] + "'") | 0 | 2023-11-15 06:04:04+00:00 | 4k |
penyoofficial/HerbMS | src/main/java/com/penyo/herbms/controller/PrescriptionController.java | [
{
"identifier": "Prescription",
"path": "src/main/java/com/penyo/herbms/pojo/Prescription.java",
"snippet": "public class Prescription extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 中草药处方 ID(外键)\n */\n private int prescriptionId;\n /**\n * 中草药 ID(外键)\n */\n private int herbId;\n /**\n * 用量\n */\n private String dosage;\n /**\n * 用法\n */\n private String usage;\n\n public Prescription() {\n }\n\n public Prescription(int id, int prescriptionId, int herbId, String dosage, String usage) {\n this.id = id;\n this.prescriptionId = prescriptionId;\n this.herbId = herbId;\n this.dosage = dosage;\n this.usage = usage;\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getPrescriptionId() {\n return prescriptionId;\n }\n\n public void setPrescriptionID(int prescriptionId) {\n this.prescriptionId = prescriptionId;\n }\n\n public int getHerbId() {\n return herbId;\n }\n\n public void setHerbId(int herbId) {\n this.herbId = herbId;\n }\n\n public String getDosage() {\n return dosage;\n }\n\n public void setDosage(String dosage) {\n this.dosage = dosage;\n }\n\n public String getUsage() {\n return usage;\n }\n\n public void setUsage(String usage) {\n this.usage = usage;\n }\n}"
},
{
"identifier": "PrescriptionInfo",
"path": "src/main/java/com/penyo/herbms/pojo/PrescriptionInfo.java",
"snippet": "public class PrescriptionInfo extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 名称\n */\n private String name;\n /**\n * 别名\n */\n private String nickname;\n /**\n * 解释\n */\n private String description;\n\n public PrescriptionInfo() {\n }\n\n public PrescriptionInfo(int id, String name, String nickname, String description) {\n this.id = id;\n this.name = name;\n this.nickname = nickname;\n this.description = description;\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNickname() {\n return nickname;\n }\n\n public void setNickname(String nickname) {\n this.nickname = nickname;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n}"
},
{
"identifier": "ReturnDataPack",
"path": "src/main/java/com/penyo/herbms/pojo/ReturnDataPack.java",
"snippet": "public class ReturnDataPack<T> extends GenericBean {\n /**\n * 影响行数\n */\n private int affectedRows = -114514;\n /**\n * 结果\n */\n private List<T> objs;\n\n public ReturnDataPack() {\n }\n\n public ReturnDataPack(List<T> objs) {\n this.objs = objs;\n }\n\n public ReturnDataPack(int affectedRows, List<T> objs) {\n this.affectedRows = affectedRows;\n this.objs = objs;\n }\n\n public int getAffectedRows() {\n return affectedRows;\n }\n\n public void setAffectedRows(int affectedRows) {\n this.affectedRows = affectedRows;\n }\n\n public List<T> getObjs() {\n return objs;\n }\n\n public void setObjs(List<T> objs) {\n this.objs = objs;\n }\n}"
},
{
"identifier": "HerbService",
"path": "src/main/java/com/penyo/herbms/service/HerbService.java",
"snippet": "@Service\npublic class HerbService extends GenericService<Herb> {\n @Override\n public int add(Herb o) {\n return herbDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return herbDAO.delete(id);\n }\n\n @Override\n public int update(Herb o) {\n return herbDAO.update(o);\n }\n\n @Override\n public Herb selectById(int id) {\n return herbDAO.selectById(id);\n }\n\n @Override\n public List<Herb> selectByFields(List<String> fields) {\n return herbDAO.selectByFields(fields);\n }\n\n /**\n * 根据中草药使用心得 ID 查询单个中草药名称。\n */\n public String selectNameByExperienceId(int id) {\n return herbDAO.selectByExperienceId(id).getName();\n }\n\n /**\n * 根据处方 ID 查找多个中草药名称和解释。\n */\n public List<String> selectNamesAndDescriptionsByPrescriptionId(int id) {\n List<String> names = new ArrayList<>();\n\n for (Herb o : herbDAO.selectByPrescriptionId(id))\n names.add(o.getName() + \"/\" + o.getDescription());\n return names;\n }\n}"
},
{
"identifier": "PrescriptionService",
"path": "src/main/java/com/penyo/herbms/service/PrescriptionService.java",
"snippet": "@Service\npublic class PrescriptionService extends GenericService<Prescription> {\n @Override\n public int add(Prescription o) {\n return prescriptionDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return prescriptionDAO.delete(id);\n }\n\n @Override\n public int update(Prescription o) {\n return prescriptionDAO.update(o);\n }\n\n @Override\n public Prescription selectById(int id) {\n return prescriptionDAO.selectById(id);\n }\n\n @Override\n public List<Prescription> selectByFields(List<String> fields) {\n return prescriptionDAO.selectByFields(fields);\n }\n\n /**\n * 根据处方 ID 查找处方概要。\n */\n public PrescriptionInfo selectPrescriptionInfoByPrescriptionId(int id) {\n return prescriptionInfoDAO.selectByPrescriptionId(id);\n }\n}"
}
] | import com.penyo.herbms.pojo.Prescription;
import com.penyo.herbms.pojo.PrescriptionInfo;
import com.penyo.herbms.pojo.ReturnDataPack;
import com.penyo.herbms.service.HerbService;
import com.penyo.herbms.service.PrescriptionService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | 1,840 | package com.penyo.herbms.controller;
/**
* 处方的控制器代理
*
* @author Penyo
* @see Prescription
* @see GenericController
*/
@Controller
public class PrescriptionController extends GenericController<Prescription> {
@Override
@RequestMapping("/use-prescriptions")
@ResponseBody
public String requestMain(HttpServletRequest request) { | package com.penyo.herbms.controller;
/**
* 处方的控制器代理
*
* @author Penyo
* @see Prescription
* @see GenericController
*/
@Controller
public class PrescriptionController extends GenericController<Prescription> {
@Override
@RequestMapping("/use-prescriptions")
@ResponseBody
public String requestMain(HttpServletRequest request) { | return requestMain(toMap(request), getService(PrescriptionService.class)).toString(); | 4 | 2023-11-13 16:40:05+00:00 | 4k |
martin-bian/DimpleBlog | dimple-blog/src/main/java/com/dimple/service/impl/TagServiceImpl.java | [
{
"identifier": "Tag",
"path": "dimple-blog/src/main/java/com/dimple/domain/Tag.java",
"snippet": "@Data\n@Entity\n@Table(name = \"bg_tag\")\npublic class Tag extends BaseEntity implements Serializable {\n @Id\n @Column(name = \"tag_id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String color;\n\n private String title;\n}"
},
{
"identifier": "TagMapper",
"path": "dimple-blog/src/main/java/com/dimple/mapstruct/TagMapper.java",
"snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface TagMapper extends BaseMapper<TagDTO, Tag> {\n}"
},
{
"identifier": "TagRepository",
"path": "dimple-blog/src/main/java/com/dimple/repository/TagRepository.java",
"snippet": "@Repository\npublic interface TagRepository extends JpaRepository<Tag, Long>, JpaSpecificationExecutor<Tag> {\n\n void deleteAllByIdIn(Set<Long> ids);\n}"
},
{
"identifier": "TagCriteria",
"path": "dimple-blog/src/main/java/com/dimple/service/Dto/TagCriteria.java",
"snippet": "@Data\npublic class TagCriteria {\n @Query(blurry = \"title\")\n private String blurry;\n}"
},
{
"identifier": "TagService",
"path": "dimple-blog/src/main/java/com/dimple/service/TagService.java",
"snippet": "public interface TagService {\n\n Map<String, Object> queryAll(TagCriteria criteria, Pageable pageable);\n\n Tag findById(Long id);\n\n void create(Tag tag);\n\n void update(Tag tag);\n\n void delete(Set<Long> ids);\n}"
},
{
"identifier": "BadRequestException",
"path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java",
"snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) {\n super(msg);\n }\n\n public BadRequestException(HttpStatus status, String msg) {\n super(msg);\n this.status = status.value();\n }\n}"
},
{
"identifier": "PageUtil",
"path": "dimple-common/src/main/java/com/dimple/utils/PageUtil.java",
"snippet": "public class PageUtil extends cn.hutool.core.util.PageUtil {\n\n /**\n * List 分页\n */\n public static List toPage(int page, int size, List list) {\n int fromIndex = page * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n return new ArrayList();\n } else if (toIndex >= list.size()) {\n return list.subList(fromIndex, list.size());\n } else {\n return list.subList(fromIndex, toIndex);\n }\n }\n\n /**\n * Page 数据处理,预防redis反序列化报错\n */\n public static Map<String, Object> toPage(Page page) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", page.getContent());\n map.put(\"totalElements\", page.getTotalElements());\n return map;\n }\n\n /**\n * 自定义分页\n */\n public static Map<String, Object> toPage(Object object, Object totalElements) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", object);\n map.put(\"totalElements\", totalElements);\n return map;\n }\n\n}"
},
{
"identifier": "QueryHelp",
"path": "dimple-common/src/main/java/com/dimple/utils/QueryHelp.java",
"snippet": "@Slf4j\n@SuppressWarnings({\"unchecked\", \"all\"})\npublic class QueryHelp {\n\n public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {\n List<Predicate> list = new ArrayList<>();\n if (query == null) {\n return cb.and(list.toArray(new Predicate[0]));\n }\n try {\n List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());\n for (Field field : fields) {\n boolean accessible = field.isAccessible();\n // 设置对象的访问权限,保证对private的属性的访\n field.setAccessible(true);\n Query q = field.getAnnotation(Query.class);\n if (q != null) {\n String propName = q.propName();\n String joinName = q.joinName();\n String blurry = q.blurry();\n String attributeName = isBlank(propName) ? field.getName() : propName;\n Class<?> fieldType = field.getType();\n Object val = field.get(query);\n if (ObjectUtil.isNull(val) || \"\".equals(val)) {\n continue;\n }\n Join join = null;\n // 模糊多字段\n if (ObjectUtil.isNotEmpty(blurry)) {\n String[] blurrys = blurry.split(\",\");\n List<Predicate> orPredicate = new ArrayList<>();\n for (String s : blurrys) {\n orPredicate.add(cb.like(root.get(s)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n }\n Predicate[] p = new Predicate[orPredicate.size()];\n list.add(cb.or(orPredicate.toArray(p)));\n continue;\n }\n if (ObjectUtil.isNotEmpty(joinName)) {\n String[] joinNames = joinName.split(\">\");\n for (String name : joinNames) {\n switch (q.join()) {\n case LEFT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.LEFT);\n } else {\n join = root.join(name, JoinType.LEFT);\n }\n break;\n case RIGHT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.RIGHT);\n } else {\n join = root.join(name, JoinType.RIGHT);\n }\n break;\n default:\n break;\n }\n }\n }\n switch (q.type()) {\n case EQUAL:\n list.add(cb.equal(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), val));\n break;\n case GREATER_THAN:\n list.add(cb.greaterThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN:\n list.add(cb.lessThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN_NQ:\n list.add(cb.lessThan(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case INNER_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n break;\n case LEFT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString()));\n break;\n case RIGHT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), val.toString() + \"%\"));\n break;\n case IN:\n if (CollUtil.isNotEmpty((Collection<Long>) val)) {\n list.add(getExpression(attributeName, join, root).in((Collection<Long>) val));\n }\n break;\n case NOT_EQUAL:\n list.add(cb.notEqual(getExpression(attributeName, join, root), val));\n break;\n case NOT_NULL:\n list.add(cb.isNotNull(getExpression(attributeName, join, root)));\n break;\n case IS_NULL:\n list.add(cb.isNull(getExpression(attributeName, join, root)));\n break;\n case BETWEEN:\n List<Object> between = new ArrayList<>((List<Object>) val);\n list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),\n (Comparable) between.get(0), (Comparable) between.get(1)));\n break;\n default:\n break;\n }\n }\n field.setAccessible(accessible);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n int size = list.size();\n return cb.and(list.toArray(new Predicate[size]));\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {\n if (ObjectUtil.isNotEmpty(join)) {\n return join.get(attributeName);\n } else {\n return root.get(attributeName);\n }\n }\n\n private static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n public static List<Field> getAllFields(Class clazz, List<Field> fields) {\n if (clazz != null) {\n fields.addAll(Arrays.asList(clazz.getDeclaredFields()));\n getAllFields(clazz.getSuperclass(), fields);\n }\n return fields;\n }\n}"
}
] | import com.dimple.domain.Tag;
import com.dimple.mapstruct.TagMapper;
import com.dimple.repository.TagRepository;
import com.dimple.service.Dto.TagCriteria;
import com.dimple.service.TagService;
import com.dimple.exception.BadRequestException;
import com.dimple.utils.PageUtil;
import com.dimple.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Set; | 2,297 | package com.dimple.service.impl;
/**
* @className: TagServiceImpl
* @description:
* @author: Dimple
* @date: 06/19/20
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class TagServiceImpl implements TagService {
| package com.dimple.service.impl;
/**
* @className: TagServiceImpl
* @description:
* @author: Dimple
* @date: 06/19/20
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class TagServiceImpl implements TagService {
| private final TagRepository tagRepository; | 2 | 2023-11-10 03:30:36+00:00 | 4k |
LazyCoder0101/LazyCoder | ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/intputscutcheon/labelscutcheon/CustomVariableLabel.java | [
{
"identifier": "LabelElementName",
"path": "database/src/main/java/com/lazycoder/database/common/LabelElementName.java",
"snippet": "public class LabelElementName {\n\n\t/**\n\t * 内容输入 t !!\n\t */\n\tpublic static final String TEXT_INPUT = \"textInput\";\n\n\t/**\n\t * 选择 c !!\n\t */\n\tpublic static final String CONTENT_CHOOSE = \"contentChoose\";\n\n\t/**\n\t * 功能拓展 m !\n\t */\n\tpublic static final String FUNCTION_ADD = \"functionAdd\";\n\n\t/**\n\t * 自定义变量 x\n\t */\n\tpublic static final String CUSTOM_VARIABLE = \"customVariable\";\n\n\t/**\n\t * 变量 v\n\t */\n\tpublic static final String VARIABLE = \"variable\";\n\n\t/**\n\t * 常量 s !\n\t */\n\tpublic static final String CONSTANT = \"constant\";\n\n\t/**\n\t * 文件 f !\n\t */\n\tpublic static final String FILE_SELECTOR = \"fileSelector\";\n\n\t/**\n\t * 注释 n (控制面板才有)!\n\t */\n\tpublic static final String NOTE = \"note\";\n\n\t/**\n\t * 图片 p(控制面板才有) !\n\t */\n\tpublic static final String PICTURE = \"picture\";\n\n\t/**\n\t * 代码输入 i !\n\t */\n\tpublic static final String CODE_INPUT = \"codeInput\";\n\n\t/**\n\t * 不常用设置 u !(控制面板才可能有)\n\t */\n\tpublic static final String INFREQUENTLY_USED_SETTING = \"infrequentlyUsedSetting\";\n\n\t/**\n\t * 方法名 d\n\t */\n\tpublic static final String CUSTOM_METHOD_NAME = \"customMethodName\";\n\n\t/**\n\t * 方法选择 y\n\t */\n\tpublic static final String METHOD_CHOOSE = \"methodChoose\";\n\n\t/**\n\t * 自己文件名(只有代码模板才有)\n\t */\n\tpublic static final String THIS_FILE_NAME = \"thisFileName\";\n\n\t/**\n\t * 对应的可选模板所添加的格式文件\n\t */\n\tpublic static final String CORRESPONDING_ADDITIONAL_DEFAULT_FILE = \"correspondingAdditionalDefaultFile\";\n\n}"
},
{
"identifier": "SysFileStructure",
"path": "service/src/main/java/com/lazycoder/service/fileStructure/SysFileStructure.java",
"snippet": "public class SysFileStructure {\n\n /**\n * 懒农文件使用后缀\n */\n public static final String PRO_SUFFIX = \".lannong\";\n\n /**\n * sqlite数据库后缀\n */\n public static final String SQLITE_SUFFIX = \".db\";\n\n// /**\n// * 当前程序目录\n// */\n//// public static final String sysDir = System.getProperty(\"user.dir\") + File.separator + \"app\";\n// public static String sysDir = DruidDBConfig.sysDir;\n\n /**\n * 用户使用时添加数据源的文件存放路径\n *\n * @return\n */\n public static File getDataFileFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"fileDataPath\");\n }\n\n /**\n * 根据此文件夹下的文件结构来进行列表显示\n *\n * @return\n */\n public static File getFileListFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"fileListPath\");\n }\n\n /**\n * 系统图片路径\n *\n * @return\n */\n public static File getImageFolder() {\n return LazyCoderBaseConfiguration.getImageFolder();\n }\n\n /**\n * 操作提示的图片路径\n * @param path 相对路径\n * @return\n */\n public static File getOperatingTipImageFolder(String path) {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"operatingTipImage\"+File.separator+path);\n }\n\n /**\n * 用户使用时添加的sqlite数据库的存放路径\n *\n * @return\n */\n public static File getUserDBFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"lannong_db\");\n }\n\n /**\n * 获取对应的sqlite数据库文件\n *\n * @param dataSourceName\n * @return\n */\n public static File getSqliteDBFile(String dataSourceName) {\n return new File(getUserDBFolder().getAbsolutePath() + File.separator + dataSourceName + SQLITE_SUFFIX);\n }\n\n /**\n * 系统数据库存放路径\n *\n * @return\n */\n public static File getSysDBFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"sysdb\");\n }\n\n public static File getSysDataSourceSqlite() {\n return new File(getSysDBFolder().getAbsolutePath() + File.separator + \"sysDataSource.db\");\n }\n\n /**\n * 临时文件夹(用来放一些文件)\n *\n * @return\n */\n protected static File getTempFolder() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"temp\");\n }\n\n\n private static File appCoolFormatDll() {\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"CoolFormatLib.dll\");\n }\n\n private static File userCoolFormatDll() {\n //return new File(System.getProperty(\"user.dir\") + File.separator + \"CoolFormatLib.dll\");\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"CoolFormatLib.dll\");\n }\n\n\n /**\n * 获取verilog的配置文件\n *\n * @return\n */\n public static File getVerilogSettingFile() {\n //return new File(System.getProperty(\"user.dir\") + File.separator + \"verilog\"+File.separator+\".verilog-format.properties\");\n return new File(LazyCoderBaseConfiguration.sysDir + File.separator + \"verilog\" + File.separator + \".verilog-format.properties\");\n }\n\n /**\n * 生成系统结构\n */\n public static void generateSysFileStrucure() {\n File file = getSysDBFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getUserDBFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getFileListFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getDataFileFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n file = getTempFolder();\n if (file.isDirectory() == false) {\n file.mkdirs();\n }\n }\n\n /**\n * 复制CoolFormat的dll\n */\n public static void copyCoolFormatDll() {\n if (userCoolFormatDll().exists() == false) {\n if (appCoolFormatDll().exists() == true) {\n try {\n FileUtil.fileCopyNormal(appCoolFormatDll(), userCoolFormatDll());\n FileUtil.setFileHidden(appCoolFormatDll());\n } catch (IOException e) {\n SysService.SYS_SERVICE_SERVICE.log_error( \"复制CoolFormat的dll出错,错误信息:\" + e.getMessage());\n }\n } else {\n SysService.SYS_SERVICE_SERVICE.log_error( \"CoolFormat的dll丢失\");\n }\n }\n }\n\n}"
},
{
"identifier": "BaseLableElement",
"path": "service/src/main/java/com/lazycoder/service/vo/element/lable/BaseLableElement.java",
"snippet": "@Data\npublic abstract class BaseLableElement extends BaseElement {\n\n\t@JSONField(ordinal = 2)\n\tprivate String labelType;\n\n\t@JSONField(ordinal = 3)\n\tprivate String thisName;\n\n\tpublic BaseLableElement() {\n\t\t// TODO Auto-generated constructor stub\n\t\ttype = ElementName.LABEL_ELEMENT;\n\t}\n\n\t/**\n\t * 查看根据字符串进行JSONObject解析后JSONObject的元素类型\n\t *\n\t * @param elementJSONObject\n\t * @return\n\t */\n\tpublic static String getLabelType(JSONObject elementJSONObject) {\n\t\treturn elementJSONObject.getString(\"labelType\");\n\t}\n\n\n\t/**\n\t * 匹配\n\t *\n\t * @param opratingLabel 操作层标签\n\t */\n\tpublic boolean match(BaseLableElement opratingLabel) {\n\t\tboolean flag = false;\n\t\tif (this.thisName.equals(opratingLabel.thisName)) {\n\t\t\tif (labelType.equals(opratingLabel.labelType)) {\n\t\t\t\tflag = true;\n\t\t\t}\n\t\t}\n\t\treturn flag;\n\t}\n\n\t/**\n\t * 匹配(该方法只供给代码元素使用)\n\t *\n\t * @param pathFindCell\n\t * @return\n\t */\n\tpublic boolean match(PathFindCell pathFindCell) {\n\t\tboolean flag = false;\n\t\tif (this.match(pathFindCell.getOpratingLabel()) == true) {\n\t\t\tflag = true;\n\t\t}\n\t\treturn flag;\n\t}\n\n\t/**\n\t * 控制组件才需要重写,该组件的信息\n\t *\n\t * @return\n\t */\n\tpublic BaseLableElement controlComponentInformation() {\n\t\treturn null;\n\t}\n\n}"
},
{
"identifier": "PassingComponentParams",
"path": "ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/inputmeta/pane/base/PassingComponentParams.java",
"snippet": "@Data\n@NoArgsConstructor\npublic class PassingComponentParams {\n\n\tprivate BasePane thisPane = null;\n\n\tprivate AbstractEditContainerModel generalModel = null;\n\n}"
},
{
"identifier": "MyButton",
"path": "ui-utils/src/main/java/com/lazycoder/uiutils/mycomponent/MyButton.java",
"snippet": "public class MyButton extends JButton {\n\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = 8262517162910576309L;\n\n\tpublic MyButton() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetFocusPainted(false);\n\t}\n\n\n\tpublic MyButton(String text) {\n\t\t// TODO Auto-generated constructor stub\n\t\tsuper(text);\n\t\tsetFocusPainted(false);\n\t}\n\n\tpublic MyButton(Icon icon) {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetIcon(icon);\n\t\tsetFocusPainted(false);\n\t}\n\n\n\tpublic MyButton(String text, Icon icon) {\n\t\t// TODO Auto-generated constructor stub\n\t\tthis(text);\n\t\tsetIcon(icon);\n\t}\n}"
}
] | import com.lazycoder.database.common.LabelElementName;
import com.lazycoder.service.fileStructure.SysFileStructure;
import com.lazycoder.service.vo.element.lable.BaseLableElement;
import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.base.PassingComponentParams;
import com.lazycoder.uiutils.mycomponent.MyButton;
import java.awt.Dimension;
import java.io.File;
import javax.swing.ImageIcon; | 3,080 | package com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon;
public class CustomVariableLabel extends MyButton implements LabelComponentIntetface {
/**
* 多个变量
*/
public final static ImageIcon CUSTOM_ARRAY_ICON = new ImageIcon(
SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + "code_content_edit" + File.separator + "base_code_content_edit" + File.separator
+ "label_element" + File.separator + "custom_variable" + File.separator + "custom_array.png");
/**
*
*/
private static final long serialVersionUID = -3492363933786387477L;
private PassingComponentParams passingComponentParams = null;
/**
* 添加在daima面板
*/
public CustomVariableLabel() {
super(CUSTOM_ARRAY_ICON);
Dimension dd = new Dimension(80, 30);
this.setMaximumSize(dd);
this.setMinimumSize(dd);
this.setPreferredSize(dd);
this.setFocusPainted(false);
}
@Override
public void deleteFromPanel() {
// TODO Auto-generated method stub
}
@Override
public String getLabelType() {
// TODO Auto-generated method stub
return LabelElementName.CUSTOM_VARIABLE;
}
@Override
public PassingComponentParams getPassingComponentParams() {
// TODO Auto-generated method stub
return passingComponentParams;
}
@Override
public void setPassingComponentParams(PassingComponentParams passingComponentParams) {
// TODO Auto-generated method stub
this.passingComponentParams = passingComponentParams;
LabelComponentIntetface.addCorrespondingComponentResponseListener(this);
}
@Override
public void setNavigate(boolean flag) {
}
@Override | package com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon;
public class CustomVariableLabel extends MyButton implements LabelComponentIntetface {
/**
* 多个变量
*/
public final static ImageIcon CUSTOM_ARRAY_ICON = new ImageIcon(
SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + "code_content_edit" + File.separator + "base_code_content_edit" + File.separator
+ "label_element" + File.separator + "custom_variable" + File.separator + "custom_array.png");
/**
*
*/
private static final long serialVersionUID = -3492363933786387477L;
private PassingComponentParams passingComponentParams = null;
/**
* 添加在daima面板
*/
public CustomVariableLabel() {
super(CUSTOM_ARRAY_ICON);
Dimension dd = new Dimension(80, 30);
this.setMaximumSize(dd);
this.setMinimumSize(dd);
this.setPreferredSize(dd);
this.setFocusPainted(false);
}
@Override
public void deleteFromPanel() {
// TODO Auto-generated method stub
}
@Override
public String getLabelType() {
// TODO Auto-generated method stub
return LabelElementName.CUSTOM_VARIABLE;
}
@Override
public PassingComponentParams getPassingComponentParams() {
// TODO Auto-generated method stub
return passingComponentParams;
}
@Override
public void setPassingComponentParams(PassingComponentParams passingComponentParams) {
// TODO Auto-generated method stub
this.passingComponentParams = passingComponentParams;
LabelComponentIntetface.addCorrespondingComponentResponseListener(this);
}
@Override
public void setNavigate(boolean flag) {
}
@Override | public BaseLableElement property() { | 2 | 2023-11-16 11:55:06+00:00 | 4k |
hardingadonis/miu-shop | src/main/java/io/hardingadonis/miu/controller/admin/AddNewProduct.java | [
{
"identifier": "Product",
"path": "src/main/java/io/hardingadonis/miu/model/Product.java",
"snippet": "public class Product {\n\n private int ID;\n private String brand;\n private String name;\n private int categoryID;\n private String origin;\n private String expiryDate;\n private String weight;\n private String preservation;\n private long price;\n private int amount;\n private String thumbnail;\n private List<String> images;\n private LocalDateTime createAt;\n private LocalDateTime updateAt;\n private LocalDateTime deleteAt;\n\n public Product() {\n }\n\n public Product(String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images) {\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n }\n\n public Product(String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images, LocalDateTime createAt, LocalDateTime updateAt, LocalDateTime deleteAt) {\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n this.createAt = createAt;\n this.updateAt = updateAt;\n this.deleteAt = deleteAt;\n }\n\n public Product(int ID, String brand, String name, int categoryID, String origin, String expiryDate, String weight, String preservation, long price, int amount, String thumbnail, List<String> images, LocalDateTime createAt, LocalDateTime updateAt, LocalDateTime deleteAt) {\n this.ID = ID;\n this.brand = brand;\n this.name = name;\n this.categoryID = categoryID;\n this.origin = origin;\n this.expiryDate = expiryDate;\n this.weight = weight;\n this.preservation = preservation;\n this.price = price;\n this.amount = amount;\n this.thumbnail = thumbnail;\n this.images = images;\n this.createAt = createAt;\n this.updateAt = updateAt;\n this.deleteAt = deleteAt;\n }\n\n public int getID() {\n return ID;\n }\n\n public void setID(int ID) {\n this.ID = ID;\n }\n\n public String getBrand() {\n return brand;\n }\n\n public void setBrand(String brand) {\n this.brand = brand;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getCategoryID() {\n return categoryID;\n }\n\n public void setCategoryID(int categoryID) {\n this.categoryID = categoryID;\n }\n\n public String getOrigin() {\n return origin;\n }\n\n public void setOrigin(String origin) {\n this.origin = origin;\n }\n\n public String getExpiryDate() {\n return expiryDate;\n }\n\n public void setExpiryDate(String expiryDate) {\n this.expiryDate = expiryDate;\n }\n\n public String getWeight() {\n return weight;\n }\n\n public void setWeight(String weight) {\n this.weight = weight;\n }\n\n public String getPreservation() {\n return preservation;\n }\n\n public void setPreservation(String preservation) {\n this.preservation = preservation;\n }\n\n public long getPrice() {\n return price;\n }\n\n public void setPrice(long price) {\n this.price = price;\n }\n\n public int getAmount() {\n return amount;\n }\n\n public void setAmount(int amount) {\n this.amount = amount;\n }\n\n public String getThumbnail() {\n return thumbnail;\n }\n\n public void setThumbnail(String thumbnail) {\n this.thumbnail = thumbnail;\n }\n\n public List<String> getImages() {\n return images;\n }\n\n public void setImages(List<String> images) {\n this.images = images;\n }\n\n public LocalDateTime getCreateAt() {\n return createAt;\n }\n\n public void setCreateAt(LocalDateTime createAt) {\n this.createAt = createAt;\n }\n\n public LocalDateTime getUpdateAt() {\n return updateAt;\n }\n\n public void setUpdateAt(LocalDateTime updateAt) {\n this.updateAt = updateAt;\n }\n\n public LocalDateTime getDeleteAt() {\n return deleteAt;\n }\n\n public void setDeleteAt(LocalDateTime deleteAt) {\n this.deleteAt = deleteAt;\n }\n\n @Override\n public String toString() {\n return \"Product{\" + \"ID=\" + ID + \", brand=\" + brand + \", name=\" + name + \", categoryID=\" + categoryID + \", origin=\" + origin + \", expiryDate=\" + expiryDate + \", weight=\" + weight + \", preservation=\" + preservation + \", price=\" + price + \", amount=\" + amount + \", thumbnail=\" + thumbnail + \", images=\" + images + \", createAt=\" + createAt + \", updateAt=\" + updateAt + \", deleteAt=\" + deleteAt + '}';\n }\n}"
},
{
"identifier": "Singleton",
"path": "src/main/java/io/hardingadonis/miu/services/Singleton.java",
"snippet": "public class Singleton {\n\n public static DBContext dbContext;\n\n public static Email email;\n \n public static AdminDAO adminDAO;\n \n public static CategoryDAO categoryDAO;\n \n public static OrderDAO orderDAO;\n \n public static OrderDataDAO orderDataDAO;\n \n public static ProductDAO productDAO;\n \n public static UserDAO userDAO;\n\n static {\n dbContext = new DBContextMySQLImpl();\n\n email = new EmailGmailImpl();\n \n adminDAO = new AdminDAOMySQLImpl();\n \n categoryDAO = new CategoryDAOMySQLImpl();\n \n orderDAO = new OrderDAOMySQLImpl();\n \n orderDataDAO = new OrderDataDAOMySQLImpl();\n \n productDAO = new ProductDAOMySQLImpl();\n \n userDAO = new UserDAOMySQLImpl();\n }\n}"
}
] | import io.hardingadonis.miu.model.Product;
import io.hardingadonis.miu.services.Singleton;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Collections;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*; | 2,015 | package io.hardingadonis.miu.controller.admin;
@WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"})
public class AddNewProduct extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String nameProduct = request.getParameter("productName");
String productBrand = request.getParameter("productBrand");
int Category_ID = Integer.parseInt(request.getParameter("productCategoryID"));
String productOrigin = request.getParameter("productOrigin");
String productExpiry = request.getParameter("productExpiry");
String productWeight = request.getParameter("productWeight");
String productPreservation = request.getParameter("productPreservation");
long productPrice = Long.parseLong(request.getParameter("productPrice"));
int productAmount = Integer.parseInt(request.getParameter("productAmount"));
Product product = new Product();
product.setName(nameProduct);
product.setBrand(productBrand);
product.setCategoryID(Category_ID);
product.setOrigin(productOrigin);
product.setExpiryDate(productExpiry);
product.setWeight(productWeight);
product.setPreservation(productPreservation);
product.setPrice(productPrice);
product.setAmount(productAmount);
product.setThumbnail("");
product.setImages(Collections.EMPTY_LIST);
| package io.hardingadonis.miu.controller.admin;
@WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"})
public class AddNewProduct extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String nameProduct = request.getParameter("productName");
String productBrand = request.getParameter("productBrand");
int Category_ID = Integer.parseInt(request.getParameter("productCategoryID"));
String productOrigin = request.getParameter("productOrigin");
String productExpiry = request.getParameter("productExpiry");
String productWeight = request.getParameter("productWeight");
String productPreservation = request.getParameter("productPreservation");
long productPrice = Long.parseLong(request.getParameter("productPrice"));
int productAmount = Integer.parseInt(request.getParameter("productAmount"));
Product product = new Product();
product.setName(nameProduct);
product.setBrand(productBrand);
product.setCategoryID(Category_ID);
product.setOrigin(productOrigin);
product.setExpiryDate(productExpiry);
product.setWeight(productWeight);
product.setPreservation(productPreservation);
product.setPrice(productPrice);
product.setAmount(productAmount);
product.setThumbnail("");
product.setImages(Collections.EMPTY_LIST);
| Singleton.productDAO.insert(product); | 1 | 2023-11-16 07:15:44+00:00 | 4k |
kash-developer/HomeDeviceEmulator | app/src/main/java/kr/or/kashi/hde/stream/StreamTxThread.java | [
{
"identifier": "HomePacket",
"path": "app/src/main/java/kr/or/kashi/hde/HomePacket.java",
"snippet": "public interface HomePacket {\n String address();\n int command();\n byte[] data();\n\n int hashCode();\n boolean parse(ByteBuffer buffer) throws BufferUnderflowException;\n void toBuffer(ByteBuffer buffer) throws BufferOverflowException;\n\n public class WithMeta implements HomePacket {\n public boolean suppressLog = false;\n\n private final HomePacket mInner;\n\n public WithMeta(HomePacket inner) {\n mInner = inner;\n }\n\n @Override public String address() { return mInner.address();}\n @Override public int command() { return mInner.command(); }\n @Override public byte[] data() { return mInner.data(); }\n @Override public int hashCode() { return mInner.hashCode(); }\n @Override public boolean parse(ByteBuffer buffer) throws BufferUnderflowException { return mInner.parse(buffer); }\n @Override public void toBuffer(ByteBuffer buffer) throws BufferOverflowException { mInner.toBuffer(buffer); }\n }\n}"
},
{
"identifier": "Utils",
"path": "app/src/main/java/kr/or/kashi/hde/util/Utils.java",
"snippet": "public final class Utils {\n private static final char[] HEX_DIGITS = \"0123456789ABCDEF\".toCharArray();\n\n public static final long SECOND_MS = 1000;\n public static final long MINUTE_MS = 60 * SECOND_MS;\n public static final long HOUR_MS = 60 * MINUTE_MS;\n public static final long DAY_MS = 24 * HOUR_MS;\n\n public static float[] toFloatArray(List<Float> list) {\n final int size = list.size();\n final float[] array = new float[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static int[] toIntArray(List<Integer> list) {\n final int size = list.size();\n final int[] array = new int[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static byte[] toByteArray(List<Byte> list) {\n final int size = list.size();\n final byte[] array = new byte[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static String toHexString(byte b) {\n char[] buf = new char[2]; // We always want two digits.\n buf[0] = HEX_DIGITS[(b >> 4) & 0xf];\n buf[1] = HEX_DIGITS[b & 0xf];\n return new String(buf);\n }\n\n public static String toHexString(byte[] b) {\n return toHexString(b, b.length);\n }\n\n public static String toHexString(byte[] b, int length) {\n if (b == null) {\n return null;\n }\n int len = Math.min(length, b.length);\n StringBuilder sb = new StringBuilder(len * 3);\n for (int i = 0; i < len; i++) {\n sb.append(toHexString(b[i]));\n if (i < len-1) sb.append(\" \");\n }\n return sb.toString();\n }\n\n public static String toHexString(ByteBuffer byteBuffer) {\n byteBuffer.flip();\n int size = byteBuffer.remaining();\n if (size <= 0) return \"\";\n byte[] buffer = new byte[size];\n byteBuffer.get(buffer);\n return toHexString(buffer);\n }\n\n public static Point getDisplaySize(Context context) {\n Point size = new Point(0, 0);\n DisplayManager dm = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);\n Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);\n display.getRealSize(size);\n return size;\n }\n\n public static void changeDensity(Context context, int densityDpi) {\n DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();\n Configuration config = context.getResources().getConfiguration();\n displayMetrics.densityDpi = densityDpi;\n config.densityDpi = densityDpi;\n displayMetrics.setTo(displayMetrics);\n config.setTo(config);\n context.getResources().updateConfiguration(config, displayMetrics);\n }\n\n public static Context createContextByDensity(Context context, int densityDpi) {\n Configuration config = context.getResources().getConfiguration();\n config.densityDpi = densityDpi;\n return context.createConfigurationContext(config);\n }\n\n public static Context createDensityAdjustedContextByHeight(Context context, int heightPixels) {\n return Utils.createContextByDensity(context, Utils.getTargetDensityByHeight(context, heightPixels));\n }\n\n public static int getTargetDensityByHeight(Context context, int heightPixels) {\n DisplayMetrics displayMetrics = new DisplayMetrics();\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n windowManager.getDefaultDisplay().getMetrics(displayMetrics);\n // e.g.) 600(heightPixels) : 1080(displayMetrics.heightPixels) = 160 : targetDendity\n return (displayMetrics.heightPixels * 160) / heightPixels;\n }\n\n public static void adjustDensityByHeight(Context context, int heightPixels) {\n changeDensity(context, getTargetDensityByHeight(context, heightPixels));\n }\n\n public static long daysToMillis(double days) {\n return (long)(days * DAY_MS);\n }\n\n public static double millisToDays(long ms) {\n return Math.round(((double)ms / (double)DAY_MS) * 100000.0) / 100000.0;\n }\n}"
}
] | import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.InterruptedException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import kr.or.kashi.hde.HomePacket;
import kr.or.kashi.hde.util.Utils; | 1,637 | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kr.or.kashi.hde.stream;
public class StreamTxThread extends Thread {
private static final String TAG = StreamTxThread.class.getSimpleName();
private static final boolean DBG = true;
private final OutputStream mOutputStream;
private final StreamCallback mCallback; | /*
* Copyright (C) 2023 Korea Association of AI Smart Home.
* Copyright (C) 2023 KyungDong Navien Co, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kr.or.kashi.hde.stream;
public class StreamTxThread extends Thread {
private static final String TAG = StreamTxThread.class.getSimpleName();
private static final boolean DBG = true;
private final OutputStream mOutputStream;
private final StreamCallback mCallback; | private final ArrayDeque<HomePacket> mPacketQueue = new ArrayDeque<>(); | 0 | 2023-11-10 01:19:44+00:00 | 4k |
Bug1312/dm_locator | src/main/java/com/bug1312/dm_locator/network/PacketRequestLocate.java | [
{
"identifier": "Config",
"path": "src/main/java/com/bug1312/dm_locator/Config.java",
"snippet": "public class Config {\n\tpublic static final ForgeConfigSpec SERVER_SPEC;\n\tpublic static final ServerConfig SERVER_CONFIG;\n\n\tstatic {\n\t\tPair<ServerConfig, ForgeConfigSpec> serverConfigPair = new ForgeConfigSpec.Builder().configure(ServerConfig::new);\n\t\tSERVER_CONFIG = serverConfigPair.getLeft();\n\t\tSERVER_SPEC = serverConfigPair.getRight();\n\t}\n\n\tpublic static class ServerConfig {\n\t\tpublic final ConfigValue<Boolean> fastFeature;\n\t\tprivate final ConfigValue<List<? extends String>> structureBlacklist;\n\t\tprivate final ConfigValue<List<? extends String>> biomeBlackList;\n\t\t\n\t\tpublic List<ResourceLocation> getStructureBlacklist() {\n\t\t\treturn structureBlacklist.get().stream().map(s -> new ResourceLocation(s)).collect(Collectors.toList());\n\t\t}\n\t\t\n\t\tpublic List<ResourceLocation> getBiomeBlacklist() {\n\t\t\treturn biomeBlackList.get().stream().map(s -> new ResourceLocation(s)).collect(Collectors.toList());\n\t\t}\n\n\t\t\n\t\tServerConfig(Builder builder) {\n\t\t\tbuilder.comment(\"Structure Locator DM Addon Configuration Settings\").push(\"server\");\n\t\t\t\n\t\t\tthis.fastFeature = builder.comment(new String[] {\n\t\t\t\t\t\"Sacrifice accuracy for speed when writing structures to data modules\",\n\t\t\t\t\t\"When enabled the game will check the bounding box of the entire structure instead of its individual pieces to see if you are inside of it\"\n\t\t\t}).define(\"fast_write_math\", false);\n\t\t\t\n\t\t\tthis.structureBlacklist = builder.comment(new String[] {\n\t\t\t\t\t\"Disallows writing and locating certain structures\",\n\t\t\t\t\t\"Example: [\\\"minecraft:endcity\\\", \\\"minecraft:buried_treasure\\\"]\"\n\t\t\t}).defineList(\"structure_blacklist\", Collections.emptyList(), s -> ResourceLocation.isValidResourceLocation((String) s));\n\n\t\t\tthis.biomeBlackList = builder.comment(new String[] {\n\t\t\t\t\t\"Disallows writing and locating certain biomes\",\n\t\t\t\t\t\"Example: [\\\"minecraft:plains\\\", \\\"minecraft:buried_treasure\\\"]\"\n\t\t\t}).defineList(\"biome_blacklist\", Collections.emptyList(), s -> ResourceLocation.isValidResourceLocation((String) s));\n\t\t}\n\t}\n}"
},
{
"identifier": "Register",
"path": "src/main/java/com/bug1312/dm_locator/Register.java",
"snippet": "public class Register {\n\t// Items\n\tpublic static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID);\n\tpublic static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, \"locator_data_writer\", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1)));\n\tpublic static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, \"locator_attachment\", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS)));\n\t\n\t// Tiles\n\tpublic static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<TileEntityType<?>> FLIGHT_PANEL_TILE = register(TILE_ENTITIES, \"flight_panel\", () -> Builder.of(FlightPanelTileEntity::new, DMBlocks.FLIGHT_PANEL.get()).build(null));\n\n // Loot Modifiers\n\tpublic static final DeferredRegister<GlobalLootModifierSerializer<?>> LOOT_MODIFIERS = DeferredRegister.create(ForgeRegistries.LOOT_MODIFIER_SERIALIZERS, ModMain.MOD_ID);\n public static final RegistryObject<FlightPanelLootModifier.Serializer> FLIGHT_PANEL_LOOT_MODIFIER = register(LOOT_MODIFIERS, \"flight_panel\", FlightPanelLootModifier.Serializer::new);\n\n\t// Particles\n\tpublic static final DeferredRegister<ParticleType<?>> PARTICLE_TYPES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<ParticleType<LocateParticleData>> LOCATE_PARTICLE = register(PARTICLE_TYPES, \"locate\", () -> \n\t\tnew ParticleType<LocateParticleData>(false, LocateParticleData.DESERIALIZER) {\n\t\t\tpublic Codec<LocateParticleData> codec() { return LocateParticleData.CODEC;\t}\n\t\t}\n\t);\n\t\n\t// Advancement Triggers\n\tpublic static final WriteModuleTrigger TRIGGER_WRITE = CriteriaTriggers.register(new WriteModuleTrigger());\n\tpublic static final UseLocatorTrigger TRIGGER_USE = CriteriaTriggers.register(new UseLocatorTrigger());\n\n\t// Key Binds\n public static final KeyBinding KEYBIND_LOCATE = new KeyBinding(String.format(\"%s.keybinds.locate_blast\", ModMain.MOD_ID), 66, \"Dalek Mod\"); // B\n \n // Translations\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_SWAP_MODE = (m) -> new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.swap_mode.%s\", ModMain.MOD_ID, m));\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_TOOLTIP_MODE = (m) -> new TranslationTextComponent(String.format(\"item.%s.locator_data_writer.hover.mode.%s\", ModMain.MOD_ID, m));\n public static final TranslationTextComponent TEXT_INSUFFICIENT_FUEL = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.insufficient_fuel\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_structure\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_biome\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_WAYPOINT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_waypoint\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_MODULE = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_module\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_structures\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_biome\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_MODULES = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_modules\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_MODULE_WRITTEN = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.module_written\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_LOAD = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.load\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_EJECT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.eject\", ModMain.MOD_ID));\n public static final Supplier<TranslationTextComponent> TEXT_USE_BUTTON = () -> new TranslationTextComponent(String.format(\"overlay.%s.flight_mode.use_button\", ModMain.MOD_ID), new KeybindTextComponent(Register.KEYBIND_LOCATE.getName()));\n public static final BiFunction<LocatorDataWriterMode, String, TranslationTextComponent> TEXT_MODULE_NAME = (m, s) -> new TranslationTextComponent(String.format(\"name.%s.structure_module.%s\", ModMain.MOD_ID, m), s);\n\n // Register Method\n\tpublic static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> register(final DeferredRegister<T> register, final String name, final Supplier<U> supplier) {\n\t\treturn register.register(name, supplier);\n\t}\n}"
},
{
"identifier": "StructureHelper",
"path": "src/main/java/com/bug1312/dm_locator/StructureHelper.java",
"snippet": "public class StructureHelper {\n\n\tpublic static final Map<UUID, CompoundNBT> FLYING_PLAYERS_LOCATOR = new HashMap<>();\n\tpublic static boolean isFlyingWithLocator = false;\n\n\tprivate static final Predicate<Pair<MutableBoundingBox, Vector3i>> IS_INSIDE = (pair) -> {\n\t\tMutableBoundingBox bb = pair.getFirst();\n\t\tVector3i pos = pair.getSecond();\n\t\t// Certain structures don't have/require an air gap, \n\t\t// if player is directly above or next to the structure, I still want to pass\n\t\treturn (\n\t\t\tpos.getX() >= bb.x0-1 && pos.getX() <= bb.x1+1 &&\n\t\t\tpos.getZ() >= bb.z0-1 && pos.getZ() <= bb.z1+1 &&\n\t\t\tpos.getY() >= bb.y0-1 && pos.getY() <= bb.y1+1\n\t\t);\n\t};\n\n\tpublic static Optional<ResourceLocation> getStructure(ServerPlayerEntity player) {\n\t\tBlockPos pos = player.blockPosition();\n\t\t\n\t\tStructureManager featureManager = player.getLevel().structureFeatureManager();\n\t\treturn player.getLevel().getChunk(player.blockPosition()).getAllReferences().entrySet().stream() \n\t\t\t// Only look at structures with references inside chunk\n\t\t\t.filter(set -> set.getValue().size() > 0) \n\t\t\t.filter(set -> \n\t\t\t\tDataFixUtils.orElse(featureManager.startsForFeature(SectionPos.of(pos), set.getKey())\n\t\t\t\t\t// Only if player is inside entire structure\n\t\t\t\t\t.filter((start) -> IS_INSIDE.test(Pair.of(start.getBoundingBox(), pos))) \n\t\t\t\t\t// Skip if fastFeature enabled\n\t\t\t\t\t.filter((start) -> Config.SERVER_CONFIG.fastFeature.get() || start.getPieces().stream() \n\t\t\t\t\t\t// Only if player is inside structures' piece\n\t\t\t\t\t\t.anyMatch((piece) -> IS_INSIDE.test(Pair.of(piece.getBoundingBox(), pos)))) \n\t\t\t\t\t.findFirst(), StructureStart.INVALID_START).isValid())\n\t\t\t.findFirst().map(entry -> entry.getKey().getRegistryName());\n\t}\n\t\n\tpublic static String formatResourceLocationName(ResourceLocation resourceLocation) {\n\t\tString reformatted = resourceLocation.getPath().replaceAll(\"_\", \" \");\n\t\tPattern pattern = Pattern.compile(\"(^[a-z]| [a-z])\");\n\t\tMatcher matcher = pattern.matcher(reformatted);\n\t\tStringBuffer noKeyName = new StringBuffer();\n\n\t\twhile (matcher.find()) matcher.appendReplacement(noKeyName, matcher.group().toUpperCase());\n\t\t\n\t\tmatcher.appendTail(noKeyName);\n\t\t\n\t\treturn noKeyName.toString();\n\t}\n\t\n}"
},
{
"identifier": "LocateParticleData",
"path": "src/main/java/com/bug1312/dm_locator/particle/LocateParticleData.java",
"snippet": "public class LocateParticleData implements IParticleData {\n\tpublic static final Codec<LocateParticleData> CODEC = RecordCodecBuilder.create(\n\t\tinstance -> instance.group(\n\t\t\tCodec.FLOAT.fieldOf(\"destination_x\").forGetter(LocateParticleData -> LocateParticleData.x),\n\t\t\tCodec.FLOAT.fieldOf(\"destination_z\").forGetter(LocateParticleData -> LocateParticleData.z),\n\t\t\tCodec.INT.fieldOf(\"arrival_in_ticks\").forGetter(LocateParticleData -> LocateParticleData.arrivalInTicks)\n\t\t).apply(instance, LocateParticleData::new)\n\t);\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static final IParticleData.IDeserializer<LocateParticleData> DESERIALIZER = new IParticleData.IDeserializer<LocateParticleData>() {\n\t\t@Override\n\t\tpublic LocateParticleData fromCommand(ParticleType<LocateParticleData> particleType, StringReader stringReader) throws CommandSyntaxException {\n\t\t\tstringReader.expect(' ');\n\t\t\tfloat x = stringReader.readFloat();\n\t\t\tstringReader.expect(' ');\n\t\t\tfloat z = stringReader.readFloat();\n\t\t\tstringReader.expect(' ');\n\t\t\tint a = stringReader.readInt();\n\t\t\treturn new LocateParticleData(x, z, a);\n\t\t}\n\n\t\t@Override\n\t\tpublic LocateParticleData fromNetwork(ParticleType<LocateParticleData> particleType, PacketBuffer byteBuff) {\n\t\t\tint x = byteBuff.readVarInt();\n\t\t\tint z = byteBuff.readVarInt();\n\t\t\tint a = byteBuff.readVarInt();\n\n\t\t\treturn new LocateParticleData(x, z, a);\n\t\t}\n\t};\n\n\tpublic final float x;\n\tpublic final float z;\n\tpublic final int arrivalInTicks;\n\n\tpublic LocateParticleData(float x, float z, int arrivalInTicks) {\n\t\tthis.x = x;\n\t\tthis.z = z;\n\t\tthis.arrivalInTicks = arrivalInTicks;\n\t}\n\t\n\t@Override\n\tpublic ParticleType<?> getType() {\n\t\treturn Register.LOCATE_PARTICLE.get();\n\t}\n\n\t@Override\n\tpublic void writeToNetwork(PacketBuffer byteBuff) {\n\t\tbyteBuff.writeFloat(this.x);\n\t\tbyteBuff.writeFloat(this.z);\n\t\tbyteBuff.writeVarInt(this.arrivalInTicks);\n\t}\n\n\t@Override\n\tpublic String writeToString() {\n\t\treturn String.format(Locale.ROOT, \"%d %d %d\", this.x, this.z, this.arrivalInTicks);\n\t}\n\n}"
}
] | import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.bug1312.dm_locator.Config;
import com.bug1312.dm_locator.Register;
import com.bug1312.dm_locator.StructureHelper;
import com.bug1312.dm_locator.particle.LocateParticleData;
import com.swdteam.common.init.DMFlightMode;
import com.swdteam.common.init.DMTardis;
import com.swdteam.common.init.DMTranslationKeys;
import com.swdteam.common.tardis.TardisData;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.registries.ForgeRegistries; | 3,429 | // Copyright 2023 Bug1312 ([email protected])
package com.bug1312.dm_locator.network;
public class PacketRequestLocate {
public PacketRequestLocate() {}
public static void encode(PacketRequestLocate msg, PacketBuffer buf) {}
public static PacketRequestLocate decode(PacketBuffer buf) {return new PacketRequestLocate();}
public static void handle(PacketRequestLocate msg, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
ServerPlayerEntity player = ctx.get().getSender();
if (StructureHelper.FLYING_PLAYERS_LOCATOR.containsKey(player.getUUID())) {
Consumer<TranslationTextComponent> sendError = (text) -> player.displayClientMessage(text.setStyle(Style.EMPTY.withColor(TextFormatting.RED)), true);
Consumer<Vector3d> toLocation = (end) -> {
Vector3d start = player.position();
Vector3d direction = end.subtract(start);
if (direction.length() > 15) direction = direction.normalize().scale(15);
Vector3d limitedEnd = start.add(direction);
Register.TRIGGER_USE.trigger(player); | // Copyright 2023 Bug1312 ([email protected])
package com.bug1312.dm_locator.network;
public class PacketRequestLocate {
public PacketRequestLocate() {}
public static void encode(PacketRequestLocate msg, PacketBuffer buf) {}
public static PacketRequestLocate decode(PacketBuffer buf) {return new PacketRequestLocate();}
public static void handle(PacketRequestLocate msg, Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
ServerPlayerEntity player = ctx.get().getSender();
if (StructureHelper.FLYING_PLAYERS_LOCATOR.containsKey(player.getUUID())) {
Consumer<TranslationTextComponent> sendError = (text) -> player.displayClientMessage(text.setStyle(Style.EMPTY.withColor(TextFormatting.RED)), true);
Consumer<Vector3d> toLocation = (end) -> {
Vector3d start = player.position();
Vector3d direction = end.subtract(start);
if (direction.length() > 15) direction = direction.normalize().scale(15);
Vector3d limitedEnd = start.add(direction);
Register.TRIGGER_USE.trigger(player); | player.getLevel().sendParticles(new LocateParticleData((float) limitedEnd.x(), (float) limitedEnd.z(), (int) direction.length()), start.x, start.y, start.z, 1, 0, 0, 0, 0); | 3 | 2023-11-13 03:42:37+00:00 | 4k |
zizai-Shen/young-im | young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/bind/ConfigServerConfigurationBind.java | [
{
"identifier": "YoungImException",
"path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java",
"snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImException(final Throwable e) {\n super(e);\n }\n}"
},
{
"identifier": "ConfigRefreshCallBack",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/callback/ConfigRefreshCallBack.java",
"snippet": "@FunctionalInterface\npublic interface ConfigRefreshCallBack {\n\n /**\n * 配置刷新 Callback\n */\n void refresh();\n}"
},
{
"identifier": "ConfigServerRepository",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/repository/ConfigServerRepository.java",
"snippet": "public interface ConfigServerRepository {\n\n String getConfig(String configKey, String groupId);\n\n\n ConfigService getConfigService();\n}"
},
{
"identifier": "ConfigType",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/ConfigType.java",
"snippet": "@Getter\npublic enum ConfigType {\n\n /**\n * Json\n */\n JSON(\"json\"),\n\n /**\n * text\n */\n PROPERTIES(\"properties\"),\n\n /**\n * yaml\n */\n YAML(\"yaml\"),\n\n /**\n *\n */\n UNSET(\"unset\");\n\n private static final Map<String, ConfigType> LOCAL_MAP = new HashMap<>();\n\n static {\n for (ConfigType configType : values()) {\n LOCAL_MAP.put(configType.getType(), configType);\n }\n }\n\n private final String type;\n\n ConfigType(String type) {\n this.type = type;\n }\n\n /**\n * 获取默认类型\n */\n public static ConfigType getDefaultType() {\n return YAML;\n }\n\n /**\n * 判断类型是否合法\n */\n public static Boolean isValidType(String type) {\n if (StringUtils.isBlank(type)) {\n return false;\n }\n return null != LOCAL_MAP.get(type);\n }\n}"
},
{
"identifier": "ConfigParseFactory",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/parse/ConfigParseFactory.java",
"snippet": "public class ConfigParseFactory {\n private static final Map<String, IConfigParseHandler> handlers = synchronizedMap(new LinkedHashMap<>());\n\n static {\n handlers.put(ConfigType.JSON.getType(), new JsonConfigParseHandler());\n handlers.put(ConfigType.PROPERTIES.getType(), new PropertiesConfigParseHandler());\n handlers.put(ConfigType.YAML.getType(), new YamlConfigParseHandler());\n }\n\n public static IConfigParseHandler acquireHandler(String type){\n return handlers.get(type);\n }\n}"
},
{
"identifier": "IConfigParseHandler",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/parse/IConfigParseHandler.java",
"snippet": "public interface IConfigParseHandler {\n\n /**\n * 解析\n */\n void parse(String content, Object bean);\n}"
},
{
"identifier": "ApplicationContextHolder",
"path": "young-im-spring-boot-starter/young-im-spring-boot-starter-extension/src/main/java/cn/young/im/springboot/starter/extension/spring/ApplicationContextHolder.java",
"snippet": "@Data\npublic class ApplicationContextHolder implements ApplicationContextAware {\n\n /**\n * Application Context\n */\n private ApplicationContext context;\n\n @Override\n public void setApplicationContext(ApplicationContext context) throws BeansException {\n this.context = context;\n }\n}"
}
] | import cn.young.im.common.exception.YoungImException;
import cn.young.im.springboot.starter.adapter.config.callback.ConfigRefreshCallBack;
import cn.young.im.springboot.starter.adapter.config.repository.ConfigServerRepository;
import cn.young.im.springboot.starter.adapter.config.ConfigType;
import cn.young.im.springboot.starter.adapter.config.anno.ConfigServerConfigurationProperties;
import cn.young.im.springboot.starter.adapter.config.parse.ConfigParseFactory;
import cn.young.im.springboot.starter.adapter.config.parse.IConfigParseHandler;
import cn.young.im.springboot.starter.extension.spring.ApplicationContextHolder;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import java.util.Objects; | 1,754 | package cn.young.im.springboot.starter.adapter.config.bind;
@AllArgsConstructor
public class ConfigServerConfigurationBind implements BeanPostProcessor {
private final ConfigServerRepository configServerRepository;
private final ApplicationContextHolder contextHolder;
/**
* 实例化前对注解进行处理
*/
@Override
public Object postProcessBeforeInitialization(Object bean, @NonNull String beanName) throws BeansException {
// 1. 提取注解
ConfigServerConfigurationProperties annotation =
AnnotationUtils.findAnnotation(bean.getClass(), ConfigServerConfigurationProperties.class);
// 2. 排除非配置 Bean
if (Objects.isNull(annotation)) {
return bean;
}
// 3. 存在注解开始绑定
bind(bean, beanName, annotation);
return bean;
}
/**
* 属性与系统绑定
*/
private void bind(final Object bean, final String beanName,
final ConfigServerConfigurationProperties annotation) {
// 1. 提取属性
final String dataId = annotation.configKey();
final String groupId = annotation.groupId();
final String type = deduceConfigType(annotation);
final ConfigRefreshCallBack callBack =
(ConfigRefreshCallBack) contextHolder.getContext().getBean(annotation.callbackClazz());
// 2. 解析属性
String content = configServerRepository.getConfig(dataId, groupId);
// 把配置文件塞进属性 (handler) + callback
IConfigParseHandler handler = ConfigParseFactory.acquireHandler(type);
handler.parse(content, bean);
// 3. 自动刷新监听器注册
if (annotation.autoRefreshed()) {
try {
configServerRepository.getConfigService().addListener(dataId, groupId, new AbstractListener() {
final String _beanName = beanName;
final ApplicationContextHolder _contextHolder = contextHolder;
final ConfigRefreshCallBack _callBack = callBack;
final String _type = type;
@Override
public void receiveConfigInfo(String configInfo) {
// 1. 提取配置 Bean
Object originBean = _contextHolder.getContext().getBean(_beanName);
// 2. 提取处理器
IConfigParseHandler handler = ConfigParseFactory.acquireHandler(_type);
// 3. 执行处理
handler.parse(configInfo, originBean);
// 4. 触发回调
_callBack.refresh();
}
});
} catch (NacosException e) {
throw new YoungImException("listener init occur error, config bean is :" + beanName);
}
}
}
/**
* 推断 Config Type
*/
private String deduceConfigType(final ConfigServerConfigurationProperties annotation) {
String type; | package cn.young.im.springboot.starter.adapter.config.bind;
@AllArgsConstructor
public class ConfigServerConfigurationBind implements BeanPostProcessor {
private final ConfigServerRepository configServerRepository;
private final ApplicationContextHolder contextHolder;
/**
* 实例化前对注解进行处理
*/
@Override
public Object postProcessBeforeInitialization(Object bean, @NonNull String beanName) throws BeansException {
// 1. 提取注解
ConfigServerConfigurationProperties annotation =
AnnotationUtils.findAnnotation(bean.getClass(), ConfigServerConfigurationProperties.class);
// 2. 排除非配置 Bean
if (Objects.isNull(annotation)) {
return bean;
}
// 3. 存在注解开始绑定
bind(bean, beanName, annotation);
return bean;
}
/**
* 属性与系统绑定
*/
private void bind(final Object bean, final String beanName,
final ConfigServerConfigurationProperties annotation) {
// 1. 提取属性
final String dataId = annotation.configKey();
final String groupId = annotation.groupId();
final String type = deduceConfigType(annotation);
final ConfigRefreshCallBack callBack =
(ConfigRefreshCallBack) contextHolder.getContext().getBean(annotation.callbackClazz());
// 2. 解析属性
String content = configServerRepository.getConfig(dataId, groupId);
// 把配置文件塞进属性 (handler) + callback
IConfigParseHandler handler = ConfigParseFactory.acquireHandler(type);
handler.parse(content, bean);
// 3. 自动刷新监听器注册
if (annotation.autoRefreshed()) {
try {
configServerRepository.getConfigService().addListener(dataId, groupId, new AbstractListener() {
final String _beanName = beanName;
final ApplicationContextHolder _contextHolder = contextHolder;
final ConfigRefreshCallBack _callBack = callBack;
final String _type = type;
@Override
public void receiveConfigInfo(String configInfo) {
// 1. 提取配置 Bean
Object originBean = _contextHolder.getContext().getBean(_beanName);
// 2. 提取处理器
IConfigParseHandler handler = ConfigParseFactory.acquireHandler(_type);
// 3. 执行处理
handler.parse(configInfo, originBean);
// 4. 触发回调
_callBack.refresh();
}
});
} catch (NacosException e) {
throw new YoungImException("listener init occur error, config bean is :" + beanName);
}
}
}
/**
* 推断 Config Type
*/
private String deduceConfigType(final ConfigServerConfigurationProperties annotation) {
String type; | ConfigType configType = annotation.type(); | 3 | 2023-11-10 06:21:17+00:00 | 4k |
xLorey/FluxLoader | src/main/java/io/xlorey/FluxLoader/server/core/CommandsManager.java | [
{
"identifier": "AccessLevel",
"path": "src/main/java/io/xlorey/FluxLoader/enums/AccessLevel.java",
"snippet": "@Getter\npublic enum AccessLevel {\n /**\n * Highest access level, typically reserved for administrators.\n * This level has the highest priority.\n */\n ADMIN(\"admin\", 5),\n\n /**\n * Access level for moderators, who manage user interactions and content.\n * Priority is lower than ADMIN but higher than OVERSEER.\n */\n MODERATOR(\"moderator\", 4),\n\n /**\n * Access level for overseers, who have oversight capabilities,\n * but fewer privileges than moderators.\n */\n OVERSEER(\"overseer\", 3),\n\n /**\n * Access level for game masters or GMs, who manage game-specific elements.\n * Priority is above OBSERVER but below OVERSEER.\n */\n GM(\"gm\", 2),\n\n /**\n * Observer access level, typically for users with limited privileges,\n * mainly to view or monitor without broader administrative rights.\n */\n OBSERVER(\"observer\", 1),\n\n /**\n * The default access level representing no special privileges.\n * This is the lowest priority level.\n */\n NONE(\"none\", 0);\n\n /**\n * Role name\n */\n private final String roleName;\n /**\n * Access Level Priority\n */\n private final int priority;\n\n /**\n * Constructs an AccessLevel enum with the specified role name and priority.\n *\n * @param roleName the name of the role\n * @param priority the priority of the role for comparison purposes\n */\n AccessLevel(String roleName, int priority) {\n this.roleName = roleName;\n this.priority = priority;\n }\n\n /**\n * Converts a string to the corresponding AccessLevel. Returns NONE if no match is found.\n *\n * @param text the string to convert\n * @return the corresponding AccessLevel\n */\n public static AccessLevel fromString(String text) {\n for (AccessLevel level : AccessLevel.values()) {\n if (level.name().equalsIgnoreCase(text)) {\n return level;\n }\n }\n return NONE;\n }\n}"
},
{
"identifier": "CommandScope",
"path": "src/main/java/io/xlorey/FluxLoader/enums/CommandScope.java",
"snippet": "public enum CommandScope {\n /**\n * Indicates that the command is available for execution only in the chat.\n */\n CHAT,\n\n /**\n * Indicates that the command is available for execution only in the console.\n */\n CONSOLE,\n\n /**\n * Indicates that the command is available for execution in both chat and console.\n */\n BOTH;\n}"
},
{
"identifier": "ICommand",
"path": "src/main/java/io/xlorey/FluxLoader/interfaces/ICommand.java",
"snippet": "public interface ICommand {\n /**\n * Performing a chat command action\n * @param playerConnection player connection, if called from the console, the connection will return as null\n * @param args arguments of the received command\n */\n void onInvoke(UdpConnection playerConnection, String[] args);\n}"
},
{
"identifier": "PlayerUtils",
"path": "src/main/java/io/xlorey/FluxLoader/server/api/PlayerUtils.java",
"snippet": "@UtilityClass\npublic class PlayerUtils {\n /**\n * Returns a player instance on its connection\n * @param udpConnection player connection\n * @return player instance or null if player not found\n */\n public static IsoPlayer getPlayerByUdpConnection(UdpConnection udpConnection) {\n return getPlayerByUsername(udpConnection.username);\n }\n /**\n * Returns the player's IP address.\n * @param player The player instance for which you want to obtain the IP address.\n * @return The player's IP address or null if the address is not found.\n */\n public static String getPlayerIP(IsoPlayer player) {\n UdpConnection playerConnection = GameServer.getConnectionFromPlayer(player);\n return playerConnection != null ? playerConnection.ip : null;\n }\n\n /**\n * Returns the player's SteamID.\n * @param player The player instance for which you want to obtain a SteamID.\n * @return Player's SteamID or null if Steam mode is disabled or SteamID not found.\n */\n public static String getPlayerSteamID(IsoPlayer player) {\n if (SteamUtils.isSteamModeEnabled()) {\n return String.valueOf(player.getSteamID());\n }\n return null;\n }\n\n /**\n * Getting a player instance by nickname\n * @param username player nickname\n * @return IsoPlayer instance, or null if not found\n */\n public static IsoPlayer getPlayerByUsername(String username){\n for (int connectionIndex = 0; connectionIndex < GameServer.udpEngine.connections.size(); ++connectionIndex) {\n UdpConnection connection = GameServer.udpEngine.connections.get(connectionIndex);\n\n for (int playerIndex = 0; playerIndex < 4; ++playerIndex) {\n IsoPlayer player = connection.players[playerIndex];\n if (player != null && (player.getDisplayName().equals(username) || player.getUsername().equals(username))) {\n return player;\n }\n }\n }\n return null;\n }\n\n /**\n * Searches for a player by a full or partial username.\n * @param userName The full or partial name of the player to search for.\n * @return The first IsoPlayer object that matches the given username, or null if no match is found.\n */\n public static IsoPlayer getPlayerByPartialUsername(String userName) {\n for (int connectionIndex = 0; connectionIndex < GameServer.udpEngine.connections.size(); ++connectionIndex) {\n UdpConnection connection = GameServer.udpEngine.connections.get(connectionIndex);\n\n for (int playerIndex = 0; playerIndex < 4; ++playerIndex) {\n IsoPlayer player = connection.players[playerIndex];\n if (player != null) {\n String displayNameLower = player.getDisplayName().toLowerCase();\n String userNameLower = userName.toLowerCase();\n if (displayNameLower.equals(userNameLower) || displayNameLower.startsWith(userNameLower)) {\n return player;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Kick a player from the server\n * @param player Player instance\n * @param reason kick reason\n */\n public void kickPlayer(IsoPlayer player, String reason) {\n if (player == null) return;\n\n EventManager.invokeEvent(\"onPlayerKick\", player, reason);\n\n UdpConnection playerConnection = GameServer.getConnectionFromPlayer(player);\n\n if (playerConnection == null) return;\n\n String kickMessage = String.format(\"You have been kicked from this server by `%s`\", reason);\n GameServer.kick(playerConnection, kickMessage, null);\n playerConnection.forceDisconnect(\"command-kick\");\n\n String logMessage = String.format(\"Player `%s` (IP: %s | SteamID: %s) was kicked from this server for the following reason: `%s`\",\n player.getDisplayName(), playerConnection.ip, player.getSteamID(), reason);\n Logger.printLog(logMessage);\n }\n\n /**\n * Blocking a user by nickname, IP and/or SteamID\n * @param player Player instance\n * @param reason Reason for blocking\n * @param banIP flag whether to block by IP\n * @param banSteamID flag whether to block by SteamID\n */\n public void banPlayer(IsoPlayer player, String reason, boolean banIP, boolean banSteamID) {\n if (player == null) return;\n\n EventManager.invokeEvent(\"onPlayerBan\", player, reason);\n\n UdpConnection playerConnection = GameServer.getConnectionFromPlayer(player);\n\n if (playerConnection == null) return;\n\n ServerWorldDatabase.instance.addUserlog(player.getUsername(), Userlog.UserlogType.Banned, reason, \"Server\", 1);\n\n banByName(player);\n\n if (SteamUtils.isSteamModeEnabled() && banSteamID) banBySteamID(player, reason);\n\n if (banIP) banByIP(playerConnection, player, reason);\n\n String kickMessage = String.format(\"You have been banned from this server for the following reason: `%s`\", reason);\n GameServer.kick(playerConnection, kickMessage, null);\n playerConnection.forceDisconnect(\"command-ban-ip\");\n\n String logMessage = String.format(\"Player `%s` (IP: %s | SteamID: %s) was banned from this server for the following reason: `%s`\",\n player.getDisplayName(), playerConnection.ip, player.getSteamID(), reason);\n Logger.printLog(logMessage);\n }\n\n /**\n * Blocks a player by SteamID\n * @param player Player to block\n * @param reason Reason for blocking\n */\n private void banBySteamID(IsoPlayer player, String reason) {\n String steamID = SteamUtils.convertSteamIDToString(player.getSteamID());\n try {\n ServerWorldDatabase.instance.banSteamID(steamID, reason, true);\n } catch (SQLException e) {\n String errorMessage = String.format(\"Error while ban SteamID: '%s', error: %s\", steamID, e);\n Logger.printLog(errorMessage);\n }\n }\n\n /**\n * Blocks a player by IP address.\n * @param playerConnection Connecting the player to the server.\n * @param player The player to block.\n * @param reason Reason for blocking.\n */\n private void banByIP(UdpConnection playerConnection, IsoPlayer player, String reason) {\n try {\n ServerWorldDatabase.instance.banIp(playerConnection.ip, player.getUsername(), reason, true);\n } catch (SQLException e) {\n String errorMessage = String.format(\"Error while ban IP: '%s', error: %s\", playerConnection.ip, e);\n Logger.printLog(errorMessage);\n }\n }\n\n /**\n * Blocks a player by username.\n * @param player The player to block.\n */\n private void banByName(IsoPlayer player) {\n try {\n ServerWorldDatabase.instance.banUser(player.getUsername(), true);\n } catch (SQLException e) {\n String errorMessage = String.format(\"Error while ban user: '%s', error: %s\", player.getUsername(), e);\n Logger.printLog(errorMessage);\n }\n }\n}"
},
{
"identifier": "Logger",
"path": "src/main/java/io/xlorey/FluxLoader/utils/Logger.java",
"snippet": "@UtilityClass\npublic class Logger {\n /**\n * Outputting a message to the console installer\n * @param text message\n */\n public static void printSystem(String text) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm:ss\");\n String time = LocalDateTime.now().format(formatter);\n System.out.println(String.format(\"<%s> [%s]: %s\", time, Constants.FLUX_NAME, text));\n }\n\n /**\n * Outputting a message to the console/logs\n * @param text message\n */\n public static void printLog(String text) {\n ZLogger fluxLogger = LoggerManager.getLogger(GameServer.bServer ? \"FluxLog-server\" : \"FluxLog-client\");\n fluxLogger.write(text, \"FluxLogger\");\n }\n\n /**\n * Outputting a message to the console/logs\n * @param logger custom logger\n * @param text message\n */\n public static void printLog(ZLogger logger, String text) {\n logger.write(text);\n }\n\n /**\n * Displaying basic information about the project\n */\n public static void printCredits() {\n int width = 50;\n char symbol = '#';\n printFilledLine(symbol, width);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.FLUX_NAME, true);\n printCenteredText(symbol, width, String.format(\"v%s\",Constants.FLUX_VERSION), true);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.GITHUB_LINK, true);\n printCenteredText(symbol, width, Constants.DISCORD_LINK, true);\n printCenteredText(symbol, width, \"\", true);\n printFilledLine(symbol, width);\n\n System.out.println();\n }\n\n /**\n * Display a message in the middle with a given line width\n * @param symbol border symbol\n * @param width line width\n * @param text message\n * @param isBordered use boundaries\n */\n public static void printCenteredText(char symbol, int width, String text, boolean isBordered) {\n String border = isBordered ? String.valueOf(symbol) : \"\";\n int textWidth = text.length() + (isBordered ? 2 : 0);\n int leftPadding = (width - textWidth) / 2;\n int rightPadding = width - leftPadding - textWidth;\n\n String paddedString = String.format(\"%s%\" + leftPadding + \"s%s%\" + rightPadding + \"s%s\", border, \"\", text, \"\", border);\n System.out.println(paddedString);\n }\n\n /**\n * Outputting the completed line to the console\n * @param symbol fill character\n * @param width fill width\n */\n public static void printFilledLine(char symbol, int width) {\n System.out.println(symbol + String.format(\"%\" + (width - 2) + \"s\", \"\").replace(' ', symbol) + symbol);\n }\n}"
}
] | import io.xlorey.FluxLoader.annotations.CommandChatReturn;
import io.xlorey.FluxLoader.annotations.CommandExecutionScope;
import io.xlorey.FluxLoader.annotations.CommandName;
import io.xlorey.FluxLoader.annotations.CommandAccessLevel;
import io.xlorey.FluxLoader.enums.AccessLevel;
import io.xlorey.FluxLoader.enums.CommandScope;
import io.xlorey.FluxLoader.interfaces.ICommand;
import io.xlorey.FluxLoader.server.api.PlayerUtils;
import io.xlorey.FluxLoader.utils.Logger;
import lombok.experimental.UtilityClass;
import zombie.characters.IsoPlayer;
import zombie.core.raknet.UdpConnection;
import java.util.Arrays;
import java.util.HashMap; | 3,389 | package io.xlorey.FluxLoader.server.core;
/**
* A set of tools for handling custom commands
*/
@UtilityClass
public class CommandsManager {
/**
* Repository of all custom commands
*/ | package io.xlorey.FluxLoader.server.core;
/**
* A set of tools for handling custom commands
*/
@UtilityClass
public class CommandsManager {
/**
* Repository of all custom commands
*/ | private static final HashMap<String, ICommand> commandsMap = new HashMap<>(); | 2 | 2023-11-16 09:05:44+00:00 | 4k |
EmonerRobotics/2023Robot | src/main/java/frc/robot/subsystems/LiftSubsystem.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final double GROUNDH = 0;\n public static final double MIDH = 0.46; \n public static final double TOPH = 1.45;\n public static final double HUMANPH = 1.37;\n public static final double LiftAllowedError = 0.005;\n }\n\n public final class IntakeMeasurements{\n public static final double IntakeClosedD = 0;\n public static final double IntakeHalfOpenD = 3.5;\n public static final double IntakeStraightOpenD = 7.6;\n public static final double IntakeStraightOpenHD = 8;\n public static final double IntakeAllowedError = 0.05;\n }\n\n public final class Limelight{\n public static final double BetweenHuman = 0.85;\n }\n\n public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n }\n\n\n public static final class DriveConstants {\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n public static final double MAX_SPEED_METERS_PER_SECOND = 4.8;\n public static final double MAX_ANGULAR_SPEED = 2 * Math.PI; // radians per second\n\n // Chassis configuration\n public static final double TRACK_WIDTH = Units.inchesToMeters(22.5);\n // Distance between centers of right and left wheels on robot\n public static final double WHEEL_BASE = Units.inchesToMeters(24.5);\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics DRIVE_KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(WHEEL_BASE / 2, -TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, -TRACK_WIDTH / 2));\n\n // Angular offsets of the modules relative to the chassis in radians\n public static final double FRONT_LEFT_CHASSIS_ANGULAR_OFFSET = -Math.PI / 2;\n public static final double FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET = 0;\n public static final double REAR_LEFT_CHASSIS_ANGULAR_OFFSET = Math.PI;\n public static final double REAR_RIGHT_CHASSIS_ANGULAR_OFFSET = Math.PI / 2;\n\n // Charge Station Constants\n public static final double CHARGE_TIPPING_ANGLE= Math.toRadians(12);\n public static final double CHARGE_TOLERANCE = Math.toRadians(2.5);\n public static final double CHARGE_MAX_SPEED = 0.8;\n public static final double CHARGE_REDUCED_SPEED = 0.70;\n\n // Delay between reading the gyro and using the value used to aproximate exact angle while spinning (0.02 is one loop)\n public static final double GYRO_READ_DELAY = 0.02;\n\n // SPARK MAX CAN IDs\n public static final int FRONT_LEFT_DRIVING_CAN_ID = 7; //7\n public static final int REAR_LEFT_DRIVING_CAN_ID = 4; //4\n public static final int FRONT_RIGHT_DRIVING_CAN_ID = 10; //10\n public static final int REAR_RIGHT_DRIVING_CAN_ID = 8; //8\n\n public static final int FRONT_LEFT_TURNING_CAN_ID = 2; //2\n public static final int REAR_LEFT_TURNING_CAN_ID = 1; //1\n public static final int FRONT_RIGHT_TURNING_CAN_ID = 3; //3\n public static final int REAR_RIGHT_TURNING_CAN_ID = 6; //6\n\n public static final boolean GYRO_REVERSED = false;\n public static final Rotation3d GYRO_ROTATION = new Rotation3d(0, 0, - Math.PI / 2);\n\n public static final Vector<N3> ODOMETRY_STD_DEV = VecBuilder.fill(0.05, 0.05, 0.01);\n }\n\n\n public static final class ModuleConstants {\n // The MAXSwerve module can be configured with one of three pinion gears: 12T, 13T, or 14T.\n // This changes the drive speed of the module (a pinion gear with more teeth will result in a\n // robot that drives faster).\n public static final int DRIVING_MOTOR_PINION_TEETH = 12;\n\n // Invert the turning encoder, since the output shaft rotates in the opposite direction of\n // the steering motor in the MAXSwerve Module.\n public static final boolean TURNING_ENCODER_INVERTED = true;\n\n // Calculations required for driving motor conversion factors and feed forward\n public static final double DRIVING_MOTOR_FREE_SPEED_RPS = NeoMotorConstants.FREE_SPEED_RPM / 60;\n public static final double WHEEL_DIAMETER_METERS = Units.inchesToMeters(3);\n public static final double WHEEL_CIRCUMFERENCE_METERS = WHEEL_DIAMETER_METERS * Math.PI;\n // 45 teeth on the wheel's bevel gear, 22 teeth on the first-stage spur gear, 15 teeth on the bevel pinion\n public static final double DRIVING_MOTOR_REDUCTION = (45.0 * 22) / (DRIVING_MOTOR_PINION_TEETH * 15);\n public static final double DRIVE_WHEEL_FREE_SPEED_RPS = (DRIVING_MOTOR_FREE_SPEED_RPS * WHEEL_CIRCUMFERENCE_METERS)\n / DRIVING_MOTOR_REDUCTION;\n\n public static final double DRIVING_ENCODER_POSITION_FACTOR = WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION; // meters\n public static final double DRIVING_ENCODER_VELOCITY_FACTOR = (WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION) / 60.0; // meters per second\n\n public static final double TURNING_ENCODER_POSITION_FACTOR = (2 * Math.PI); // radians\n public static final double TURNING_ENCODER_VELOCITY_FACTOR = (2 * Math.PI) / 60.0; // radians per second\n\n public static final double TURNING_ENCODER_POSITION_PID_MIN_INPUT = 0; // radians\n public static final double TURNING_ENCODER_POSITION_PID_MAX_INPUT = TURNING_ENCODER_POSITION_FACTOR; // radians\n\n public static final double DRIVING_P = 0.04;\n public static final double DRIVING_I = 0;\n public static final double DRIVING_D = 0;\n public static final double DRIVING_FF = 1 / DRIVE_WHEEL_FREE_SPEED_RPS;\n public static final double DRIVING_MIN_OUTPUT = -1;\n public static final double DRIVING_MAX_OUTPUT = 1;\n\n public static final double TURNING_P = 2;\n public static final double TURNING_I = 0;\n public static final double TURNING_D = 0;\n public static final double TURNING_FF = 0;\n public static final double TURNING_MIN_OUTPUT = -1;\n public static final double TURNING_MAX_OUTPUT = 1;\n\n public static final CANSparkMax.IdleMode DRIVING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n public static final CANSparkMax.IdleMode TURNING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n\n public static final int DRIVING_MOTOR_CURRENT_LIMIT = 20; // amps\n public static final int TURNING_MOTOR_CURRENT_LIMIT = 15; // amps\n }\n\n public static final class NeoMotorConstants {\n public static final double FREE_SPEED_RPM = 5676;\n }\n\n public static class FieldConstants {\n public static final double fieldLength = Units.inchesToMeters(651.25);\n public static final double fieldWidth = Units.inchesToMeters(315.5);\n public static final double tapeWidth = Units.inchesToMeters(2.0);\n public static final double aprilTagWidth = Units.inchesToMeters(6.0);\n }\n \n public static class VisionConstants {\n // FIXME: actually measure these constants\n\n public static final Transform3d PHOTONVISION_TRANSFORM = new Transform3d(\n new Translation3d(0.205697, -0.244475, 0.267365),\n new Rotation3d(0, Units.degreesToRadians(15), 0)\n );\n\n public static final Vector<N3> PHOTONVISION_STD_DEV = VecBuilder.fill(0.7, 0.7, 0.5);\n\n public static final Vector<N3> LIMELIGHT_STD_DEV = VecBuilder.fill(0.9, 0.9, 0.9);\n\n public static final double AMBIGUITY_FILTER = 0.05;\n }\n\n public static final class AutoConstants {\n public static final HashMap<String, Command> autoEventMap = new HashMap<>();\n public static final double MAX_SPEED_METERS_PER_SECOND = 3;\n public static final double MAX_ACCELERATION_METERS_PER_SECOND_SQUARED = 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND = Math.PI * 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED = Math.PI * 2;\n\n public static final double P_TRANSLATION_PATH_CONTROLLER = 1;\n public static final double P_THETA_PATH_CONTROLLER = 1;\n\n public static final double P_TRANSLATION_POINT_CONTROLLER = 4;\n public static final double P_THETA_POINT_CONTROLLER = 6;\n\n public static final double TRANSLATION_TOLERANCE = 0.02;\n public static final Rotation2d THETA_TOLERANCE = Rotation2d.fromDegrees(1);\n\n // Constraint for the motion profiled robot angle controller\n public static final TrapezoidProfile.Constraints THETA_CONTROLLER_CONSTRAINTS = new TrapezoidProfile.Constraints(\n MAX_ANGULAR_SPEED_RADIANS_PER_SECOND, MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED);\n\n public static final Transform2d NODE_HIGH_TRANSFORM = new Transform2d(\n new Translation2d(-1, 0),\n Rotation2d.fromRadians(Math.PI)\n );\n}\n}"
},
{
"identifier": "IntakeConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n}"
}
] | import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.IntakeConstants; | 3,483 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
public class LiftSubsystem extends SubsystemBase {
private PWMVictorSPX liftMotor;
private Encoder liftEncoder;
public LiftSubsystem() {
//redline motor
liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1);
//lift encoder
liftEncoder = new Encoder(6, 7); //true, EncodingType.k4X
liftEncoder.reset();
}
public void manuelLiftControl(double speed){
liftMotor.set(-speed);
}
public double getEncoderMeters(){
return (liftEncoder.get() * -IntakeConstants.kEncoderTick2Meter);
}
public boolean isAtGround(){ | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
public class LiftSubsystem extends SubsystemBase {
private PWMVictorSPX liftMotor;
private Encoder liftEncoder;
public LiftSubsystem() {
//redline motor
liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1);
//lift encoder
liftEncoder = new Encoder(6, 7); //true, EncodingType.k4X
liftEncoder.reset();
}
public void manuelLiftControl(double speed){
liftMotor.set(-speed);
}
public double getEncoderMeters(){
return (liftEncoder.get() * -IntakeConstants.kEncoderTick2Meter);
}
public boolean isAtGround(){ | double error = getEncoderMeters() - Constants.LiftMeasurements.GROUNDH; | 0 | 2023-11-18 14:02:20+00:00 | 4k |
backend-source/ecommerce-microservice-architecture | shipping-service/src/main/java/com/hoangtien2k3/shippingservice/service/impl/OrderItemServiceImpl.java | [
{
"identifier": "AppConstant",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/constant/AppConstant.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic abstract class AppConstant {\n\n public static final String LOCAL_DATE_FORMAT = \"dd-MM-yyyy\";\n public static final String LOCAL_DATE_TIME_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n public static final String ZONED_DATE_TIME_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n public static final String INSTANT_FORMAT = \"dd-MM-yyyy__HH:mm:ss:SSSSSS\";\n\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public abstract class DiscoveredDomainsApi {\n\n public static final String USER_SERVICE_HOST = \"http://USER-SERVICE/user-service\";\n public static final String USER_SERVICE_API_URL = \"http://USER-SERVICE/user-service/api/users\";\n\n public static final String PRODUCT_SERVICE_HOST = \"http://PRODUCT-SERVICE/product-service\";\n public static final String PRODUCT_SERVICE_API_URL = \"http://localhost:8830/api/products\";\n\n public static final String ORDER_SERVICE_HOST = \"http://ORDER-SERVICE/order-service\";\n public static final String ORDER_SERVICE_API_URL = \"http://localhost:8300/api/orders\";\n\n// public static final String FAVOURITE_SERVICE_HOST = \"http://FAVOURITE-SERVICE/favourite-service\";\n// public static final String FAVOURITE_SERVICE_API_URL = \"http://FAVOURITE-SERVICE/favourite-service/api/favourites\";\n\n public static final String PAYMENT_SERVICE_HOST = \"http://PAYMENT-SERVICE/payment-service\";\n public static final String PAYMENT_SERVICE_API_URL = \"http://PAYMENT-SERVICE/payment-service/api/payments\";\n\n public static final String SHIPPING_SERVICE_HOST = \"http://SHIPPING-SERVICE/shipping-service\";\n public static final String SHIPPING_SERVICE_API_URL = \"http://SHIPPING-SERVICE/shipping-service/api/shippings\";\n\n }\n\n}"
},
{
"identifier": "OrderItemId",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/domain/id/OrderItemId.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\npublic class OrderItemId implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n // primary keys in class properties\n private Integer productId;\n private Integer orderId;\n\n}"
},
{
"identifier": "OrderDto",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/dto/OrderDto.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class OrderDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer orderId;\n\n @JsonSerialize(using = LocalDateTimeSerializer.class)\n @JsonDeserialize(using = LocalDateTimeDeserializer.class)\n @JsonFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT, shape = Shape.STRING)\n @DateTimeFormat(pattern = AppConstant.LOCAL_DATE_TIME_FORMAT)\n private LocalDateTime orderDate;\n private String orderDesc;\n private Double orderFee;\n\n @JsonInclude(Include.NON_NULL)\n private Set<OrderItemDto> orderItemDtos;\n\n}"
},
{
"identifier": "OrderItemDto",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/dto/OrderItemDto.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class OrderItemDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer productId;\n private Integer orderId;\n private Integer orderedQuantity;\n\n @JsonProperty(\"product\")\n @JsonInclude(Include.NON_NULL)\n private ProductDto productDto;\n\n @JsonProperty(\"order\")\n @JsonInclude(Include.NON_NULL)\n private OrderDto orderDto;\n\n}"
},
{
"identifier": "ProductDto",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/dto/ProductDto.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class ProductDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer productId;\n private String productTitle;\n private String imageUrl;\n private String sku;\n private Double priceUnit;\n private Integer quantity;\n\n @JsonInclude(Include.NON_NULL)\n private Set<OrderItemDto> orderItemDtos;\n\n}"
},
{
"identifier": "OrderItemNotFoundException",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/exception/wrapper/OrderItemNotFoundException.java",
"snippet": "public class OrderItemNotFoundException extends RuntimeException {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public OrderItemNotFoundException() {\n super();\n }\n\n public OrderItemNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public OrderItemNotFoundException(String message) {\n super(message);\n }\n\n public OrderItemNotFoundException(Throwable cause) {\n super(cause);\n }\n\n}"
},
{
"identifier": "OrderItemMappingHelper",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/helper/OrderItemMappingHelper.java",
"snippet": "public interface OrderItemMappingHelper {\n\n static OrderItemDto map(final OrderItem orderItem) {\n return OrderItemDto.builder()\n .productId(orderItem.getProductId())\n .orderId(orderItem.getOrderId())\n .orderedQuantity(orderItem.getOrderedQuantity())\n .productDto(\n ProductDto.builder()\n .productId(orderItem.getProductId())\n .build())\n .orderDto(\n OrderDto.builder()\n .orderId(orderItem.getOrderId())\n .build())\n .build();\n }\n\n static OrderItem map(final OrderItemDto orderItemDto) {\n return OrderItem.builder()\n .productId(orderItemDto.getProductId())\n .orderId(orderItemDto.getOrderId())\n .orderedQuantity(orderItemDto.getOrderedQuantity())\n .build();\n }\n\n}"
},
{
"identifier": "OrderItemRepository",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/repository/OrderItemRepository.java",
"snippet": "public interface OrderItemRepository extends JpaRepository<OrderItem, OrderItemId> {\n\n}"
},
{
"identifier": "OrderItemService",
"path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/service/OrderItemService.java",
"snippet": "public interface OrderItemService {\n\n List<OrderItemDto> findAll();\n OrderItemDto findById(final OrderItemId orderItemId);\n OrderItemDto save(final OrderItemDto orderItemDto);\n OrderItemDto update(final OrderItemDto orderItemDto);\n void deleteById(final OrderItemId orderItemId);\n\n}"
}
] | import java.util.List;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import com.hoangtien2k3.shippingservice.constant.AppConstant;
import com.hoangtien2k3.shippingservice.domain.id.OrderItemId;
import com.hoangtien2k3.shippingservice.dto.OrderDto;
import com.hoangtien2k3.shippingservice.dto.OrderItemDto;
import com.hoangtien2k3.shippingservice.dto.ProductDto;
import com.hoangtien2k3.shippingservice.exception.wrapper.OrderItemNotFoundException;
import com.hoangtien2k3.shippingservice.helper.OrderItemMappingHelper;
import com.hoangtien2k3.shippingservice.repository.OrderItemRepository;
import com.hoangtien2k3.shippingservice.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; | 1,851 | package com.hoangtien2k3.shippingservice.service.impl;
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class OrderItemServiceImpl implements OrderItemService {
private final OrderItemRepository orderItemRepository;
private final RestTemplate restTemplate;
@Override | package com.hoangtien2k3.shippingservice.service.impl;
@Service
@Transactional
@Slf4j
@RequiredArgsConstructor
public class OrderItemServiceImpl implements OrderItemService {
private final OrderItemRepository orderItemRepository;
private final RestTemplate restTemplate;
@Override | public List<OrderItemDto> findAll() { | 3 | 2023-11-13 04:24:52+00:00 | 4k |
NewXdOnTop/skyblock-remake | src/main/java/com/sweattypalms/skyblock/core/mobs/regions/end/Zealot.java | [
{
"identifier": "ISkyblockMob",
"path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/ISkyblockMob.java",
"snippet": "public interface ISkyblockMob {\n SkyblockMob getSkyblockMob();\n EntityLiving getEntityInstance();\n}"
},
{
"identifier": "SkyblockMob",
"path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/SkyblockMob.java",
"snippet": "public class SkyblockMob {\n\n @Getter\n public final String id;\n private final Class<? extends ISkyblockMob> nmsClass;\n private final Queue<ArmorStand> damageIndicators = new ConcurrentLinkedQueue<>();\n\n private final Map<MobAttributes, Object> attributes = MobAttributes.getDefault();\n private final Map<NameAttributes, Object> nameAttributes = NameAttributes.getDefault();\n Runnable onSpawn;\n @Getter\n @Setter\n private MobLoot mobLoot;\n @Getter\n @Setter\n private LivingEntity entityInstance;\n @Getter\n private SkyblockPlayer lastDamager;\n\n public SkyblockMob(String id, Class<? extends ISkyblockMob> nmsClass) {\n this.id = id;\n this.nmsClass = nmsClass;\n }\n\n public static SkyblockMob getSkyblockMob(LivingEntity livingEntity) {\n EntityLiving entityLiving = ((CraftLivingEntity) livingEntity).getHandle();\n if (entityLiving instanceof ISkyblockMob skyblockMob) {\n return skyblockMob.getSkyblockMob();\n }\n return null;\n }\n\n public void onSpawn(Runnable onSpawn) {\n this.onSpawn = onSpawn;\n }\n\n public void spawn(Location location) {\n if (entityInstance != null) return;\n\n if (nmsClass == null) return;\n try {\n Constructor<? extends ISkyblockMob> constructor = nmsClass.getConstructor(Location.class, SkyblockMob.class);\n ISkyblockMob _skyblockMob = constructor.newInstance(location, this);\n EntityLiving _entityLiving = _skyblockMob.getEntityInstance();\n\n ((CraftWorld) location.getWorld()).getHandle().addEntity(_entityLiving);\n _entityLiving.setPosition(location.getX(), location.getY(), location.getZ());\n\n this.entityInstance = (LivingEntity) _entityLiving.getBukkitEntity();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n initMob();\n heartbeat();\n\n if (onSpawn != null) onSpawn.run();\n }\n\n private void initMob() {\n LivingEntity entity = this.entityInstance;\n entity.setCustomNameVisible(getNameAttribute(NameAttributes.CUSTOM_NAME_VISIBLE));\n entity.setRemoveWhenFarAway(false);\n entity.setCanPickupItems(false);\n MozangStuff.setAI(entity, getAttribute(MobAttributes.AI_ENABLED));\n entity.setMaximumNoDamageTicks(0);\n entity.setNoDamageTicks(0);\n setEntityInstanceMaxHealth(getAttribute(MobAttributes.MAX_HEALTH));\n }\n\n private void heartbeat() {\n new BukkitRunnable() {\n final SkyblockMob capture = SkyblockMob.this;\n\n @Override\n public void run() {\n if (entityInstance == null || entityInstance.isDead() || entityInstance.getHealth() < 1) {\n capture.despawn();\n cancel();\n return;\n }\n EntityLiving entityLiving = BukkitWrapper.getHandle(entityInstance);\n AttributeInstance healthAttribute = entityLiving.getAttributeInstance(GenericAttributes.maxHealth);\n assert healthAttribute != null;\n healthAttribute.setValue(getAttribute(MobAttributes.MAX_HEALTH));\n\n\n MozangStuff.setAI(entityInstance, getAttribute(MobAttributes.AI_ENABLED));\n\n if (getAttribute(MobAttributes.FROZEN)) {\n PotionEffect _frozenPotionEffect = new PotionEffect(PotionEffectType.SLOW, 15, 255, false, false);\n entityInstance.addPotionEffect(_frozenPotionEffect);\n }\n\n AttributeInstance speedAttribute = entityLiving.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED);\n if (speedAttribute != null)\n speedAttribute.setValue((int) getAttribute(MobAttributes.SPEED) / 500f);\n\n refreshName();\n }\n }.runTaskTimer(SkyBlock.getInstance(), 0, 10);\n }\n\n private void refreshName() {\n String levelComponent = this.getNameAttribute(NameAttributes.SHOW_LEVEL) ? \"$8[$7Lv\" + getAttribute(MobAttributes.LEVEL) + \"$8] \" : \"\";\n\n double maxHealth = getAttribute(MobAttributes.MAX_HEALTH);\n String healthColour =\n entityInstance.getHealth() > maxHealth * 0.66 ? \"$a\" :\n entityInstance.getHealth() > maxHealth * 0.33 ? \"$e\" :\n \"$c\";\n\n\n String formattedHp = healthColour + PlaceholderFormatter.compactNumber((int) entityInstance.getHealth()) + \"$c❤\";\n String noneFormatted =\n healthColour + String.format(\"%.0f\", Math.floor(entityInstance.getHealth())) + \"$f/$a\" + String.format(\"%.0f\", maxHealth) + \"$c❤\";\n\n String customName =\n this.getNameAttribute(NameAttributes.SHOW_HP) ?\n this.getNameAttribute(NameAttributes.FORMATTED) ? formattedHp : noneFormatted\n :\n \"\";\n customName = levelComponent + getNameAttribute(NameAttributes.CUSTOM_NAME) + \" \" + customName;\n\n customName = PlaceholderFormatter.format(customName);\n\n if (this.getNameAttribute(NameAttributes.CUSTOM_NAME_VISIBLE))\n entityInstance.setCustomName(customName);\n }\n\n public void despawn() {\n if (entityInstance == null) return;\n if (!entityInstance.isDead()) {\n entityInstance.setHealth(0);\n }\n entityInstance = null;\n }\n\n /**\n * This is called after the damage calculation is done. Don't call the event again.\n *\n * @param event The event that was called.\n */\n public void damageEntityWithCause(SkyblockPlayerDamageEntityEvent event) {\n if (entityInstance == null) return;\n if (entityInstance.isDead()) return;\n\n SkyblockPlayer skyblockPlayer = event.getSkyblockPlayer();\n double damage = event.getDamage();\n\n // Add checks. Maybe if a specific mob is immune to a damage type. (Use interfaces on the nms classes like IAbilityInvulnerable)\n\n this.lastDamager = skyblockPlayer;\n\n if (entityInstance == null) return;\n\n entityInstance.setLastDamageCause(new EntityDamageEvent(entityInstance, EntityDamageEvent.DamageCause.ENTITY_ATTACK, 0.1));\n\n // To set the last damager\n ((CraftLivingEntity) entityInstance).getHandle().lastDamager = ((CraftPlayer) event.getPlayer()).getHandle();\n\n this.refreshName();\n boolean showCritEffect = event.isCrit();\n if (event.getDamageType() == SkyblockPlayerDamageEntityEvent.DamageType.ABILITY && event.getAbility() instanceof IHasAbilityDamage)\n showCritEffect = false;\n showDamageIndicator(damage, showCritEffect);\n\n double newHealth = entityInstance.getHealth() - damage;\n if (newHealth <= 0) {\n // This will kill the entity, triggering the EntityDeathEvent. which is forwards to the SkyblockDeathEvent.\n entityInstance.setHealth(0);\n } else {\n entityInstance.setHealth(newHealth);\n showDamageEffect(skyblockPlayer);\n }\n }\n\n public void showDamageIndicator(double damage, boolean showCritEffect) {\n double random = Math.random(); // This is for random spawn location\n\n Location spawnLocation = entityInstance.getLocation().add(entityInstance.getLocation().getDirection().multiply(random)).add(0, 1, 0);\n\n if (spawnLocation.getWorld() == null) return;\n\n assert spawnLocation.getWorld() != null;\n\n ArmorStand as = spawnLocation.getWorld().spawn(spawnLocation, ArmorStand.class);\n configureArmorStand(as, damage, showCritEffect);\n int maxAmount = 1;\n if (damageIndicators.size() >= maxAmount) {\n ArmorStand oldest = damageIndicators.poll();\n if (oldest != null && !oldest.isDead()) {\n oldest.remove();\n }\n }\n damageIndicators.add(as);\n\n new BukkitRunnable() {\n public void run() {\n if (!as.isDead()) {\n as.remove();\n }\n damageIndicators.remove(as);\n }\n }.runTaskLater(SkyBlock.getInstance(), 10L);\n }\n\n public void showDamageEffect(SkyblockPlayer player) {\n PacketPlayOutEntityStatus entityStatusPacket = new PacketPlayOutEntityStatus(((CraftLivingEntity) entityInstance).getHandle(), (byte) 2);\n ((CraftPlayer) player.getPlayer()).getHandle().playerConnection.sendPacket(entityStatusPacket);\n }\n\n private void configureArmorStand(ArmorStand armorStand, double damage, boolean showCritEffect) {\n armorStand.setVisible(false);\n String actualDmg = formatDamageString(damage);\n String star = \"§f ✧ \";\n String customName = star + actualDmg + ChatColor.WHITE + \" ✧\";\n if (!showCritEffect) {\n customName = \"§7\" + (int) Math.floor(damage);\n }\n armorStand.setCustomName(customName);\n armorStand.setCustomNameVisible(true);\n armorStand.setArms(false);\n armorStand.setGravity(false);\n armorStand.setVisible(false);\n armorStand.setSmall(true);\n armorStand.setMarker(true);\n EntityArmorStand en = BukkitWrapper.getHandle(armorStand);\n en.n(true);\n }\n\n private String formatDamageString(double damage) {\n String dmg = String.valueOf((int) Math.floor(damage));\n StringBuilder actualDmg = new StringBuilder();\n for (int i = 0; i < dmg.length(); i++) {\n char c = dmg.charAt(i);\n switch (i % 4) {\n case 0 -> actualDmg.append(\"§f\");\n case 1 -> actualDmg.append(\"§e\");\n case 2 -> actualDmg.append(\"§6\");\n case 3 -> actualDmg.append(\"§c\");\n }\n actualDmg.append(c);\n }\n return actualDmg.toString();\n }\n\n public SkyblockMob setCustomName(String customName, boolean formatted) {\n this.setCustomName(customName);\n this.setNameAttribute(NameAttributes.FORMATTED, formatted);\n\n return this;\n }\n\n public SkyblockMob setCustomName(String customName) {\n customName = PlaceholderFormatter.format(customName);\n this.setNameAttribute(NameAttributes.CUSTOM_NAME, customName);\n if (entityInstance != null) {\n entityInstance.setCustomName(customName);\n entityInstance.setCustomNameVisible(true);\n }\n return this;\n }\n\n public SkyblockMob setCustomNameVisible(boolean customNameVisible) {\n this.setNameAttribute(NameAttributes.CUSTOM_NAME_VISIBLE, customNameVisible);\n if (entityInstance != null)\n entityInstance.setCustomNameVisible(customNameVisible);\n return this;\n }\n\n public SkyblockMob setDamage(double damage) {\n this.setAttribute(MobAttributes.DAMAGE, damage);\n return this;\n }\n\n public SkyblockMob setDefense(int defense) {\n this.setAttribute(MobAttributes.DEFENSE, defense);\n return this;\n }\n\n public SkyblockMob setSpeed(int speed) {\n this.setAttribute(MobAttributes.SPEED, speed);\n return this;\n }\n\n public SkyblockMob setLevel(int level) {\n this.setAttribute(MobAttributes.LEVEL, level);\n return this;\n }\n\n public SkyblockMob setMaxHealth(double health) {\n this.setAttribute(MobAttributes.MAX_HEALTH, health);\n if (entityInstance != null)\n setEntityInstanceMaxHealth(health);\n return this;\n }\n\n private void setEntityInstanceMaxHealth(double health) {\n EntityLiving en = BukkitWrapper.getHandle(entityInstance);\n AttributeInstance attributeInstance = en.getAttributeInstance(GenericAttributes.maxHealth);\n assert attributeInstance != null;\n attributeInstance.setValue(health);\n entityInstance.setHealth(health);\n }\n\n public SkyblockMob setDefense(double defense) {\n this.setAttribute(MobAttributes.DEFENSE, defense);\n return this;\n }\n\n public SkyblockMob setSpeed(double speed) {\n this.setAttribute(MobAttributes.SPEED, speed);\n return this;\n }\n\n public <T> SkyblockMob setAttribute(MobAttributes key, T value) {\n if (key.getAttribute().getType().isInstance(value)) {\n attributes.put(key, value);\n } else {\n throw new IllegalArgumentException(\"Value type doesn't match the expected type for the attribute.\");\n }\n return this;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> T getAttribute(MobAttributes key) {\n return (T) attributes.get(key);\n }\n\n public <T> SkyblockMob setNameAttribute(NameAttributes key, T value) {\n if (key.getAttribute().getType().isInstance(value)) {\n nameAttributes.put(key, value);\n } else {\n throw new IllegalArgumentException(\"Value type doesn't match the expected type for the attribute.\");\n }\n return this;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T> T getNameAttribute(NameAttributes key) {\n return (T) nameAttributes.get(key);\n }\n\n public SkyblockMob setLoot(MobLoot mobLoot) {\n this.mobLoot = mobLoot;\n return this;\n }\n}"
}
] | import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob;
import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob;
import net.minecraft.server.v1_8_R3.EntityEnderman;
import net.minecraft.server.v1_8_R3.EntityLiving;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld; | 3,392 | package com.sweattypalms.skyblock.core.mobs.regions.end;
public class Zealot extends EntityEnderman implements ISkyblockMob {
public static final String ID = "zealot"; | package com.sweattypalms.skyblock.core.mobs.regions.end;
public class Zealot extends EntityEnderman implements ISkyblockMob {
public static final String ID = "zealot"; | private final SkyblockMob skyblockMob; | 1 | 2023-11-15 15:05:58+00:00 | 4k |
microsphere-projects/microsphere-i18n | microsphere-i18n-core/src/test/java/io/microsphere/i18n/spring/context/I18nInitializerTest.java | [
{
"identifier": "CompositeServiceMessageSource",
"path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java",
"snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider;\n\n private List<ServiceMessageSource> serviceMessageSources;\n\n public CompositeServiceMessageSource(ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider) {\n super(\"Composite\");\n this.serviceMessageSourcesProvider = serviceMessageSourcesProvider;\n }\n\n @Override\n public void afterSingletonsInstantiated() {\n List<ServiceMessageSource> serviceMessageSources = initServiceMessageSources();\n setServiceMessageSources(serviceMessageSources);\n\n Locale defaultLocale = initDefaultLocale(serviceMessageSources);\n setDefaultLocale(defaultLocale);\n\n List<Locale> supportedLocales = initSupportedLocales(serviceMessageSources);\n setSupportedLocales(supportedLocales);\n }\n\n public void setServiceMessageSources(List<ServiceMessageSource> serviceMessageSources) {\n this.serviceMessageSources = serviceMessageSources;\n logger.debug(\"Source '{}' sets ServiceMessageSource list: {}\", serviceMessageSources);\n }\n\n protected Locale resolveLocale(Locale locale) {\n\n Locale defaultLocale = getDefaultLocale();\n\n if (locale == null || Objects.equals(defaultLocale, locale)) { // If it's the default Locale\n return defaultLocale;\n }\n\n if (supports(locale)) { // If it matches the supported Locale list\n return locale;\n }\n\n Locale resolvedLocale = null;\n\n List<Locale> derivedLocales = resolveDerivedLocales(locale);\n for (Locale derivedLocale : derivedLocales) {\n if (supports(derivedLocale)) {\n resolvedLocale = derivedLocale;\n break;\n }\n }\n\n return resolvedLocale == null ? defaultLocale : resolvedLocale;\n }\n\n @Override\n protected String getInternalMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object... args) {\n String message = null;\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n message = serviceMessageSource.getMessage(resolvedCode, resolvedLocale, args);\n if (message != null) {\n break;\n }\n }\n\n if (message == null) {\n Locale defaultLocale = getDefaultLocale();\n if (!Objects.equals(defaultLocale, resolvedLocale)) { // Use the default Locale as the bottom pocket\n message = getInternalMessage(resolvedCode, resolvedCode, defaultLocale, defaultLocale, args);\n }\n }\n\n return message;\n }\n\n private Locale initDefaultLocale(List<ServiceMessageSource> serviceMessageSources) {\n return serviceMessageSources.isEmpty() ? super.getDefaultLocale() : serviceMessageSources.get(0).getDefaultLocale();\n }\n\n private List<Locale> initSupportedLocales(List<ServiceMessageSource> serviceMessageSources) {\n List<Locale> allSupportedLocales = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n for (Locale supportedLocale : serviceMessageSource.getSupportedLocales()) {\n allSupportedLocales.add(supportedLocale);\n }\n }\n return unmodifiableList(allSupportedLocales);\n }\n\n private List<ServiceMessageSource> initServiceMessageSources() {\n List<ServiceMessageSource> serviceMessageSources = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSourcesProvider) {\n if (serviceMessageSource != this) {\n serviceMessageSources.add(serviceMessageSource);\n }\n }\n AnnotationAwareOrderComparator.sort(serviceMessageSources);\n logger.debug(\"Initializes the ServiceMessageSource Bean list : {}\", serviceMessageSources);\n return unmodifiableList(serviceMessageSources);\n }\n\n @Override\n public String toString() {\n return \"CompositeServiceMessageSource{\" +\n \"serviceMessageSources=\" + serviceMessageSources +\n '}';\n }\n}"
},
{
"identifier": "ServiceMessageSource",
"path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/ServiceMessageSource.java",
"snippet": "public interface ServiceMessageSource {\n\n /**\n * Common internationalizing message sources\n */\n String COMMON_SOURCE = \"common\";\n\n /**\n * Initialize the life cycle\n */\n void init();\n\n /**\n * Destruction life cycle\n */\n void destroy();\n\n /**\n * Getting international Messages\n *\n * @param code message Code\n * @param locale {@link Locale}\n * @param args the argument of message pattern\n * @return 如果获取到,返回器内容,获取不到,返回 <code>null</code>\n */\n @Nullable\n String getMessage(String code, Locale locale, Object... args);\n\n default String getMessage(String code, Object... args) {\n return getMessage(code, getLocale(), args);\n }\n\n /**\n * Get the runtime {@link Locale}\n *\n * @return {@link Locale}\n */\n @NonNull\n default Locale getLocale() {\n Locale locale = LocaleContextHolder.getLocale();\n return locale == null ? getDefaultLocale() : locale;\n }\n\n /**\n * Get the default {@link Locale}\n *\n * @return {@link Locale#SIMPLIFIED_CHINESE} as default\n */\n @NonNull\n default Locale getDefaultLocale() {\n return Locale.SIMPLIFIED_CHINESE;\n }\n\n /**\n * Gets a list of supported {@link Locale}\n *\n * @return Non-null {@link List}, simplified Chinese and English by default\n */\n @NonNull\n default List<Locale> getSupportedLocales() {\n return asList(getDefaultLocale(), Locale.ENGLISH);\n }\n\n /**\n * Message service source\n *\n * @return The application name or {@link #COMMON_SOURCE}\n */\n default String getSource() {\n return COMMON_SOURCE;\n }\n}"
}
] | import io.microsphere.i18n.CompositeServiceMessageSource;
import io.microsphere.i18n.ServiceMessageSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals; | 1,678 | package io.microsphere.i18n.spring.context;
/**
* {@link I18nInitializer} Test
*
* @author <a href="mailto:[email protected]">Mercy<a/>
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = I18nInitializer.class, loader = AnnotationConfigContextLoader.class, classes = I18nInitializerTest.class)
@Configuration
public class I18nInitializerTest {
@Before
public void before() {
LocaleContextHolder.resetLocaleContext();
}
@Autowired
private ServiceMessageSource serviceMessageSource;
@Test
public void test() { | package io.microsphere.i18n.spring.context;
/**
* {@link I18nInitializer} Test
*
* @author <a href="mailto:[email protected]">Mercy<a/>
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = I18nInitializer.class, loader = AnnotationConfigContextLoader.class, classes = I18nInitializerTest.class)
@Configuration
public class I18nInitializerTest {
@Before
public void before() {
LocaleContextHolder.resetLocaleContext();
}
@Autowired
private ServiceMessageSource serviceMessageSource;
@Test
public void test() { | assertEquals(CompositeServiceMessageSource.class, serviceMessageSource.getClass()); | 0 | 2023-11-17 11:35:59+00:00 | 4k |
pyzpre/Create-Bicycles-Bitterballen | src/main/java/createbicyclesbitterballen/index/BlockEntityRegistry.java | [
{
"identifier": "BlockRegistry",
"path": "src/main/java/createbicyclesbitterballen/index/BlockRegistry.java",
"snippet": "public class BlockRegistry {\n\tpublic static final BlockEntry<MechanicalFryer> MECHANICAL_FRYER =\n\t\t\tREGISTRATE.block(\"mechanical_fryer\", MechanicalFryer::new)\n\t\t\t.initialProperties(SharedProperties::copperMetal)\n\t\t\t.properties(p -> p.noOcclusion().strength(2.0f))\n\t\t\t.transform(pickaxeOnly())\n\t\t\t.blockstate(BlockStateGen.horizontalBlockProvider(true))\n\t\t\t.transform(BlockStressDefaults.setImpact(4.0))\n\t\t\t.item(AssemblyOperatorBlockItem::new)\n\t\t\t.transform(customItemModel())\n\t\t\t.register();\n\n\n\n\t\tpublic static void register() {\n\n\t}\n}"
},
{
"identifier": "FryerInstance",
"path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/FryerInstance.java",
"snippet": "public class FryerInstance extends ShaftInstance<MechanicalFryerEntity> implements DynamicInstance {\n\n\n private final RotatingData mixerHead;\n private final OrientedData mixerPole;\n private final MechanicalFryerEntity mixer;\n public FryerInstance(MaterialManager materialManager, MechanicalFryerEntity blockEntity) {\n super(materialManager, blockEntity);\n this.mixer = blockEntity;\n\n mixerHead = materialManager.defaultCutout()\n .material(AllMaterialSpecs.ROTATING)\n .getModel(PartialsRegistry.MECHANICAL_FRYER_HEAD, blockState)\n .createInstance();\n\n mixerHead.setRotationAxis(Direction.Axis.Y);\n\n mixerPole = getOrientedMaterial()\n .getModel(AllPartialModels.MECHANICAL_MIXER_POLE, blockState)\n .createInstance();\n\n\n float renderedHeadOffset = getRenderedHeadOffset();\n\n transformPole(renderedHeadOffset);\n transformHead(renderedHeadOffset);\n }\n\n\n @Override\n public void beginFrame() {\n\n float renderedHeadOffset = getRenderedHeadOffset();\n\n transformPole(renderedHeadOffset);\n transformHead(renderedHeadOffset);\n }\n\n private void transformHead(float renderedHeadOffset) {\n\n\n mixerHead.setPosition(getInstancePosition())\n .nudge(0, -renderedHeadOffset, 0);\n }\n\n private void transformPole(float renderedHeadOffset) {\n mixerPole.setPosition(getInstancePosition())\n .nudge(0, -renderedHeadOffset, 0);\n }\n\n private float getRenderedHeadOffset() {\n return mixer.getRenderedHeadOffset(AnimationTickHolder.getPartialTicks());\n }\n\n @Override\n public void updateLight() {\n super.updateLight();\n\n relight(pos.below(), mixerHead);\n relight(pos, mixerPole);\n }\n\n @Override\n public void remove() {\n super.remove();\n mixerHead.delete();\n mixerPole.delete();\n }\n}"
},
{
"identifier": "MechanicalFryerEntity",
"path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerEntity.java",
"snippet": "public class MechanicalFryerEntity extends BasinOperatingBlockEntity {\n\n private static final Object DeepFryingRecipesKey = new Object();\n\n public int runningTicks;\n public int processingTicks;\n public boolean running;\n\n public MechanicalFryerEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n\n super(type, pos, state);\n }\n\n public float getRenderedHeadOffset(float partialTicks) {\n int localTick;\n float offset = 0;\n if (running) {\n if (runningTicks < 20) {\n localTick = runningTicks;\n float num = (localTick + partialTicks) / 20f;\n num = ((2 - Mth.cos((float) (num * Math.PI))) / 2);\n offset = num - .5f;\n } else if (runningTicks <= 20) {\n offset = 1;\n } else {\n localTick = 40 - runningTicks;\n float num = (localTick - partialTicks) / 20f;\n num = ((2 - Mth.cos((float) (num * Math.PI))) / 2);\n offset = num - .5f;\n }\n }\n return offset + 7 / 16f;\n }\n\n\n\n\n @Override\n protected AABB createRenderBoundingBox() {\n return new AABB(worldPosition).expandTowards(0, -1.5, 0);\n }\n\n @Override\n protected void read(CompoundTag compound, boolean clientPacket) {\n running = compound.getBoolean(\"Running\");\n runningTicks = compound.getInt(\"Ticks\");\n super.read(compound, clientPacket);\n\n if (clientPacket && hasLevel())\n getBasin().ifPresent(bte -> bte.setAreFluidsMoving(running && runningTicks <= 20));\n }\n\n @Override\n public void write(CompoundTag compound, boolean clientPacket) {\n compound.putBoolean(\"Running\", running);\n compound.putInt(\"Ticks\", runningTicks);\n super.write(compound, clientPacket);\n }\n\n @Override\n public void tick() {\n super.tick();\n\n if (runningTicks >= 40) {\n running = false;\n runningTicks = 0;\n basinChecker.scheduleUpdate();\n return;\n }\n\n float speed = Math.abs(getSpeed());\n if (running && level != null) {\n if (level.isClientSide && runningTicks == 20)\n renderParticles();\n\n if ((!level.isClientSide || isVirtual()) && runningTicks == 20) {\n if (processingTicks < 0) {\n float recipeSpeed = 1;\n if (currentRecipe instanceof ProcessingRecipe) {\n int t = ((ProcessingRecipe<?>) currentRecipe).getProcessingDuration();\n if (t != 0)\n recipeSpeed = t / 100f;\n }\n\n processingTicks = Mth.clamp((Mth.log2((int) (512 / speed))) * Mth.ceil(recipeSpeed * 15) + 1, 1, 512);\n\n Optional<BasinBlockEntity> basin = getBasin();\n if (basin.isPresent()) {\n Couple<SmartFluidTankBehaviour> tanks = basin.get()\n .getTanks();\n if (!tanks.getFirst()\n .isEmpty()\n || !tanks.getSecond()\n .isEmpty())\n level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP,\n SoundSource.BLOCKS, .75f, 1.6f);\n }\n\n } else {\n processingTicks--;\n if (processingTicks == 0) {\n runningTicks++;\n processingTicks = -1;\n applyBasinRecipe();\n sendData();\n }\n }\n }\n\n if (runningTicks != 20)\n runningTicks++;\n }\n }\n\n public void renderParticles() {\n Optional<BasinBlockEntity> basin = getBasin();\n if (!basin.isPresent() || level == null)\n return;\n\n for (SmartFluidTankBehaviour behaviour : basin.get()\n .getTanks()) {\n if (behaviour == null)\n continue;\n for (TankSegment tankSegment : behaviour.getTanks()) {\n if (tankSegment.isEmpty(0))\n continue;\n spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid()));\n }\n }\n }\n\n protected void spillParticle(ParticleOptions data) {\n float angle = level.random.nextFloat() * 360;\n Vec3 offset = new Vec3(0, 0, 0.25f);\n offset = VecHelper.rotate(offset, angle, Axis.Y);\n Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y)\n .add(0, .25f, 0);\n Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition));\n target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f);\n level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z);\n }\n\n @Override\n protected List<Recipe<?>> getMatchingRecipes() {\n List<Recipe<?>> matchingRecipes = super.getMatchingRecipes();\n\n\n Optional<BasinBlockEntity> basin = getBasin();\n if (!basin.isPresent())\n return matchingRecipes;\n\n BasinBlockEntity basinBlockEntity = basin.get();\n if (basin.isEmpty())\n return matchingRecipes;\n\n IItemHandler availableItems = basinBlockEntity\n .getCapability(ForgeCapabilities.ITEM_HANDLER)\n .orElse(null);\n if (availableItems == null)\n return matchingRecipes;\n\n return matchingRecipes;\n }\n\n @Override\n protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) {\n return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType();\n }\n\n @Override\n public void startProcessingBasin() {\n if (running && runningTicks <= 20)\n return;\n super.startProcessingBasin();\n running = true;\n runningTicks = 0;\n }\n\n @Override\n public boolean continueWithPreviousRecipe() {\n runningTicks = 20;\n return true;\n }\n\n @Override\n protected void onBasinRemoved() {\n if (!running)\n return;\n runningTicks = 40;\n running = false;\n }\n\n @Override\n protected Object getRecipeCacheKey() {\n return DeepFryingRecipesKey;\n }\n\n @Override\n protected boolean isRunning() {\n return running;\n }\n\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void tickAudio() {\n super.tickAudio();\n\n boolean slow = Math.abs(getSpeed()) < 65;\n if (slow && AnimationTickHolder.getTicks() % 2 == 0)\n return;\n if (runningTicks == 20)\n SoundsRegistry.FRYING.playAt(level, worldPosition, .75f, 1, true);\n }\n\n}"
},
{
"identifier": "MechanicalFryerRenderer",
"path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerRenderer.java",
"snippet": "public class MechanicalFryerRenderer extends ShaftRenderer<MechanicalFryerEntity> {\n\n public MechanicalFryerRenderer(BlockEntityRendererProvider.Context context) {\n super(context);\n }\n\n @Override\n public boolean shouldRenderOffScreen(MechanicalFryerEntity be) {\n return true;\n }\n\n @Override\n protected void renderSafe(MechanicalFryerEntity be, float partialTicks, PoseStack ms, MultiBufferSource buffer,\n int light, int overlay) {\n\n if (Backend.canUseInstancing(be.getLevel())) return;\n\n super.renderSafe(be, partialTicks, ms, buffer, light, overlay);\n\n BlockState blockState = be.getBlockState();\n\n VertexConsumer vb = buffer.getBuffer(RenderType.solid());\n\n float renderedHeadOffset = be.getRenderedHeadOffset(partialTicks);\n\n\n SuperByteBuffer poleRender = CachedBufferer.partial(AllPartialModels.MECHANICAL_MIXER_POLE, blockState);\n poleRender.translate(0, -renderedHeadOffset, 0)\n .light(light)\n .renderInto(ms, vb);\n\n // Render the mixer head\n VertexConsumer vbCutout = buffer.getBuffer(RenderType.cutoutMipped());\n SuperByteBuffer headRender = CachedBufferer.partial(PartialsRegistry.MECHANICAL_FRYER_HEAD, blockState);\n headRender.translate(0, -renderedHeadOffset, 0)\n .light(light)\n .renderInto(ms, vbCutout);\n }\n}"
},
{
"identifier": "REGISTRATE",
"path": "src/main/java/createbicyclesbitterballen/CreateBicBitMod.java",
"snippet": "public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID);"
}
] | import createbicyclesbitterballen.index.BlockRegistry;
import com.tterrag.registrate.util.entry.BlockEntityEntry;
import createbicyclesbitterballen.block.mechanicalfryer.FryerInstance;
import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerEntity;
import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerRenderer;
import static createbicyclesbitterballen.CreateBicBitMod.REGISTRATE; | 3,136 | package createbicyclesbitterballen.index;
public class BlockEntityRegistry {
public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE
.blockEntity("mechanical_fryer", MechanicalFryerEntity::new)
.instance(() -> FryerInstance::new)
.validBlocks(BlockRegistry.MECHANICAL_FRYER) | package createbicyclesbitterballen.index;
public class BlockEntityRegistry {
public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE
.blockEntity("mechanical_fryer", MechanicalFryerEntity::new)
.instance(() -> FryerInstance::new)
.validBlocks(BlockRegistry.MECHANICAL_FRYER) | .renderer(() -> MechanicalFryerRenderer::new) | 3 | 2023-11-12 13:05:18+00:00 | 4k |
HanGyeolee/AndroidPdfWriter | android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/PDFBuilder.java | [
{
"identifier": "BinaryPage",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/binary/BinaryPage.java",
"snippet": "public class BinaryPage {\n int currentNumber = 1;\n\n ArrayList<Bitmap> lists = new ArrayList<>();\n\n int pageCount;\n int pageWidth, pageHeight;\n RectF contentRect;\n\n public BinaryPage(int pageCount, int quality){\n this.pageCount = pageCount;\n BinarySingleton.getInstance().quality = quality;\n }\n\n public void setContentRect(RectF contentRect){\n this.contentRect = contentRect;\n this.pageWidth = Math.round(contentRect.right+contentRect.left);\n this.pageHeight = Math.round(contentRect.bottom+contentRect.top);\n }\n\n public void addBitmap(Bitmap bitmap){\n lists.add(bitmap);\n }\n\n public void saveTo(OutputStream fos){\n StringBuilder tmp;\n byte[] tmp_b;\n\n try {\n BufferedOutputStream bufos = new BufferedOutputStream(fos);\n\n tmp = new StringBuilder();\n tmp.append(\"%PDF-1.4\\n\");\n tmp_b = tmp.toString().getBytes(BinarySingleton.US_ASCII);\n BinarySingleton.getInstance().addXRef(65535, (byte) 'f');\n BinarySingleton.getInstance().byteLength += tmp_b.length + 1;\n bufos.write(tmp_b);\n\n tmp = new StringBuilder();\n tmp.append(\"<</Producer (Gyeolee/APW v\").append(BuildConfig.PUBLISH_VERSION).append(\")>>\");\n tmp_b = addObject(addDictionary(tmp.toString()));\n BinarySingleton.getInstance().addXRef((byte) 'n');\n BinarySingleton.getInstance().byteLength += tmp_b.length;\n bufos.write(tmp_b);\n\n int PagesNumber = currentNumber+1;\n tmp = new StringBuilder();\n tmp.append(\"<< /Type /Catalog\\n\")\n .append(\"/Pages \").append(PagesNumber).append(\" 0 R>>\");\n tmp_b = addObject(addDictionary(tmp.toString()));\n BinarySingleton.getInstance().addXRef((byte) 'n');\n BinarySingleton.getInstance().byteLength += tmp_b.length;\n // 1 0 obj Catalog\n bufos.write(tmp_b);\n\n tmp = new StringBuilder();\n tmp.append(\"<< /Type /Pages\\n\")\n .append(\"/Count \").append(pageCount).append('\\n')\n .append(\"/Kids [\");\n\n int objNumber = PagesNumber+1;\n for(int i = 0; i < lists.size(); i ++){\n objNumber = measurePageNumber(objNumber);\n tmp.append(objNumber).append(\" 0 R\\n\");\n objNumber += 1;\n }\n\n tmp.append(\"]>>\");\n tmp_b = addObject(addDictionary(tmp.toString()));\n BinarySingleton.getInstance().addXRef((byte) 'n');\n BinarySingleton.getInstance().byteLength += tmp_b.length;\n // 2 0 obj Pages\n bufos.write(tmp_b);\n\n objNumber = PagesNumber+1;\n for(int i = 0; i < lists.size(); i ++){\n BinaryImage image = new BinaryImage(objNumber, lists.get(i), pageWidth, pageHeight);\n bufos.write(image.getContentOfPage(contentRect, PagesNumber));\n objNumber = image.currentNumber;\n }\n currentNumber = objNumber;\n\n tmp = new StringBuilder();\n tmp.append(\"xref\\n\")\n .append(\"0 \").append(BinarySingleton.getInstance().getLengthXref()).append(\"\\n\");\n tmp_b = tmp.toString().getBytes(BinarySingleton.US_ASCII);\n bufos.write(tmp_b);\n\n for(XRef b: BinarySingleton.getInstance().XRefs){\n bufos.write(b.write());\n }\n\n tmp = new StringBuilder();\n tmp.append(\"trailer\\n\")\n .append(\"<< /Size \").append(BinarySingleton.getInstance().getLengthXref()).append(\"\\n\")\n .append(\"/Info 1 0 R\\n\")\n .append(\"/Root 2 0 R\\n>>\\n\")\n .append(\"startxref\\n\")\n .append(BinarySingleton.getInstance().byteLength);\n tmp_b = tmp.toString().getBytes(BinarySingleton.US_ASCII);\n bufos.write(tmp_b);\n\n bufos.write(\"\\n%%EOF\".getBytes(BinarySingleton.US_ASCII));\n\n bufos.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n for(int i = 0; i < lists.size(); i++){\n if(lists.get(i) != null) {\n lists.get(i).recycle();\n }\n }\n lists.clear();\n }\n\n private int measurePageNumber(int objNumber){\n return objNumber+2;\n }\n private byte[] addDictionary(String s){\n return s.getBytes(BinarySingleton.US_ASCII);\n }\n private byte[] addObject(byte[] data){\n StringBuilder start = new StringBuilder();\n // {객체 번호} {세대 번호} obj\n start.append(currentNumber).append(\" \").append(0).append(\" obj\\n\");\n byte[] start_b = start.toString().getBytes(BinarySingleton.US_ASCII);\n\n StringBuilder end = new StringBuilder();\n end.append(\"\\nendobj\\n\");\n byte[] end_b = end.toString().getBytes(BinarySingleton.US_ASCII);\n\n byte[] re = new byte[start_b.length + data.length + end_b.length];\n\n int i = 0;\n for(int j = 0; j < start_b.length; j++, i++){\n re[i] = start_b[j];\n }\n for(int j = 0; j < data.length; j++, i++){\n re[i] = data[j];\n }\n for(int j = 0; j < end_b.length; j++, i++){\n re[i] = end_b[j];\n }\n currentNumber += 1;\n return re;\n }\n\n @Override\n protected void finalize() throws Throwable {\n for(int i = 0; i < lists.size(); i++){\n if(lists.get(i) != null) {\n lists.get(i).recycle();\n }\n }\n lists.clear();\n super.finalize();\n }\n}"
},
{
"identifier": "PDFLayout",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFLayout.java",
"snippet": "public abstract class PDFLayout extends PDFComponent{\n ArrayList<PDFComponent> child;\n\n public PDFLayout(){super();}\n\n @Override\n public void measure(float x, float y) {\n super.measure(x, y);\n\n // 레이아웃은 Anchor를 적용하지 않는 다.\n float d = 0;\n if (parent != null)\n d += parent.measureX + parent.border.size.left + parent.padding.left;\n measureX = relativeX + margin.left + d;\n d = 0;\n if (parent != null)\n d += parent.measureY + parent.border.size.top + parent.padding.top;\n measureY = relativeY + margin.top + d;\n }\n\n /**\n * 레이아웃에 자식 추가<br>\n * Add children to layout\n * @param component 자식 컴포넌트\n * @return 자기자신\n */\n public PDFLayout addChild(PDFComponent component){\n component.setParent(this);\n child.add(component);\n return this;\n }\n}"
},
{
"identifier": "DPI",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/DPI.java",
"snippet": "public class DPI {\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({D2, Standard, M2, M4, M5, M8, M10})\n public @interface DPIInt {}\n public static final int D2 = 36;\n /**\n * PDF 파일의 기본 DPI <br>\n * Default DPI in PDF file\n */\n public static final int Standard = 72;\n public static final int M2 = 144;\n public static final int M4 = 288;\n public static final int M5 = 360;\n public static final int M8 = 576;\n public static final int M10 = 720;\n}"
},
{
"identifier": "Paper",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Paper.java",
"snippet": "public enum Paper{\n // 840 x1188mm\n A0(2381.103648f,3367.5608736f),\n // 594 x840mm\n A1(1683.7804368f,2381.103648f),\n // 420 x594mm\n A2(1190.551824f,1683.7804368f),\n // 297 x420mm\n A3(841.8902184f,1190.551824f),\n // 210 x297mm\n A4(595.275912f, 841.8902184f),\n // 148.5x210mm\n A5(595.275912f, 841.8902184f),\n // 1028 1456\n B0(2914.0173216f, 4127.2463232f),\n // 728 1028\n B1(2063.6231616f, 2914.0173216f),\n // 514 728\n B2(1457.0086608f, 2063.6231616f),\n // 364 514\n B3(1031.8115808f, 1457.0086608f),\n // 257 364\n B4(728.5043304f, 1031.8115808f),\n // 182 x257mm\n B5(515.9057904f, 728.5043304f),\n // 8.5 X11inch\n Letter(612f, 792f),\n // 8.5 X14inch\n Legal(612f, 1008f);\n //*2.8346472\n\n private float width;\n private float height;\n\n Paper(float width, float height){\n this.width = width;\n this.height = height;\n }\n\n public void setCustom(float width, float height){\n this.width = width;\n this.height = height;\n }\n\n public float getHeight() {\n return height;\n }\n\n public float getWidth() {\n return width;\n }\n\n public Paper Landscape(){\n float w = getWidth();\n width = getHeight();\n height = w;\n return this;\n }\n}"
},
{
"identifier": "StandardDirectory",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/StandardDirectory.java",
"snippet": "public class StandardDirectory {\n @Retention(RetentionPolicy.SOURCE)\n @StringDef({\n DIRECTORY_MUSIC,\n DIRECTORY_PODCASTS,\n DIRECTORY_RINGTONES,\n DIRECTORY_ALARMS,\n DIRECTORY_NOTIFICATIONS,\n DIRECTORY_PICTURES,\n DIRECTORY_MOVIES,\n DIRECTORY_DOWNLOADS,\n DIRECTORY_DCIM,\n DIRECTORY_DOCUMENTS,\n DIRECTORY_AUDIOBOOKS,\n })\n public @interface DirectoryString {}\n\n public static final String DIRECTORY_MUSIC = \"Music\";\n public static final String DIRECTORY_PODCASTS = \"Podcasts\";\n public static final String DIRECTORY_RINGTONES = \"Ringtones\";\n public static final String DIRECTORY_ALARMS = \"Alarms\";\n public static final String DIRECTORY_NOTIFICATIONS = \"Notifications\";\n public static final String DIRECTORY_PICTURES = \"Pictures\";\n public static final String DIRECTORY_MOVIES = \"Movies\";\n public static final String DIRECTORY_DOWNLOADS = \"Download\";\n public static final String DIRECTORY_DCIM = \"DCIM\";\n @RequiresApi(api = Build.VERSION_CODES.KITKAT)\n public static final String DIRECTORY_DOCUMENTS = \"Documents\";\n @RequiresApi(api = Build.VERSION_CODES.Q)\n public static final String DIRECTORY_AUDIOBOOKS = \"Audiobooks\";\n\n public static final String[] STANDARD_DIRECTORIES = {\n DIRECTORY_MUSIC,\n DIRECTORY_PODCASTS,\n DIRECTORY_RINGTONES,\n DIRECTORY_ALARMS,\n DIRECTORY_NOTIFICATIONS,\n DIRECTORY_PICTURES,\n DIRECTORY_MOVIES,\n DIRECTORY_DOWNLOADS,\n DIRECTORY_DCIM,\n DIRECTORY_DOCUMENTS,\n DIRECTORY_AUDIOBOOKS,\n };\n\n public static boolean isStandardDirectory(String dir) {\n for (String valid : STANDARD_DIRECTORIES) {\n if (valid.equals(dir)) {\n return true;\n }\n }\n return false;\n }\n}"
},
{
"identifier": "Zoomable",
"path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Zoomable.java",
"snippet": "public class Zoomable {\n private static Zoomable instance = null;\n\n public static Zoomable getInstance(){\n if(instance == null){\n instance = new Zoomable();\n }\n return instance;\n }\n\n /**\n * PDF 내에 들어가는 요소를 전부 이미지로 변환 후 집어 넣기 때문에<br>\n * density 를 통해 전체적으로 이미지 파일 크기 자체를 키워서<br>\n * 디바이스에 구애 받지 않고 dpi 를 늘리는 효과를 만든다. <br>\n * Since all elements in the PDF are converted into images and inserted,<br>\n * Through density, the image file size itself is increased as a whole,<br>\n * creating the effect of increasing dpi regardless of device.\n */\n public float density = 1.0f;\n\n private RectF contentRect = null;\n\n public void setContentRect(RectF contentRect){\n this.contentRect = contentRect;\n }\n\n public RectF getContentRect() {\n return contentRect;\n }\n public float getZoomWidth() {\n return contentRect.width() * density;\n }\n public float getZoomHeight() {\n return contentRect.height() * density;\n }\n}"
}
] | import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import com.hangyeolee.androidpdfwriter.binary.BinaryPage;
import com.hangyeolee.androidpdfwriter.components.PDFLayout;
import com.hangyeolee.androidpdfwriter.utils.DPI;
import com.hangyeolee.androidpdfwriter.utils.Paper;
import com.hangyeolee.androidpdfwriter.utils.StandardDirectory;
import com.hangyeolee.androidpdfwriter.utils.Zoomable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Provider;
import java.util.Locale; | 3,538 | package com.hangyeolee.androidpdfwriter;
public class PDFBuilder<T extends PDFLayout> {
int quality = 60; | package com.hangyeolee.androidpdfwriter;
public class PDFBuilder<T extends PDFLayout> {
int quality = 60; | BinaryPage page; | 0 | 2023-11-15 08:05:28+00:00 | 4k |
Ghost-chu/CustomClientDNS | src/main/java/com/ghostchu/mods/customclientdns/CustomClientDNS.java | [
{
"identifier": "DNSConfig",
"path": "src/main/java/com/ghostchu/mods/customclientdns/config/DNSConfig.java",
"snippet": "public class DNSConfig {\n private boolean useLocalDnsServer = true;\n private List<String> customizedDNSResolver = new ArrayList<>(List.of(\n \"https://dns.alidns.com/dns-query\",\n \"https://dot.pub/dns-query\",\n \"223.5.5.5\",\n \"119.29.29.29\",\n \"114.114.114.114\",\n \"1.1.1.1\",\n \"8.8.8.8\"));\n\n public DNSConfig(YamlConfiguration configuration) {\n this.useLocalDnsServer = configuration.getBoolean(\"use-local-dns-server\");\n this.customizedDNSResolver = configuration.getStringList(\"customized-dns-resolvers\");\n }\n\n public DNSConfig() {\n }\n\n public List<String> getCustomizedDNSResolver() {\n return customizedDNSResolver;\n }\n\n public boolean isUseLocalDnsServer() {\n return useLocalDnsServer;\n }\n\n public YamlConfiguration createConfiguration() {\n YamlConfiguration yamlConfiguration = new YamlConfiguration();\n yamlConfiguration.set(\"use-local-dns-server\", this.useLocalDnsServer);\n yamlConfiguration.setComments(\"use-local-dns-server\",\n List.of(\"This configuration item allows you to configure whether or not to use the local DNS settings of the user's computer system.\",\n \"When set to false, the system's local DNS is ignored and only the DNS servers configured by the Mod are used.\")\n );\n yamlConfiguration.set(\"customized-dns-resolvers\", this.customizedDNSResolver);\n yamlConfiguration.setComments(\"customized-dns-resolvers\",\n List.of(\"This configuration item allows you to add a custom DNS server that has a higher priority than the user system's local DNS settings.\"));\n return yamlConfiguration;\n }\n}"
},
{
"identifier": "DNSLookupHelper",
"path": "src/main/java/com/ghostchu/mods/customclientdns/dns/DNSLookupHelper.java",
"snippet": "public class DNSLookupHelper {\n private static final Logger LOG = LoggerFactory.getLogger(\"DNSLookupHelper\");\n private static final int DEFAULT_PORT = 25565;\n private static final String SRV_STR = \"_minecraft._tcp.\";\n private String ipAddress = \"\";\n private String hostName = \"\";\n private int port = 0;\n\n public DNSLookupHelper(String hostName, int port) throws\n UnknownHostException {\n this.resolve(hostName, port);\n }\n\n public DNSLookupHelper(String hostName) throws\n UnknownHostException {\n this.resolve(hostName, 0);\n }\n\n private void resolve(String hostName, int port) throws\n UnknownHostException {\n // check whether the port is encoded within the hostname string\n String[] parts = hostName.split(\":\");\n if (parts.length > 2) {\n StringJoiner partsHosts = new StringJoiner(\":\");\n for (int i = 0; i < parts.length; i++) {\n partsHosts.add(parts[i]);\n if (i + 1 >= parts.length - 1) {\n break;\n }\n }\n String partsPort = parts[parts.length - 1];\n String partsHost = partsHosts.toString();\n parts = new String[2];\n parts[0] = partsHost;\n parts[1] = partsPort;\n }\n if (parts.length > 1) {\n this.hostName = parts[0];\n try {\n this.port = Integer.parseInt(parts[1]);\n } catch (NumberFormatException e) {\n LOG.debug(\"Invalid port within hostname '{}' provided, use port from second parameter '{}'\", hostName, port);\n this.port = port;\n }\n } else {\n this.hostName = hostName;\n this.port = port;\n }\n\n if (!IPAddressMatcher.isIPAddress(this.hostName) &&\n !Objects.equals(this.hostName, InetAddress.getLocalHost().getHostName()) &&\n this.port == 0) {\n // input is an hostname, but no port submitted, try to resolve via SRV record\n try {\n SRVRecord srvRecord = (SRVRecord) lookupRecord(SRV_STR + hostName, Type.SRV);\n this.hostName = srvRecord.getTarget().toString().replaceFirst(\"\\\\.$\", \"\");\n this.port = srvRecord.getPort();\n } catch (UnknownHostException e) {\n // no SRV record found at the moment, just continue\n }\n }\n\n if (IPAddressMatcher.isIPAddress(this.hostName)) {\n // hostname provided is a IP address\n this.ipAddress = this.hostName;\n } else {\n // hostname provided is an actual hostname, resolve IP address\n try {\n this.ipAddress = ((ARecord) lookupRecord(this.hostName, Type.A)).getAddress().getHostAddress();\n } catch (UnknownHostException e) {\n this.ipAddress = ((AAAARecord) lookupRecord(this.hostName, Type.AAAA)).getAddress().getHostAddress();\n }\n }\n\n if (this.port == 0) {\n // couldn't resolve via SVR record, therefore use default minecraft port\n this.port = DEFAULT_PORT;\n }\n }\n\n private Record lookupRecord(String hostName, int type) throws\n UnknownHostException {\n\n Record record;\n Lookup lookup;\n int result;\n\n try {\n lookup = new Lookup(hostName, type);\n } catch (TextParseException e) {\n throw new UnknownHostException(String.format(\"Host '%s' parsing error:%s\", hostName, e.getMessage()));\n }\n\n lookup.run();\n\n result = lookup.getResult();\n\n if (result == Lookup.SUCCESSFUL) {\n record = lookup.getAnswers()[0];\n LOG.info(\"Successfully got DNS record of type '{}' for hostname '{}': '{}'\", Type.string(type), hostName, record);\n } else {\n LOG.debug(\"Failed to get DNS record of type '{}' for hostname '{}'\", type, hostName);\n\n switch (result) {\n case Lookup.HOST_NOT_FOUND:\n throw new UnknownHostException(String.format(\"Host '%s' not found\", hostName));\n case Lookup.TYPE_NOT_FOUND:\n throw new UnknownHostException(String.format(\"Host '%s' not found (no A record)\", hostName));\n case Lookup.UNRECOVERABLE:\n throw new UnknownHostException(String.format(\"Cannot lookup host '%s'\", hostName));\n case Lookup.TRY_AGAIN:\n throw new UnknownHostException(String.format(\"Temporary failure to lookup host '%s'\", hostName));\n default:\n throw new UnknownHostException(String.format(\"Unknown error %d in host lookup of '%s'\", result, hostName));\n }\n }\n\n return record;\n }\n\n\n public int getPort() {\n return this.port;\n }\n\n public String getHostName() {\n return this.hostName;\n }\n\n public String getIpAddress() {\n return this.ipAddress;\n }\n\n @Override\n public String toString() {\n return \"DNSLookupHelper{\" +\n \"ipAddress='\" + ipAddress + '\\'' +\n \", hostName='\" + hostName + '\\'' +\n \", port=\" + port +\n '}';\n }\n}"
}
] | import com.ghostchu.mods.customclientdns.config.DNSConfig;
import com.ghostchu.mods.customclientdns.dns.DNSLookupHelper;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.impl.FabricLoaderImpl;
import org.bspfsystems.yamlconfiguration.file.YamlConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.*;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List; | 2,023 | package com.ghostchu.mods.customclientdns;
public class CustomClientDNS implements ModInitializer {
public DNSConfig DNS_CONFIG;
public static CustomClientDNS INSTANCE;
private static final Logger LOGGER = LoggerFactory.getLogger("CustomClientDNS");
/**
* Runs the mod initializer.
*/
@Override
public void onInitialize() {
INSTANCE = this;
try {
DNS_CONFIG = loadConfig();
} catch (IOException e) {
throw new RuntimeException(e); // Crash the game if files failed to create to avoid silent failure
}
setupDNSResolver(DNS_CONFIG);
selfTest();
}
private void selfTest() {
List<String> testList = List.of(
"github.com",
"hypixel.net",
"google.com",
"cloudflare.com",
"minecrafr.net",
"mojang.com"
);
testList.parallelStream().forEach(s -> {
try { | package com.ghostchu.mods.customclientdns;
public class CustomClientDNS implements ModInitializer {
public DNSConfig DNS_CONFIG;
public static CustomClientDNS INSTANCE;
private static final Logger LOGGER = LoggerFactory.getLogger("CustomClientDNS");
/**
* Runs the mod initializer.
*/
@Override
public void onInitialize() {
INSTANCE = this;
try {
DNS_CONFIG = loadConfig();
} catch (IOException e) {
throw new RuntimeException(e); // Crash the game if files failed to create to avoid silent failure
}
setupDNSResolver(DNS_CONFIG);
selfTest();
}
private void selfTest() {
List<String> testList = List.of(
"github.com",
"hypixel.net",
"google.com",
"cloudflare.com",
"minecrafr.net",
"mojang.com"
);
testList.parallelStream().forEach(s -> {
try { | LOGGER.info("[Self-Test] DNS lookup for {}: {} ", s, new DNSLookupHelper(s)); | 1 | 2023-11-17 17:56:41+00:00 | 4k |
frc-7419/SwerveBase | src/main/java/frc/robot/subsystems/drive/DriveBaseSubsystem.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n public static class SwerveConstants {\n /*\n * IMPORTANT: THIS WAS FOUND THROUGH CAD FILES BUT THERE ARE MANY SWERVE X CONFIGURATIONS\n * SO YOU NEED TO DOUBLE CHECK THIS IS CORRECT IN PRACTICE\n */\n /* ANGLE MOTOR\n * NEO Shaft to 12T Pulley to 24T Pulley to 14T Gear to 72T Main Rotation Gear\n */\n public static final double kGearRatioAngleMotor = 12.0/24.0*14.0/72.0;\n /* DRIVE MOTOR\n * NEO shaft to 12T Pulley to 24T Pulley to 24T Gear to 22T Gear to 15T bevel to 45T Bevel\n *\n * The CANCODER measures rotations of a the driven 1:1 PULLEY in which the driver pulley is on the same\n * shaft as the 24T Pulley\n */\n public static final double kSpeedMotorGearRatio = 12.0/24.0* 24.0/22.0 * 15.0/45.0;\n public static final double LENGTH = Units.inchesToMeters(26.5);\n public static final double HALF_LENGTH = LENGTH/2.0;\n //Not sure how to calculate this theoretically but this needs to be determined experimentally first\n //Neo Free-Speed 13.16 ft/s 15.68 ft/s 18.66 ft/s\n public static final double kMaxTranslationalSpeed = Units.feetToMeters(3);\n //arbitrary value in radians, let's say one pi/second\n public static final double kMaxRotationalSpeed = Math.PI/4;\n public static final double kWheelDiameter = Units.inchesToMeters(3.5);\n public static final double kWheelCircumfrence = kWheelDiameter * Math.PI;\n public static final double anglekP = 0.002;\n public static final double anglekI = 0;\n public static final double anglekD = 0;\n\n \n //INFO: according to WPILib docs \"The locations for the modules must be relative to the center of the robot. Positive x\n //values represent moving toward the front of the robot whereas positive y values represent moving toward the left of the robot.\" \n public static final SwerveModuleConstants frontLeft = new SwerveModuleConstants(2, 1, 9, 102.39,\n new Translation2d(SwerveConstants.HALF_LENGTH, SwerveConstants.HALF_LENGTH) );\n public static final SwerveModuleConstants frontRight = new SwerveModuleConstants(4, 3, 10, 189.94,\n new Translation2d(SwerveConstants.HALF_LENGTH, -SwerveConstants.HALF_LENGTH));\n public static final SwerveModuleConstants backLeft = new SwerveModuleConstants(8, 7, 12, 161.63,\n new Translation2d(-SwerveConstants.HALF_LENGTH, SwerveConstants.HALF_LENGTH));\n public static final SwerveModuleConstants backRight = new SwerveModuleConstants(6, 5,11, 246.09,\n new Translation2d(-SwerveConstants.HALF_LENGTH, -SwerveConstants.HALF_LENGTH));\n public static final SwerveDriveKinematics m_SwerveDriveKinematics = new SwerveDriveKinematics(SwerveConstants.frontLeft.location, SwerveConstants.frontRight.location, SwerveConstants.backLeft.location, SwerveConstants.backRight.location);\n }\n\n public static class SwerveModuleConstants {\n public final int driveMotorID;\n public final int turnMotorID;\n public final int turnEncoderID;\n public final double offset;\n public final Translation2d location;\n public static final double kMaxTurningSpeed = 0.3;\n \n public SwerveModuleConstants(int driveMotorID, int turnMotorID, int turnEncoderID, double offset, Translation2d location) {\n this.driveMotorID = driveMotorID;\n this.turnMotorID = turnMotorID;\n this.turnEncoderID = turnEncoderID;\n this.offset = offset;\n this.location = location;\n } \n }\n}"
},
{
"identifier": "SwerveConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static class SwerveConstants {\n /*\n * IMPORTANT: THIS WAS FOUND THROUGH CAD FILES BUT THERE ARE MANY SWERVE X CONFIGURATIONS\n * SO YOU NEED TO DOUBLE CHECK THIS IS CORRECT IN PRACTICE\n */\n /* ANGLE MOTOR\n * NEO Shaft to 12T Pulley to 24T Pulley to 14T Gear to 72T Main Rotation Gear\n */\n public static final double kGearRatioAngleMotor = 12.0/24.0*14.0/72.0;\n /* DRIVE MOTOR\n * NEO shaft to 12T Pulley to 24T Pulley to 24T Gear to 22T Gear to 15T bevel to 45T Bevel\n *\n * The CANCODER measures rotations of a the driven 1:1 PULLEY in which the driver pulley is on the same\n * shaft as the 24T Pulley\n */\n public static final double kSpeedMotorGearRatio = 12.0/24.0* 24.0/22.0 * 15.0/45.0;\n public static final double LENGTH = Units.inchesToMeters(26.5);\n public static final double HALF_LENGTH = LENGTH/2.0;\n //Not sure how to calculate this theoretically but this needs to be determined experimentally first\n //Neo Free-Speed 13.16 ft/s 15.68 ft/s 18.66 ft/s\n public static final double kMaxTranslationalSpeed = Units.feetToMeters(3);\n //arbitrary value in radians, let's say one pi/second\n public static final double kMaxRotationalSpeed = Math.PI/4;\n public static final double kWheelDiameter = Units.inchesToMeters(3.5);\n public static final double kWheelCircumfrence = kWheelDiameter * Math.PI;\n public static final double anglekP = 0.002;\n public static final double anglekI = 0;\n public static final double anglekD = 0;\n\n \n //INFO: according to WPILib docs \"The locations for the modules must be relative to the center of the robot. Positive x\n //values represent moving toward the front of the robot whereas positive y values represent moving toward the left of the robot.\" \n public static final SwerveModuleConstants frontLeft = new SwerveModuleConstants(2, 1, 9, 102.39,\n new Translation2d(SwerveConstants.HALF_LENGTH, SwerveConstants.HALF_LENGTH) );\n public static final SwerveModuleConstants frontRight = new SwerveModuleConstants(4, 3, 10, 189.94,\n new Translation2d(SwerveConstants.HALF_LENGTH, -SwerveConstants.HALF_LENGTH));\n public static final SwerveModuleConstants backLeft = new SwerveModuleConstants(8, 7, 12, 161.63,\n new Translation2d(-SwerveConstants.HALF_LENGTH, SwerveConstants.HALF_LENGTH));\n public static final SwerveModuleConstants backRight = new SwerveModuleConstants(6, 5,11, 246.09,\n new Translation2d(-SwerveConstants.HALF_LENGTH, -SwerveConstants.HALF_LENGTH));\n public static final SwerveDriveKinematics m_SwerveDriveKinematics = new SwerveDriveKinematics(SwerveConstants.frontLeft.location, SwerveConstants.frontRight.location, SwerveConstants.backLeft.location, SwerveConstants.backRight.location);\n}"
}
] | import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.wpilibj.SerialPort;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.Constants.SwerveConstants;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; | 2,120 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.drive;
public class DriveBaseSubsystem extends SubsystemBase {
private final SwerveDriveOdometry m_odometry;
private final SwerveModule frontLeftModule;
private final SwerveModule frontRightModule;
private final SwerveModule backLeftModule;
private final SwerveModule backRightModule;
private final AHRS ahrs;
public DriveBaseSubsystem() { | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems.drive;
public class DriveBaseSubsystem extends SubsystemBase {
private final SwerveDriveOdometry m_odometry;
private final SwerveModule frontLeftModule;
private final SwerveModule frontRightModule;
private final SwerveModule backLeftModule;
private final SwerveModule backRightModule;
private final AHRS ahrs;
public DriveBaseSubsystem() { | frontLeftModule = new SwerveModule(SwerveConstants.frontLeft.turnMotorID, SwerveConstants.frontLeft.driveMotorID, SwerveConstants.frontLeft.turnEncoderID, SwerveConstants.frontLeft.offset, "FrontLeftModule"); | 1 | 2023-11-17 04:37:58+00:00 | 4k |
SoBadFish/Report | src/main/java/org/sobadfish/report/form/DisplayCustomForm.java | [
{
"identifier": "ReportMainClass",
"path": "src/main/java/org/sobadfish/report/ReportMainClass.java",
"snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n\n private Config messageConfig;\n\n private Config adminPlayerConfig;\n\n private PlayerInfoManager playerInfoManager;\n\n private List<String> adminPlayers = new ArrayList<>();\n\n\n @Override\n public void onEnable() {\n mainClass = this;\n saveDefaultConfig();\n reloadConfig();\n sendMessageToConsole(\"&e举报系统正在加载\");\n if(!initSql()){\n sendMessageToConsole(\"&c无法接入数据库!\");\n dataManager = new ReportYamlManager(this);\n }\n this.getServer().getPluginManager().registerEvents(new ReportListener(),this);\n reportConfig = new ReportConfig(getConfig());\n saveResource(\"message.yml\",false);\n saveResource(\"players.yml\",false);\n messageConfig = new Config(this.getDataFolder()+\"/message.yml\",Config.YAML);\n adminPlayerConfig = new Config(this.getDataFolder()+\"/players.yml\",Config.YAML);\n adminPlayers = adminPlayerConfig.getStringList(\"admin-players\");\n playerInfoManager = new PlayerInfoManager();\n this.getServer().getCommandMap().register(\"report\",new ReportCommand(\"rp\"));\n this.getServer().getScheduler().scheduleRepeatingTask(this,playerInfoManager,20);\n sendMessageToConsole(\"举报系统加载完成\");\n }\n\n public List<String> getAdminPlayers() {\n return adminPlayers;\n }\n\n public Config getAdminPlayerConfig() {\n return adminPlayerConfig;\n }\n\n public void saveAdminPlayers(){\n adminPlayerConfig.set(\"admin-players\",adminPlayers);\n adminPlayerConfig.save();\n }\n\n public PlayerInfoManager getPlayerInfoManager() {\n return playerInfoManager;\n }\n\n public ReportConfig getReportConfig() {\n return reportConfig;\n }\n\n public Config getMessageConfig() {\n return messageConfig;\n }\n\n public static ReportMainClass getMainClass() {\n return mainClass;\n }\n\n private boolean initSql(){\n sendMessageToConsole(\"初始化数据库\");\n try {\n\n Class.forName(\"com.smallaswater.easysql.EasySql\");\n String user = getConfig().getString(\"mysql.username\");\n int port = getConfig().getInt(\"mysql.port\");\n String url = getConfig().getString(\"mysql.host\");\n String passWorld = getConfig().getString(\"mysql.password\");\n String table = getConfig().getString(\"mysql.database\");\n UserData data = new UserData(user, passWorld, url, port, table);\n SqlManager sql = new SqlManager(this, data);\n dataManager = new ReportSqlManager(sql);\n if (!((ReportSqlManager) dataManager).createTable()) {\n sendMessageToConsole(\"&c创建表单 \" + ReportSqlManager.SQL_TABLE + \" 失败!\");\n }\n sendMessageToConsole(\"&a数据库初始化完成\");\n return true;\n\n }catch (Exception e) {\n sendMessageToConsole(\"&c数据库初始化失败\");\n return false;\n }\n\n }\n\n public static IDataManager getDataManager() {\n return dataManager;\n }\n\n private static void sendMessageToConsole(String msg){\n sendMessageToObject(msg,null);\n }\n\n public static void sendMessageToAdmin(String msg){\n for(Player player: Server.getInstance().getOnlinePlayers().values()){\n if(player.isOp() || getMainClass().adminPlayers.contains(player.getName())){\n sendMessageToObject(msg,player);\n }\n }\n }\n\n public static void sendMessageToObject(String msg, CommandSender target){\n if(target == null){\n mainClass.getLogger().info(formatString(msg));\n }else{\n target.sendMessage(formatString(msg));\n }\n }\n\n public static void sendMessageToAll(String msg){\n Server.getInstance().broadcastMessage(formatString(msg));\n }\n\n\n private static String formatString(String str){\n return TextFormat.colorize('&',\"&7[&e举报系统&7] &r>&r \"+str);\n }\n}"
},
{
"identifier": "PlayerInfo",
"path": "src/main/java/org/sobadfish/report/config/PlayerInfo.java",
"snippet": "public class PlayerInfo {\n\n private String playerName;\n\n private int cold = 0;\n\n private int reportCount = 0;\n\n private Date createData;\n\n private ArrayList<String> targetName = new ArrayList<>();\n\n public PlayerInfo(String playerName){\n this.playerName = playerName;\n this.createData = new Date();\n }\n\n public void reduceCold(){\n if(cold > 0){\n cold--;\n }\n if(Utils.getDifferDay(createData) >= 1){\n reset();\n }\n }\n\n\n\n public Date getCreateData() {\n return createData;\n }\n\n public ReportType addReport(String target){\n if(target.equalsIgnoreCase(playerName)){\n return ReportType.MY;\n }\n if(targetName.contains(target)){\n return ReportType.HAS_TARGET;\n }\n if(reportCount == ReportMainClass.getMainClass().getReportConfig().getDayMax()){\n return ReportType.DAY_MAX;\n }\n if(cold != 0){\n return ReportType.COLD;\n }\n targetName.add(target);\n reportCount++;\n cold = ReportMainClass.getMainClass().getReportConfig().getCold();\n ReportMainClass.sendMessageToAdmin(\"&r玩家 &2\"+playerName+\" &r 举报了 &e\"+target+\" \");\n return ReportType.SUCCESS;\n }\n\n public int getCold() {\n return cold;\n }\n\n public int getReportCount() {\n return reportCount;\n }\n\n public ArrayList<String> getTargetName() {\n return targetName;\n }\n\n private void reset(){\n createData = new Date();\n cold = 0;\n reportCount = 0;\n targetName.clear();\n }\n\n public String getPlayerName() {\n return playerName;\n }\n\n\n @Override\n public boolean equals(Object obj) {\n if(obj instanceof PlayerInfo){\n return ((PlayerInfo) obj).playerName.equalsIgnoreCase(playerName);\n }\n return false;\n }\n\n public enum ReportType{\n /**\n * 举报成功\n * */\n SUCCESS,\n /**\n * 存在举报的玩家\n * */\n HAS_TARGET,\n /**\n * 到达今日上限\n * */\n DAY_MAX,\n /**\n * 冷却中\n * */\n COLD,\n /**\n * 自己举报自己\n * */\n MY\n\n }\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/org/sobadfish/report/tools/Utils.java",
"snippet": "public class Utils {\n\n private static final SplittableRandom RANDOM = new SplittableRandom(System.currentTimeMillis());\n\n public static int rand(int min, int max) {\n return min == max ? max : RANDOM.nextInt(max + 1 - min) + min;\n }\n\n public static double rand(double min, double max) {\n return min == max ? max : min + Math.random() * (max - min);\n }\n\n public static float rand(float min, float max) {\n return min == max ? max : min + (float)Math.random() * (max - min);\n }\n\n /**\n * 计算两个时间相差天数\n *\n * @param oldDate 终点时间\n *\n * @return 时差\n * */\n public static int getDifferDay(Date oldDate){\n if(oldDate == null) {\n return 0;\n }\n Calendar cal = Calendar.getInstance();\n cal.setTime(oldDate);\n long time1 = cal.getTimeInMillis();\n cal.setTime(Objects.requireNonNull(getDate(getDateToString(new Date()))));\n long time2 = cal.getTimeInMillis();\n long betweenDays = (time1-time2)/(1000*3600*24);\n return Integer.parseInt(String.valueOf(betweenDays));\n }\n\n public static String getDateToString(Date date){\n SimpleDateFormat lsdStrFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n return lsdStrFormat.format(date);\n }\n\n\n\n //转换String为Date\n\n public static Date getDate(String format){\n SimpleDateFormat lsdStrFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n return lsdStrFormat.parse(format);\n }catch (ParseException e){\n return null;\n }\n }\n\n public static String[] splitMsg(String msg){\n String[] rel = msg.split(\"&\");\n if(rel.length <= 1){\n String rr = rel[0].trim();\n if(\"\".equalsIgnoreCase(rr)){\n rr = \"-\";\n }\n rel = new String[]{rr,\"-\"};\n }\n return rel;\n }\n}"
}
] | import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.form.element.ElementDropdown;
import cn.nukkit.form.element.ElementInput;
import cn.nukkit.form.element.ElementLabel;
import cn.nukkit.form.response.FormResponseCustom;
import cn.nukkit.form.window.FormWindowCustom;
import cn.nukkit.utils.Config;
import cn.nukkit.utils.TextFormat;
import org.sobadfish.report.ReportMainClass;
import org.sobadfish.report.config.PlayerInfo;
import org.sobadfish.report.tools.Utils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List; | 2,363 | package org.sobadfish.report.form;
/**
* @author Sobadfish
* @date 2023/11/14
*/
public class DisplayCustomForm {
private final int id;
public static int getRid(){ | package org.sobadfish.report.form;
/**
* @author Sobadfish
* @date 2023/11/14
*/
public class DisplayCustomForm {
private final int id;
public static int getRid(){ | return Utils.rand(11900,21000); | 2 | 2023-11-15 03:08:23+00:00 | 4k |
daobab-projects/orm-performance-comparator | src/main/java/io/daobab/performance/invoker/InvokerService.java | [
{
"identifier": "SakilaDataBase",
"path": "src/main/java/io/daobab/performance/daobab/SakilaDataBase.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class SakilaDataBase extends DataBaseTarget implements SakilaTables, SqlProducer {\n\n private final RentalGenerator rentalGenerator;\n boolean recreate_database_on_start = false;\n @Value(\"${spring.datasource.url}\")\n private String url;\n @Value(\"${spring.datasource.username}\")\n private String user;\n @Value(\"${spring.datasource.password}\")\n private String pass;\n @Value(\"${spring.datasource.driverClassName}\")\n private String driverClassName;\n\n @Override\n protected DataSource initDataSource() {\n\n var config = new HikariConfig();\n config.setJdbcUrl(url);\n config.setUsername(user);\n config.setPassword(pass);\n config.setDriverClassName(driverClassName);\n config.setSchema(\"PUBLIC\");\n var db = new HikariDataSource(config);\n\n if (recreate_database_on_start) {\n createDatabaseContent(db);\n }\n\n return db;\n }\n\n @PostConstruct\n public void init() {\n getAccessProtector().setColumnAccess(tabActor.colLastName(), Access.NO_INSERT, Access.NO_UPDATE);\n setShowSql(false);\n }\n\n\n @Override\n public List<Entity> initTables() {\n return Arrays.asList(\n tabActor,\n tabAddress,\n tabCategory,\n tabCity,\n tabCountry,\n tabCustomer,\n tabFilm,\n tabFilmActor,\n tabFilmCategory,\n tabFilmText,\n tabInventory,\n tabLanguage,\n tabPayment,\n tabRental,\n tabStaff,\n tabStore\n );\n }\n\n\n private void createDatabaseContent(DataSource ds) {\n\n try {\n var con = ds.getConnection();\n\n RunScript.execute(con, new BufferedReader(\n new InputStreamReader(new ClassPathResource(\"schema.sql\").getInputStream())));\n\n RunScript.execute(con, new BufferedReader(\n new InputStreamReader(new ClassPathResource(\"data.sql\").getInputStream())));\n\n } catch (Exception e) {\n e.printStackTrace();\n throw new RuntimeException(\"Database initialize script error\");\n }\n\n }\n\n @Override\n public <E extends Entity> DataBaseIdGeneratorSupplier<?> getPrimaryKeyGenerator(E entity) {\n\n if (entity.getClass().equals(Rental.class)) {\n return rentalGenerator;\n }\n return null;\n }\n\n}"
},
{
"identifier": "SakilaTables",
"path": "src/main/java/io/daobab/performance/daobab/SakilaTables.java",
"snippet": "package io.daobab.performance.daobab;\r\rimport io.daobab.parser.ParserGeneral;\rimport io.daobab.performance.daobab.table.*;\rimport io.daobab.performance.daobab.table.enhanced.CountryCity;\rimport io.daobab.performance.daobab.table.enhanced.EnglishFilm;\rimport io.daobab.target.database.query.base.QueryDataBaseWhisperer;\r\r\rpublic interface SakilaTables extends ParserGeneral, QueryDataBaseWhisperer {\r\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * ActorId(PK) Integer 5 ACTOR_ID SMALLINT\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r Actor tabActor = new Actor();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Address String 50 ADDRESS VARCHAR\r * Address2 String 50 ADDRESS2 VARCHAR\r * AddressId(PK) Integer 5 ADDRESS_ID SMALLINT\r * CityId Integer 5 CITY_ID SMALLINT\r * District String 20 DISTRICT VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Phone String 20 PHONE VARCHAR\r * PostalCode String 10 POSTAL_CODE VARCHAR\r * </pre>\r */\r Address tabAddress = new Address();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CategoryId(PK) Integer 3 CATEGORY_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Name String 25 NAME VARCHAR\r * </pre>\r */\r Category tabCategory = new Category();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * City String 50 CITY VARCHAR\r * CityId(PK) Integer 5 CITY_ID SMALLINT\r * CountryId Integer 5 COUNTRY_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r City tabCity = new City();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Country String 50 COUNTRY VARCHAR\r * CountryId(PK) Integer 5 COUNTRY_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r Country tabCountry = new Country();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Active Boolean 1 ACTIVE BOOLEAN\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * CreateDate Timestamp 26 CREATE_DATE TIMESTAMP\r * CustomerId(PK) Integer 5 CUSTOMER_ID SMALLINT\r * Email String 50 EMAIL VARCHAR\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * StoreId Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Customer tabCustomer = new Customer();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Description String 2147483647 DESCRIPTION VARCHAR\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LanguageId Integer 3 LANGUAGE_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Length Integer 5 LENGTH SMALLINT\r * OriginalLanguageId Integer 3 ORIGINAL_LANGUAGE_ID TINYINT\r * Rating String 5 RATING VARCHAR\r * ReleaseYear Date 10 RELEASE_YEAR DATE\r * RentalDuration Integer 3 RENTAL_DURATION TINYINT\r * RentalRate BigDecimal 4 RENTAL_RATE DECIMAL\r * ReplacementCost BigDecimal 5 REPLACEMENT_COST DECIMAL\r * SpecialFeatures String 54 SPECIAL_FEATURES VARCHAR\r * Title String 255 TITLE VARCHAR\r * </pre>\r */\r Film tabFilm = new Film();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * ActorId(PK) Integer 5 ACTOR_ID SMALLINT\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r FilmActor tabFilmActor = new FilmActor();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CategoryId(PK) Integer 3 CATEGORY_ID TINYINT\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * </pre>\r */\r FilmCategory tabFilmCategory = new FilmCategory();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Description String 2147483647 DESCRIPTION VARCHAR\r * FilmId(PK) Integer 5 FILM_ID SMALLINT\r * Title String 255 TITLE VARCHAR\r * </pre>\r */\r FilmText tabFilmText = new FilmText();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * FilmId Integer 5 FILM_ID SMALLINT\r * InventoryId(PK) BigDecimal 10 INVENTORY_ID INTEGER\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * StoreId Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Inventory tabInventory = new Inventory();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * LanguageId(PK) Integer 3 LANGUAGE_ID TINYINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Name String 20 NAME VARCHAR\r * </pre>\r */\r Language tabLanguage = new Language();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Amount BigDecimal 5 AMOUNT DECIMAL\r * CustomerId Integer 5 CUSTOMER_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * PaymentDate Timestamp 26 PAYMENT_DATE TIMESTAMP\r * PaymentId(PK) Integer 5 PAYMENT_ID SMALLINT\r * RentalId BigDecimal 10 RENTAL_ID INTEGER\r * StaffId Integer 3 STAFF_ID TINYINT\r * </pre>\r */\r Payment tabPayment = new Payment();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * CustomerId Integer 5 CUSTOMER_ID SMALLINT\r * InventoryId BigDecimal 10 INVENTORY_ID INTEGER\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * RentalDate Timestamp 26 RENTAL_DATE TIMESTAMP\r * RentalId(PK) BigDecimal 10 RENTAL_ID INTEGER\r * ReturnDate Timestamp 26 RETURN_DATE TIMESTAMP\r * StaffId Integer 3 STAFF_ID TINYINT\r * </pre>\r */\r Rental tabRental = new Rental();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * Active Boolean 1 ACTIVE BOOLEAN\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * Email String 50 EMAIL VARCHAR\r * FirstName String 45 FIRST_NAME VARCHAR\r * LastName String 45 LAST_NAME VARCHAR\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * Password String 40 PASSWORD VARCHAR\r * Picture byte[] 2147483647 PICTURE VARBINARY\r * StaffId(PK) Integer 3 STAFF_ID TINYINT\r * StoreId Integer 3 STORE_ID TINYINT\r * Username String 16 USERNAME VARCHAR\r * </pre>\r */\r Staff tabStaff = new Staff();\r\r /**\r * Comment:<br>\r *\r * <pre>\r *\r * <u> Name Type Size DBName DBType Description </u>\r * AddressId Integer 5 ADDRESS_ID SMALLINT\r * LastUpdate Timestamp 26 LAST_UPDATE TIMESTAMP\r * ManagerStaffId Integer 3 MANAGER_STAFF_ID TINYINT\r * StoreId(PK) Integer 3 STORE_ID TINYINT\r * </pre>\r */\r Store tabStore = new Store();\r\r //===================================\r\r /**\r * Enhanced Entity\r */\r EnglishFilm tabEnglishFilm = new EnglishFilm();\r\r\r /**\r * Enhanced Entity\r */\r CountryCity tabCountryCity = new CountryCity();\r}\r"
}
] | import io.daobab.performance.daobab.SakilaDataBase;
import io.daobab.performance.daobab.SakilaTables;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static java.lang.String.format; | 3,446 | package io.daobab.performance.invoker;
@Component
@Slf4j
@RequiredArgsConstructor | package io.daobab.performance.invoker;
@Component
@Slf4j
@RequiredArgsConstructor | public class InvokerService implements SakilaTables { | 1 | 2023-11-12 21:43:51+00:00 | 4k |
lastnightinparis/tinkoff-investement-bot | bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/update/impl/TextUpdateHandler.java | [
{
"identifier": "UserConverter",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/converter/UserConverter.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class UserConverter {\n\n\n public User fromTgApi(org.telegram.telegrambots.meta.api.objects.User user) {\n Long chatId = user.getId();\n String username;\n String tgUsername;\n\n if (user.getUserName() != null && !user.getUserName().isEmpty()) {\n username = user.getUserName();\n tgUsername = user.getUserName();\n } else if (!user.getFirstName().isEmpty()) {\n username = user.getFirstName();\n tgUsername = \"user_\" + chatId;\n } else {\n username = \"user_\" + chatId;\n tgUsername = \"user_\" + chatId;\n }\n return User.builder()\n .chatId(chatId)\n .username(username)\n .tgUsername(tgUsername)\n .build();\n }\n}"
},
{
"identifier": "BotUserDeniedException",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/chat/BotUserDeniedException.java",
"snippet": "public class BotUserDeniedException extends ChatException {\n\n public BotUserDeniedException(Long chatId) {\n super(chatId);\n }\n\n}"
},
{
"identifier": "ProcessingException",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/chat/ProcessingException.java",
"snippet": "public class ProcessingException extends ChatException {\n\n public ProcessingException(Long chatId, String message) {\n super(chatId, message);\n }\n\n public ProcessingException(Long chatId, String message, Throwable cause) {\n super(chatId, message, cause);\n }\n\n public String getMasterMessage() {\n return String.format(\"#processing_error\\nChat ID: %d, Message: %s\", getChatId(), getMessage());\n }\n}"
},
{
"identifier": "IllegalTradingBotException",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/system/IllegalTradingBotException.java",
"snippet": "public class IllegalTradingBotException extends TradingBotException {\n\n public IllegalTradingBotException(String message) {\n super(message);\n }\n\n public IllegalTradingBotException(String message, Throwable cause) {\n super(message, cause);\n }\n}"
},
{
"identifier": "UpdateHandlersRegistry",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/registry/UpdateHandlersRegistry.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class UpdateHandlersRegistry {\n\n @Qualifier(\"textHandlers\")\n private final Map<BotState, TextUpdate> textHandlers;\n @Qualifier(\"callbackHandlers\")\n private final Map<BotState, CallbackUpdate> callbackHandlers;\n\n public TextUpdate getTextHandlerFor(BotState botState) {\n if (textHandlers.containsKey(botState)) {\n return textHandlers.get(botState);\n }\n throw new IllegalTradingBotException(\"Unknown text handler botState: \" + botState.toString());\n }\n\n public CallbackUpdate getCallbackHandlerFor(BotState botState) {\n if (callbackHandlers.containsKey(botState)) {\n return callbackHandlers.get(botState);\n }\n throw new IllegalTradingBotException(\n \"Unknown callback handler botState: \" + botState.toString());\n }\n}"
},
{
"identifier": "BotUpdateHandler",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/update/BotUpdateHandler.java",
"snippet": "public interface BotUpdateHandler {\n\n void handelUpdates(Update update);\n\n UpdateType supportedUpdateType();\n}"
},
{
"identifier": "User",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/domain/User.java",
"snippet": "@Data\n@Entity\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = \"users\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"chat_id\")\n private Long chatId;\n\n @Column(name = \"username\")\n private String username;\n\n @Column(name = \"tg_username\")\n private String tgUsername;\n\n @Column(name = \"is_active\")\n private boolean active;\n\n @Column(name = \"is_blocked\")\n private boolean blocked;\n\n @Column(name = \"is_connected_account\")\n private boolean connectedInvestAccount;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"bot_state\")\n private BotState botState;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"prev_bot_state\")\n private BotState previousBotState;\n\n @Column(name = \"registered_at\")\n private Instant registeredAt;\n\n @Column(name = \"last_activity_at\")\n private Instant lastActivityAt;\n}"
},
{
"identifier": "BotState",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/bot/BotState.java",
"snippet": "public enum BotState {\n BOT_VERSION_COMMAND, HELP_COMMAND,\n\n START, FIRST_START,\n\n TRADING_MENU, NOTIFICATION_MENU, ACCOUNT_SETTINGS, HELP, BACK,\n\n START_TRADING, CHOOSE_STRATEGY_ACTION, ENTER_TRADING_TICKER, CHOOSE_STRATEGY_PARAM,\n ENTER_ADDITIONAL_PARAM,\n\n TRADINGS_LIST, STRATEGIES_LIST,\n\n CREATE_NOTIFICATION_EVENT, NOTIFICATION_EVENT_LIST,\n\n INVEST_ACCOUNT_ACTION, ENTER_TOKEN\n}"
},
{
"identifier": "Button",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/bot/Button.java",
"snippet": "@Getter\npublic enum Button {\n // inline команды\n START(\"/start\", BotState.START),\n BOT_VERSION_COMMAND(\"/bot_version\", BotState.BOT_VERSION_COMMAND),\n HELP_COMMAND(\"/help\", BotState.HELP_COMMAND),\n HELP(\"Помощь\", BotState.HELP),\n\n TRADING_MENU(\"Торги\", BotState.TRADING_MENU),\n NOTIFICATION_MENU(\"Уведомления\", BotState.NOTIFICATION_MENU),\n ACCOUNT_SETTINGS(\"Аккаунт\", BotState.ACCOUNT_SETTINGS),\n BACK(\"Назад\", BotState.BACK),\n\n START_TRADING(\"Начать торги\", BotState.START_TRADING),\n TRADINGS_LIST(\"Список активных стратегий\", BotState.TRADINGS_LIST),\n STRATEGIES_LIST(\"Список стратегий\", BotState.STRATEGIES_LIST),\n\n\n CREATE_NOTIFICATION_EVENT(\"Подключить уведомление\", BotState.CREATE_NOTIFICATION_EVENT),\n NOTIFICATION_EVENT_LIST(\"Список уведомлений\", BotState.NOTIFICATION_EVENT_LIST);\n\n private final String message;\n private final BotState botState;\n\n Button(String message, BotState botState) {\n this.message = message;\n this.botState = botState;\n }\n\n public static Optional<Button> findByMessage(String message) {\n return Stream.of(Button.values())\n .filter(button -> button.message.equals(message))\n .findFirst();\n }\n}"
},
{
"identifier": "UpdateType",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/handler/UpdateType.java",
"snippet": "public enum UpdateType {\n TEXT,\n CALLBACK\n}"
},
{
"identifier": "UserService",
"path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/users/UserService.java",
"snippet": "public interface UserService {\n\n List<User> findAll();\n\n Optional<User> findUserByChatId(long chatId);\n\n Optional<User> findUserByTgUsername(String tgUsername);\n\n List<Long> getAdminChatIds();\n\n User getUserById(Long id);\n\n User getUserByChatId(Long chatId);\n\n User save(User user);\n\n User setCurrentBotState(Long chatId, BotState botState);\n\n boolean isNew(Long chatId);\n}"
}
] | import com.itmo.tinkoffinvestementbot.converter.UserConverter;
import com.itmo.tinkoffinvestementbot.exception.chat.BotUserDeniedException;
import com.itmo.tinkoffinvestementbot.exception.chat.ProcessingException;
import com.itmo.tinkoffinvestementbot.exception.system.IllegalTradingBotException;
import com.itmo.tinkoffinvestementbot.handler.registry.UpdateHandlersRegistry;
import com.itmo.tinkoffinvestementbot.handler.update.BotUpdateHandler;
import com.itmo.tinkoffinvestementbot.model.domain.User;
import com.itmo.tinkoffinvestementbot.model.enums.bot.BotState;
import com.itmo.tinkoffinvestementbot.model.enums.bot.Button;
import com.itmo.tinkoffinvestementbot.model.enums.handler.UpdateType;
import com.itmo.tinkoffinvestementbot.service.users.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.Optional; | 2,372 | package com.itmo.tinkoffinvestementbot.handler.update.impl;
@Service
@RequiredArgsConstructor
public class TextUpdateHandler implements BotUpdateHandler {
private final UserService userService;
private final UserConverter userConverter;
private final UpdateHandlersRegistry updateHandlersRegistry;
@Override
public void handelUpdates(Update update) {
Message message = update.getMessage();
Long userChatId = message.getFrom().getId();
User user;
if (userService.isNew(userChatId)) {
// Если пользователь новый
if (message.getFrom().getIsBot()) {
// Если пользователь является ботом
throw new BotUserDeniedException(userChatId);
} else {
// Если новый пользователь не является ботом
user = userService.save(
userConverter.fromTgApi(message.getFrom())
);
try {
updateHandlersRegistry
.getTextHandlerFor(BotState.FIRST_START)
.handleText(user, message);
} catch (IllegalTradingBotException e) {
throw new ProcessingException(
userChatId,
"There is no text handler for bot state - " + BotState.FIRST_START,
e
);
}
}
} else {
// Если пользователь зарегистрирован в системе
user = userService.getUserByChatId(userChatId);
if (user.isBlocked()) {
// Если пользователь разблокировал бота
user.setBlocked(false);
user = userService.save(user);
} | package com.itmo.tinkoffinvestementbot.handler.update.impl;
@Service
@RequiredArgsConstructor
public class TextUpdateHandler implements BotUpdateHandler {
private final UserService userService;
private final UserConverter userConverter;
private final UpdateHandlersRegistry updateHandlersRegistry;
@Override
public void handelUpdates(Update update) {
Message message = update.getMessage();
Long userChatId = message.getFrom().getId();
User user;
if (userService.isNew(userChatId)) {
// Если пользователь новый
if (message.getFrom().getIsBot()) {
// Если пользователь является ботом
throw new BotUserDeniedException(userChatId);
} else {
// Если новый пользователь не является ботом
user = userService.save(
userConverter.fromTgApi(message.getFrom())
);
try {
updateHandlersRegistry
.getTextHandlerFor(BotState.FIRST_START)
.handleText(user, message);
} catch (IllegalTradingBotException e) {
throw new ProcessingException(
userChatId,
"There is no text handler for bot state - " + BotState.FIRST_START,
e
);
}
}
} else {
// Если пользователь зарегистрирован в системе
user = userService.getUserByChatId(userChatId);
if (user.isBlocked()) {
// Если пользователь разблокировал бота
user.setBlocked(false);
user = userService.save(user);
} | Optional<Button> buttonOpt = Button.findByMessage(message.getText()); | 8 | 2023-11-13 09:28:00+00:00 | 4k |
toxicity188/InventoryAPI | plugin/src/main/java/kor/toxicity/inventory/manager/ResourcePackManagerImpl.java | [
{
"identifier": "InventoryAPI",
"path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontManager fontManager;\n private ResourcePackManager resourcePackManager;\n\n @Override\n public final void onLoad() {\n if (api != null) throw new SecurityException();\n api = this;\n }\n\n public static @NotNull InventoryAPI getInstance() {\n return Objects.requireNonNull(api);\n }\n\n public final void setFontManager(@NotNull FontManager fontManager) {\n this.fontManager = Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull FontManager getFontManager() {\n return Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull ImageManager getImageManager() {\n return Objects.requireNonNull(imageManager);\n }\n\n public final void setImageManager(@NotNull ImageManager imageManager) {\n this.imageManager = Objects.requireNonNull(imageManager);\n }\n\n public final void setResourcePackManager(@NotNull ResourcePackManager resourcePackManager) {\n this.resourcePackManager = Objects.requireNonNull(resourcePackManager);\n }\n\n public @NotNull ResourcePackManager getResourcePackManager() {\n return Objects.requireNonNull(resourcePackManager);\n }\n public final void reload() {\n reload(true);\n }\n\n public abstract void reload(boolean callEvent);\n public void reload(@NotNull Consumer<Long> longConsumer) {\n var pluginManager = Bukkit.getPluginManager();\n pluginManager.callEvent(new PluginReloadStartEvent());\n Bukkit.getScheduler().runTaskAsynchronously(this, () -> {\n var time = System.currentTimeMillis();\n reload(false);\n var time2 = System.currentTimeMillis() - time;\n Bukkit.getScheduler().runTask(this, () -> {\n pluginManager.callEvent(new PluginReloadEndEvent());\n longConsumer.accept(time2);\n });\n });\n }\n\n public @NotNull ItemStack getEmptyItem(@NotNull Consumer<ItemMeta> metaConsumer) {\n var stack = new ItemStack(getResourcePackManager().getEmptyMaterial());\n var meta = stack.getItemMeta();\n assert meta != null;\n metaConsumer.accept(meta);\n meta.setCustomModelData(1);\n stack.setItemMeta(meta);\n return stack;\n }\n public abstract @NotNull MiniMessage miniMessage();\n public abstract @NotNull GuiFont defaultFont();\n public abstract void openGui(@NotNull Player player, @NotNull Gui gui, @NotNull GuiType type, long delay, @NotNull GuiExecutor executor);\n}"
},
{
"identifier": "GuiFont",
"path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiFont.java",
"snippet": "@Getter\npublic final class GuiFont implements GuiResource {\n\n public static final FontRenderContext CONTEXT = new FontRenderContext(null, true, true);\n public static final double VERTICAL_SIZE = 1.4;\n\n private final @NotNull String name;\n private final @NotNull Font font;\n private final int size;\n private final @NotNull Map<Character, Function<Integer, Integer>> fontWidth;\n private final @NotNull List<Character> availableChar;\n private final @NotNull FontMetrics metrics;\n\n public GuiFont(@NotNull Font font, @NotNull String name) {\n this(font, name, 16);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size) {\n this(font, name, size, 0);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size, double width) {\n this(font, name, size, width, 1);\n }\n public GuiFont(@NotNull Font font, @NotNull String name, int size, double width, double widthMultiplier) {\n this.font = font.deriveFont((float) size);\n this.name = name;\n this.size = size;\n var widthMap = new TreeMap<@NotNull Character, @NotNull Function<Integer, Integer>>();\n IntStream.rangeClosed(Character.MIN_VALUE, Character.MAX_VALUE).mapToObj(i -> (char) i).filter(font::canDisplay).forEach(c -> {\n var str = this.font.getStringBounds(Character.toString(c), CONTEXT);\n widthMap.put(c, i -> (int) Math.round((str.getWidth() * i / VERTICAL_SIZE / str.getHeight() + width) * widthMultiplier));\n });\n fontWidth = ImmutableMap.copyOf(widthMap);\n var graphics = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).createGraphics();\n metrics = graphics.getFontMetrics(this.font);\n graphics.dispose();\n var c = new ArrayList<>(widthMap.keySet());\n availableChar = ImmutableList.copyOf(c.subList(0, c.size() - c.size() % 16));\n }\n}"
},
{
"identifier": "GuiObjectGenerator",
"path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiObjectGenerator.java",
"snippet": "public interface GuiObjectGenerator {\n int getAscent();\n int getHeight();\n @NotNull GuiObjectBuilder builder();\n @NotNull Key getFontKey();\n}"
},
{
"identifier": "GuiResource",
"path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiResource.java",
"snippet": "public interface GuiResource {\n default @NotNull GuiObjectGenerator generator(int height, int ascent) {\n return InventoryAPI.getInstance().getResourcePackManager().registerTask(this, height, ascent);\n }\n}"
},
{
"identifier": "ResourcePackManager",
"path": "api/src/main/java/kor/toxicity/inventory/api/manager/ResourcePackManager.java",
"snippet": "public interface ResourcePackManager extends InventoryManager {\n @NotNull GuiObjectGenerator registerTask(@NotNull GuiResource resource, int height, int ascent);\n @NotNull Material getEmptyMaterial();\n}"
},
{
"identifier": "JsonArrayBuilder",
"path": "plugin/src/main/java/kor/toxicity/inventory/builder/JsonArrayBuilder.java",
"snippet": "public class JsonArrayBuilder {\n private final JsonArray array = new JsonArray();\n\n\n public JsonArrayBuilder add(Number value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(Character value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(String value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(Boolean value) {\n array.add(value);\n return this;\n }\n public JsonArrayBuilder add(JsonElement value) {\n array.add(value);\n return this;\n }\n\n public JsonArray build() {\n return array;\n }\n}"
},
{
"identifier": "JsonObjectBuilder",
"path": "plugin/src/main/java/kor/toxicity/inventory/builder/JsonObjectBuilder.java",
"snippet": "public class JsonObjectBuilder {\n private final JsonObject object = new JsonObject();\n\n\n public JsonObjectBuilder add(String key, Number value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, Character value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, String value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, Boolean value) {\n object.addProperty(key, value);\n return this;\n }\n public JsonObjectBuilder add(String key, JsonElement value) {\n object.add(key, value);\n return this;\n }\n\n public JsonObject build() {\n return object;\n }\n}"
},
{
"identifier": "FontObjectGeneratorImpl",
"path": "plugin/src/main/java/kor/toxicity/inventory/generator/FontObjectGeneratorImpl.java",
"snippet": "public class FontObjectGeneratorImpl implements FontObjectGenerator {\n\n private final GuiFont font;\n private final int height;\n private final int ascent;\n @Getter\n private final String fontTitle;\n private final Key key;\n\n public FontObjectGeneratorImpl(GuiFont font, int height, int ascent) {\n this.font = font;\n this.height = height;\n this.ascent = ascent;\n fontTitle = font.getName() + \"_\" + height + \"_\" + ascent;\n key = Key.key(\"inventory:font/\" + fontTitle);\n }\n\n @Override\n public @NotNull GuiFont getFont() {\n return font;\n }\n\n @Override\n public int getAscent() {\n return ascent;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n\n @Override\n public @NotNull GuiObjectBuilder builder() {\n return new FontObjectBuilder() {\n private int space = 6;\n private String text = \"none\";\n private int xOffset = 0;\n private Style style = Style.empty();\n\n @Override\n public @NotNull FontObjectBuilder setSpace(int space) {\n this.space = space;\n return this;\n }\n\n @Override\n public @NotNull FontObjectBuilder setText(@NotNull String text) {\n this.text = Objects.requireNonNull(text);\n return this;\n }\n\n @Override\n public @NotNull GuiObjectBuilder setXOffset(int xOffset) {\n this.xOffset = xOffset;\n return this;\n }\n\n @Override\n public @NotNull FontObjectBuilder setStyle(@NotNull Style style) {\n this.style = Objects.requireNonNull(style);\n return this;\n }\n\n @Override\n public @NotNull GuiObject build() {\n return new FontObjectImpl(FontObjectGeneratorImpl.this, text, style, space, xOffset);\n }\n };\n }\n\n @Override\n public @NotNull Key getFontKey() {\n return key;\n }\n}"
},
{
"identifier": "ImageObjectGeneratorImpl",
"path": "plugin/src/main/java/kor/toxicity/inventory/generator/ImageObjectGeneratorImpl.java",
"snippet": "public class ImageObjectGeneratorImpl implements ImageObjectGenerator, Comparable<ImageObjectGeneratorImpl> {\n\n private static final Key GUI_KEY = Key.key(\"inventory:gui\");\n private static int serialNumber = 0xD0000;\n\n public static void initialize() {\n serialNumber = 0xD0000;\n }\n\n private final GuiImage image;\n private final int height;\n private final int ascent;\n @Getter\n private final String serialChar;\n private final int compareNumber;\n\n public ImageObjectGeneratorImpl(GuiImage image, int height, int ascent) {\n this.image = image;\n this.height = height;\n this.ascent = ascent;\n compareNumber = ++serialNumber;\n serialChar = AdventureUtil.parseChar(compareNumber);\n }\n @Override\n public int getAscent() {\n return ascent;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n @Override\n public @NotNull GuiObjectBuilder builder() {\n return new ImageObjectBuilder() {\n private int xOffset;\n @Override\n public @NotNull GuiObjectBuilder setXOffset(int xOffset) {\n this.xOffset = xOffset;\n return this;\n }\n\n @Override\n public @NotNull GuiObject build() {\n return new ImageObjectImpl(ImageObjectGeneratorImpl.this, xOffset);\n }\n };\n }\n\n @Override\n public @NotNull Key getFontKey() {\n return GUI_KEY;\n }\n\n @Override\n public @NotNull GuiImage getImage() {\n return image;\n }\n\n @Override\n public int compareTo(@NotNull ImageObjectGeneratorImpl o) {\n return Integer.compare(compareNumber, o.compareNumber);\n }\n}"
},
{
"identifier": "PluginUtil",
"path": "plugin/src/main/java/kor/toxicity/inventory/util/PluginUtil.java",
"snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\npublic class PluginUtil {\n private PluginUtil() {\n throw new SecurityException();\n }\n\n public static void loadFolder(String dir, Consumer<File> fileConsumer) {\n var dataFolder = InventoryAPI.getInstance().getDataFolder();\n if (!dataFolder.exists()) dataFolder.mkdir();\n var folder = new File(dataFolder, dir);\n if (!folder.exists()) folder.mkdir();\n var listFiles = folder.listFiles();\n if (listFiles != null) for (File listFile : listFiles) {\n fileConsumer.accept(listFile);\n }\n }\n\n public static FileName getFileName(File file) {\n var name = file.getName().split(\"\\\\.\");\n return new FileName(name[0], name.length > 1 ? name[1] : \"\");\n }\n\n public static void warn(String message) {\n InventoryAPI.getInstance().getLogger().warning(message);\n }\n\n public record FileName(String name, String extension) {\n }\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.stream.JsonWriter;
import kor.toxicity.inventory.api.InventoryAPI;
import kor.toxicity.inventory.api.gui.GuiFont;
import kor.toxicity.inventory.api.gui.GuiImage;
import kor.toxicity.inventory.api.gui.GuiObjectGenerator;
import kor.toxicity.inventory.api.gui.GuiResource;
import kor.toxicity.inventory.api.manager.ResourcePackManager;
import kor.toxicity.inventory.builder.JsonArrayBuilder;
import kor.toxicity.inventory.builder.JsonObjectBuilder;
import kor.toxicity.inventory.generator.FontObjectGeneratorImpl;
import kor.toxicity.inventory.generator.ImageObjectGeneratorImpl;
import kor.toxicity.inventory.util.PluginUtil;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List; | 3,263 | package kor.toxicity.inventory.manager;
public class ResourcePackManagerImpl implements ResourcePackManager {
private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();
private final List<ImageObjectGeneratorImpl> images = new ArrayList<>();
@Getter
private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void reload() { | package kor.toxicity.inventory.manager;
public class ResourcePackManagerImpl implements ResourcePackManager {
private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();
private final List<ImageObjectGeneratorImpl> images = new ArrayList<>();
@Getter
private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR;
@SuppressWarnings("ResultOfMethodCallIgnored")
@Override
public void reload() { | var topFolder = getFile(getFile(InventoryAPI.getInstance().getDataFolder(), ".generated"), "assets"); | 0 | 2023-11-13 00:19:46+00:00 | 4k |
Hikaito/Fox-Engine | src/system/setting/UserSetting.java | [
{
"identifier": "Program",
"path": "src/system/Program.java",
"snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static LayerManager layerManager;\n private static UndoRedoStack undoRedoStack;\n private static ProjectManager projectManager;\n\n // function to launch, control, and represent program window\n public static void main(String[] args){\n\n // load user settings\n userSetting = UserSetting.get();\n if (!userSetting.pathDefaultProject.equals(\"\")) FileOperations.generateDirectories(); // refresh directories if a project was selected\n\n // load project\n projectManager = new ProjectManager(); // generate manager\n // if no project, then initialize null\n if(userSetting.pathDefaultProject.equals(\"\")) projectManager.initializeEmpty();\n else projectManager.loadProject(getProjectPath()); // load project\n\n // initialize project\n layerManager = new LayerManager();\n layerManager.setProjectID(projectManager.getUUID());\n layerManager.setProjectTitle(projectManager.getTitle());\n\n // initialize undo/redo stack\n undoRedoStack = new UndoRedoStack(userSetting.undoMax);\n\n //initialize frame\n try {\n window = new MainWindow();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n //endregion\n //region utility functions---------------------------------------------------\n\n // Version numbers\n private static VersionNumber programVersionNumber = new VersionNumber(\"1.0.0\");\n public static VersionNumber getProgramVersion(){return programVersionNumber;}\n\n // function for log output\n private static final PrintStream logStreamOut = System.out; // stream for log outputs\n public static void log(String input){\n logStreamOut.println(input);\n }\n\n // window title\n public static String getWindowTitle(){return \"Fox Engine\";}\n\n // GSON builder\n private static final Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag\n .setPrettyPrinting() // creates a pretty version of the output\n .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter\n .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer\n .create();\n\n //endregion\n //region MainWindow operations --------------------------------------------\n\n // composite function: re-render both canvas and editors\n public static void redrawAllRegions(){\n redrawCanvas();\n redrawLayerEditor();\n }\n\n // composite function: re-render editor panes\n public static void redrawLayerEditor(){\n layerManager.rebuildLayerTree();\n layerManager.rebuildEditorPanel();\n window.repaintLayerEditor(); //clears lingering removed elements from underlying rectangles\n }\n\n // vanilla functions\n public static void redrawCanvas(){\n window.redrawCanvas();\n } // re-render the canvas image from layer tree\n public static void redrawMenuBar(){\n window.regenMenuBar();\n } // rerender menu bar\n public static void zoomInCanvas(){ window.zoomInCanvas(); }\n public static void zoomOutCanvas(){ window.zoomOutCanvas();}\n\n //endregion\n //region ProjectManager -----------------------------\n\n // loads the image associated with a filecode\n public static String getProjectID(){return projectManager.getUUID();}\n public static ProjectFile getImageFile(long fileCode){ return projectManager.getFile(fileCode);}\n public static BufferedImage getImage(long fileCode){\n //get file\n ProjectFile file = projectManager.getFile(fileCode);\n if (file == null) return null;\n String path = projectManager.getAbsolutePath(file); // get image path\n try {\n return ImageIO.read(new File(path));\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n public static void saveProject() {projectManager.saveFile();}\n public static void loadProject(){projectManager.loadProject();}\n public static void editProject(){projectManager.openEditor();}\n public static void selectFileFromProject(Layer layer){projectManager.openSelector(layer);}\n public static void selectIntersectClippingFile(Folder folder){projectManager.openSelector(folder);}\n public static JMenu getProjectMenu(){\n return projectManager.getMenu();\n }\n\n // endregion\n // region SelectionManger [via LayerManager] -----------------------\n\n public static void addSelection(TreeUnit obj){layerManager.addSelection(obj);}\n public static void removeSelection(TreeUnit obj){layerManager.removeSelection(obj);}\n public static void clearSelection(){layerManager.clearSelection();}\n public static TreeUnit peekSelectionTop(){return layerManager.peekSelectionTop();}\n public static SelectionManager.selectionPriority getSelectionStatus(){return layerManager.getSelectionStatus();}\n public static SelectionManager.selectionPriority checkSelection(TreeUnit obj){return layerManager.checkSelection(obj);}\n public static Color selectionColor(TreeUnit unit){return layerManager.selectionColor(unit);}\n\n // endregion\n // region LayerManager operations ---------------------------------\n\n //generate a save file for the project manager\n public static boolean generateManagerFile(String path){\n // derive json\n String json = gson.toJson(layerManager);\n\n // write json to file\n try {\n FileWriter out = new FileWriter(path, false);\n out.write(json);\n out.close();\n Program.log(\"LayerManager Save File '\" + path + \"' successfully written.\");\n } catch (IOException e) {\n //e.printStackTrace(); fixme\n Program.log(\"LayerManager Save File '\" + path + \"' could not be written.\");\n return false;\n }\n\n return true;\n }\n\n // open a save and generate a manager to hold it; does not assign a manager\n public static LayerManager loadManagerFile(String path){\n\n // return control object loaded from file if possible\n try {\n String json = new String(Files.readAllBytes(Paths.get(path)));\n return gson.fromJson(json, LayerManager.class);\n }\n\n // return null if no object could be loaded\n catch (IOException e) {\n Program.log(\"LayerManager Save File '\" + path + \"' could not be read.\");\n return null;\n }\n }\n\n // open a save file and load it as the layer manager\n public static void loadFileAsManager(String path){\n LayerManager temp = loadManagerFile(path); // load file\n if (temp == null) return; // reject failed loads\n\n //if successful, perform program transition\n layerManager.replaceManager(temp);\n redrawAllRegions();\n Program.log(\"LayerManager Save File '\" + path + \"' loaded as layer manager.\");\n }\n\n // open a save file and merge it into the existing tree\n public static void mergeFileAsManager(String path){\n LayerManager temp = loadManagerFile(path); // load file\n if (temp == null) return; // reject failed loads\n\n //if successful, perform program transition\n layerManager.addManager(temp);\n redrawAllRegions();\n Program.log(\"LayerManager Save File '\" + path + \"' loaded as layer manager.\");\n }\n\n // vanilla functions\n public static void clearFile(){layerManager.clear();}\n public static void moveLayer(TreeUnit unit, LayerManager.direction dir){layerManager.moveLayer(unit, dir);}\n public static void addFolder(){layerManager.addFolder();}\n public static void addLayer(){layerManager.addLayer();}\n public static void addLayer(long code, boolean useColor, Color color){layerManager.addLayer(code, useColor, color);}\n public static void duplicateTreeUnit(TreeUnit unit){layerManager.duplicate(unit);}\n public static void deleteTreeUnit(TreeUnit unit, Boolean bool){layerManager.delete(unit, bool);}\n public static void markImageForRender(TreeUnit unit){layerManager.markImageForRender(unit);}\n public static void markParentForRender(TreeUnit unit){layerManager.markParentForRender(unit);}\n public static BufferedImage getCanvasImage(){return layerManager.stackImage();}\n public static JPanel getLayerTreePanel(){return layerManager.getLayerTreePanel();}\n public static JPanel getLayerEditPanel(){return layerManager.getLayerEditorPanel();}\n\n //endregion\n //region file operations ---------------------------------------------------\n\n // file editing\n public static void loadTemplate(){ FileOperations.loadTemplate();}\n public static void addTemplate(){ FileOperations.addTemplate();}\n public static void saveTemplate(){ FileOperations.saveTemplate();}\n public static void loadImage(){ FileOperations.loadImage();}\n public static void saveFile(){ FileOperations.saveFile();}\n public static void exportImage(){ FileOperations.exportDialogue();}\n public static void newFile(){ FileOperations.newFile(true);}\n public static void newFileNoWarning(){ FileOperations.newFile(false);}\n\n // endregion\n // region undo/redo ---------------------------------------------------\n\n public static void addUndo(Receipt task){\n undoRedoStack.add(task);\n }\n public static void redo(){\n undoRedoStack.redo();\n }\n public static void undo(){\n undoRedoStack.undo();\n }\n\n // endregion\n // region UserSetting object accessors and mutators ---------------------------------------------------\n\n public static int getScrollMouseAcceleration(){return userSetting.canvasMouseAcceleration;}\n public static double getCanvasScaleFactor(){return userSetting.canvasScaleFactor;}\n public static int getCanvasSliderMin(){return userSetting.canvasSliderMin;}\n public static int getCanvasSliderMax(){return userSetting.canvasSliderMax;}\n public static int getCanvasSliderNeutral(){return userSetting.canvasSliderNeutral;}\n public static int getDefaultCanvasWidth(){return userSetting.defaultCanvasWidth;}\n public static int getDefaultCanvasHeight(){return userSetting.defaultCanvasHeight;}\n public static int getDefaultWindowWidth(){return userSetting.defaultWindowWidth;}\n public static int getDefaultWindowHeight(){return userSetting.defaultWindowHeight;}\n public static int getUndoMax(){return userSetting.undoMax;}\n public static Color getPrimarySelectionColor(){return userSetting.colorPrimarySelection;}\n public static Color getSecondarySelectionColor(){return userSetting.colorSecondarySelection;}\n public static Color getManySelectionColor(){return userSetting.colorManySelection;}\n public static String getDefaultRenderableTitle(){return userSetting.defaultRenderableTitle;}\n public static long getDefaultFileCode() {return userSetting.defaultFileCode;}\n public static String getSaveFileExtension(){return userSetting.fileExtensionSave;}\n public static String getImageFileExtension(){return userSetting.fileExtensionRender;}\n public static String getImageExportFormat(){return userSetting.imageRenderFormat;}\n public static String getAutosavePath(String file){\n //path format: \"file.txt_AUTO.txt\" in the autosave folder\n return Paths.get( Program.getSaveFolderPath(), file + userSetting.filenameExtensionAutosave + userSetting.fileExtensionSave).toString();\n }\n public static String getFileExtensionLoadImage(){return userSetting.fileExtensionLoadImage;}\n public static String getProjectFile(){return userSetting.projectFileName;}\n public static String getProjectPath(){ return userSetting.pathDefaultProject;}\n public static void setProjectPath(String path){\n userSetting.pathDefaultProject = path; // set variable\n userSetting.exportJson(); // export object\n FileOperations.generateDirectories(); // refresh directories\n }\n public static String getSaveFolder(){return userSetting.pathExportSaveFolder;}\n public static String getSaveFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathExportSaveFolder).toString();}\n public static String getTemplateFolder(){return userSetting.pathSourceTemplateFolder;}\n public static String getTemplateFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathSourceTemplateFolder).toString();}\n public static String getRenderFolder(){return userSetting.pathExportImageFolder;}\n public static String getExportFolderPath(){return Paths.get(userSetting.pathDefaultProject, userSetting.pathExportImageFolder).toString();}\n\n // endregion\n}"
},
{
"identifier": "ColorAdapter",
"path": "src/system/backbone/ColorAdapter.java",
"snippet": "public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Color> {\n @Override\n public Color deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {\n return Color.decode(jsonElement.getAsString());\n }\n\n @Override\n public JsonElement serialize(Color color, Type type, JsonSerializationContext jsonSerializationContext) {\n // get numbers representation\n return new JsonPrimitive(color.getRGB());\n }\n}"
},
{
"identifier": "RendererTypeAdapter",
"path": "src/system/layerTree/RendererTypeAdapter.java",
"snippet": "public class RendererTypeAdapter implements JsonDeserializer {\n @Override\n public Object deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {\n // retrieve json\n JsonObject json = jsonElement.getAsJsonObject();\n\n // case switching for type\n // if type is image, use ImageLayer\n if (json.get(\"type\").getAsString().equals(\"layer\"))\n return jsonDeserializationContext.deserialize(jsonElement, Layer.class);\n // if type is folder, use FolderLayer\n if (json.get(\"type\").getAsString().equals(\"folder\"))\n return jsonDeserializationContext.deserialize(jsonElement, Folder.class);\n\n // if unknown type, return nothing\n return null;\n }\n}"
},
{
"identifier": "TreeUnit",
"path": "src/system/layerTree/data/TreeUnit.java",
"snippet": "public abstract class TreeUnit {\n\n //Existing Types: layer, folder\n\n //type differentiation\n @Expose\n @SerializedName(value = \"type\")\n public final String type;\n\n protected TreeUnit(String type) {\n this.type = type;\n }\n\n\n // parent --------------------------------\n // Purpose: track parent for filestructure tree\n // Note: not saved to JSON file to maintain directed acyclic graph properties; generated on load by V1.Layer Manager\n\n private LayerTreeFolder parent = null;\n\n // accessor\n public LayerTreeFolder getParent(){\n return parent;\n }\n\n // mutator\n public void setParent(LayerTreeFolder source){\n parent = source;\n }\n\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import system.Program;
import system.backbone.ColorAdapter;
import system.layerTree.RendererTypeAdapter;
import system.layerTree.data.TreeUnit;
import java.awt.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths; | 3,476 | package system.setting;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
// settings container class
// loads, saves, etc the settings
// on change to folder paths, call generateDirectories [makes sure all referenced path directories actually exist]
public class UserSetting {
// region save/load functionality --------------------------------
// default control file
private final static String fileName = "settings.json";
// GSON builder
private static final Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag
.setPrettyPrinting() // creates a pretty version of the output | package system.setting;
//====================================================================================================
// Authors: Hikaito
// Project: Fox Engine
//====================================================================================================
// settings container class
// loads, saves, etc the settings
// on change to folder paths, call generateDirectories [makes sure all referenced path directories actually exist]
public class UserSetting {
// region save/load functionality --------------------------------
// default control file
private final static String fileName = "settings.json";
// GSON builder
private static final Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag
.setPrettyPrinting() // creates a pretty version of the output | .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter | 1 | 2023-11-12 21:12:21+00:00 | 4k |
shizotoaster/thaumon | forge/src/main/java/jdlenl/thaumon/forge/ThaumonForge.java | [
{
"identifier": "Thaumon",
"path": "common/src/main/java/jdlenl/thaumon/Thaumon.java",
"snippet": "public class Thaumon {\n public static final String MOD_ID = \"thaumon\";\n public static Logger logger = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n ThaumonItems.init();\n ThaumonBlocks.init();\n }\n}"
},
{
"identifier": "ThaumonBlocksImpl",
"path": "forge/src/main/java/jdlenl/thaumon/block/forge/ThaumonBlocksImpl.java",
"snippet": "public class ThaumonBlocksImpl {\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Thaumon.MOD_ID);\n\n public static <T extends Block> Supplier<T> registerBlock(String id, Supplier<T> supplier, boolean genItem) {\n RegistryObject<T> object = BLOCKS.register(id, supplier);\n if (genItem) {\n ThaumonItemsImpl.ITEMS.register(id, () -> new BlockItem(object.get(), new Item.Settings()));\n }\n return (Supplier<T>) object;\n }\n}"
},
{
"identifier": "ColorRegistrationHandlers",
"path": "forge/src/main/java/jdlenl/thaumon/color/forge/ColorRegistrationHandlers.java",
"snippet": "public class ColorRegistrationHandlers {\n @SubscribeEvent\n public static void onBlockColorHandlerRegistration(RegisterColorHandlersEvent.Block event) {\n event.register(new BlockColorProvider() {\n @Override\n public int getColor(BlockState state, @Nullable BlockRenderView world, @Nullable BlockPos pos, int tintIndex) {\n if (world != null && pos != null) {\n return BiomeColors.getFoliageColor(world, pos);\n }\n return FoliageColors.getDefaultColor();\n }\n }, GREATWOOD_LEAVES.get());\n }\n\n @SubscribeEvent\n public static void onItemColorHandlerRegistration(RegisterColorHandlersEvent.Item event) {\n event.register(new ItemColorProvider() {\n @Override\n public int getColor(ItemStack stack, int tintIndex) {\n return FoliageColors.getDefaultColor();\n }\n }, GREATWOOD_LEAVES.get().asItem());\n }\n}"
},
{
"identifier": "ThaumonItemsImpl",
"path": "forge/src/main/java/jdlenl/thaumon/item/forge/ThaumonItemsImpl.java",
"snippet": "public class ThaumonItemsImpl {\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Thaumon.MOD_ID);\n\n public static <T extends Item> Supplier<T> registerItem(String id, Supplier<T> supplier) {\n RegistryObject<T> object = ITEMS.register(id, supplier);\n return (Supplier<T>) object;\n }\n}"
},
{
"identifier": "ThaumonItemGroupForge",
"path": "forge/src/main/java/jdlenl/thaumon/itemgroup/forge/ThaumonItemGroupForge.java",
"snippet": "public class ThaumonItemGroupForge {\n public static final DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(RegistryKeys.ITEM_GROUP, Thaumon.MOD_ID);\n\n public static final Supplier<ItemGroup> THAUMON_GROUP = ITEM_GROUPS.register(\"thaumon_item_group\",\n () -> ItemGroup.builder().displayName(Text.translatable(\"itemgroup.thaumon.thaumon_item_group\")).icon(() -> new ItemStack(ThaumonBlocks.ELDRITCH_LANTERN.get().asItem()))\n .entries(((displayContext, entries) -> {\n entries.add(ThaumonBlocks.AMBER.get());\n entries.add(ThaumonBlocks.AMBER_STAIRS.get());\n entries.add(ThaumonBlocks.AMBER_SLAB.get());\n entries.add(ThaumonBlocks.AMBER_BRICKS.get());\n entries.add(ThaumonBlocks.AMBER_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.AMBER_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.AMBERGLASS.get());\n entries.add(ThaumonBlocks.AMBERGLASS_PANE.get());\n\n entries.add(ThaumonBlocks.GREATWOOD_LOG.get());\n entries.add(ThaumonBlocks.GREATWOOD_WOOD.get());\n entries.add(ThaumonBlocks.GREATWOOD_LOG_WALL.get());\n entries.add(ThaumonBlocks.GREATWOOD_LOG_POST.get());\n entries.add(ThaumonBlocks.GREATWOOD_PLANKS.get());\n entries.add(ThaumonBlocks.GREATWOOD_STAIRS.get());\n entries.add(ThaumonBlocks.GREATWOOD_SLAB.get());\n entries.add(ThaumonBlocks.GREATWOOD_DOOR.get());\n entries.add(ThaumonBlocks.GREATWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.GILDED_GREATWOOD_DOOR.get());\n entries.add(ThaumonBlocks.GILDED_GREATWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.GREATWOOD_FENCE.get());\n entries.add(ThaumonBlocks.GREATWOOD_FENCE_GATE.get());\n entries.add(ThaumonBlocks.GREATWOOD_WINDOW.get());\n entries.add(ThaumonBlocks.GREATWOOD_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.EMPTY_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.CLASSIC_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.DUSTY_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.ALCHEMISTS_GREATWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.GREATWOOD_GRIMOIRE_BOOKSHELF.get());\n\n entries.add(ThaumonBlocks.SILVERWOOD_LOG.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WOOD.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LOG_WALL.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LOG_POST.get());\n entries.add(ThaumonBlocks.SILVERWOOD_PLANKS.get());\n entries.add(ThaumonBlocks.SILVERWOOD_STAIRS.get());\n entries.add(ThaumonBlocks.SILVERWOOD_SLAB.get());\n entries.add(ThaumonBlocks.SILVERWOOD_DOOR.get());\n entries.add(ThaumonBlocks.SILVERWOOD_TRAPDOOR.get());\n entries.add(ThaumonBlocks.SILVERWOOD_FENCE.get());\n entries.add(ThaumonBlocks.SILVERWOOD_FENCE_GATE.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WINDOW.get());\n entries.add(ThaumonBlocks.SILVERWOOD_WINDOW_PANE.get());\n entries.add(ThaumonBlocks.EMPTY_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.CLASSIC_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.DUSTY_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.ALCHEMISTS_SILVERWOOD_BOOKSHELF.get());\n entries.add(ThaumonBlocks.SILVERWOOD_GRIMOIRE_BOOKSHELF.get());\n\n entries.add(ThaumonBlocks.ARCANE_STONE.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_SlAB.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WALL.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ARCANE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.LARGE_ARCANE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_TILES.get());\n entries.add(ThaumonBlocks.ARCANE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ARCANE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.RUNIC_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.ARCANE_LANTERN.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ARCANE_STONE_WINDOW_PANE.get());\n\n entries.add(ThaumonBlocks.ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WALL.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILES.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_CAPSTONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_FACADE.get());\n entries.add(ThaumonBlocks.CHISELED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.CARVED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ENGRAVED_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.TILED_ARCANE_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ELDRITCH_STONE.get());\n entries.add(ThaumonBlocks.ELDRITCH_LANTERN.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ELDRITCH_STONE_WINDOW_PANE.get());\n\n entries.add(ThaumonBlocks.ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WALL.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_STAIRS.get());\n entries.add(ThaumonBlocks.POLISHED_ANCIENT_STONE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICKS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_BRICK_WALL.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILES.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_STAIRS.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_TILE_SLAB.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_DOOR.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_PILLAR.get());\n entries.add(ThaumonBlocks.ENGRAVED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.CHISELED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.RUNIC_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.TILED_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.INLAID_ANCIENT_STONE.get());\n entries.add(ThaumonBlocks.ANCIENT_LANTERN.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW.get());\n entries.add(ThaumonBlocks.ANCIENT_STONE_WINDOW_PANE.get());\n\n entries.add(ThaumonBlocks.GREATWOOD_LEAVES.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAVES.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAF_POST.get());\n entries.add(ThaumonBlocks.SILVERWOOD_LEAF_WALL.get());\n\n entries.add(ThaumonBlocks.GRIMOIRE.get());\n entries.add(ThaumonBlocks.GRIMOIRE_STACK.get());\n entries.add(ThaumonBlocks.RESEARCH_NOTES.get());\n entries.add(ThaumonBlocks.CRYSTAL_LAMP.get());\n entries.add(ThaumonBlocks.RETORT.get());\n entries.add(ThaumonBlocks.VIAL_RACK.get());\n entries.add(ThaumonBlocks.CRYSTAL_STAND.get());\n\n entries.add(ThaumonItems.MUTAGEN.get());\n })).build()\n );\n}"
}
] | import jdlenl.thaumon.Thaumon;
import jdlenl.thaumon.block.forge.ThaumonBlocksImpl;
import jdlenl.thaumon.color.forge.ColorRegistrationHandlers;
import jdlenl.thaumon.item.forge.ThaumonItemsImpl;
import jdlenl.thaumon.itemgroup.forge.ThaumonItemGroupForge;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; | 3,453 | package jdlenl.thaumon.forge;
@Mod(Thaumon.MOD_ID)
public class ThaumonForge {
public ThaumonForge() {
Thaumon.init();
IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
ThaumonItemGroupForge.ITEM_GROUPS.register(eventBus); | package jdlenl.thaumon.forge;
@Mod(Thaumon.MOD_ID)
public class ThaumonForge {
public ThaumonForge() {
Thaumon.init();
IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus();
ThaumonItemGroupForge.ITEM_GROUPS.register(eventBus); | ThaumonBlocksImpl.BLOCKS.register(eventBus); | 1 | 2023-11-16 06:03:29+00:00 | 4k |
KomnisEvangelos/GeoApp | app/src/main/java/gr/ihu/geoapp/ui/home/HomeFragment.java | [
{
"identifier": "Image",
"path": "app/src/main/java/gr/ihu/geoapp/models/Image.java",
"snippet": "public class Image {\n private String id;\n private String path;\n private String title;\n private String description;\n private String tags_csv;\n //private String location;\n\n /**\n * Constructs an Image object with the specified id, path, title, description, and tags.\n *\n * @param id the id of the image\n * @param path the path of the image\n * @param title the title of the image\n * @param description the description of the image\n * @param tags_csv the tags of the image in CSV format\n */\n public Image(String id, String path, String title, String description, String tags_csv) {\n this.id = id;\n this.path = path;\n this.title = title;\n this.description = description;\n this.tags_csv = tags_csv;\n }\n\n /**\n * Constructs an Image object with the specified title, description, and tags.\n * The id and path of the image are left unspecified.\n *\n * @param title the title of the image\n * @param description the description of the image\n * @param tags_csv the tags of the image in CSV format\n */\n public Image(String title, String description, String tags_csv) {\n this.id = id;\n this.path = path;\n this.title = title;\n this.description = description;\n this.tags_csv = tags_csv;\n }\n\n /**\n * Gets the id of the image.\n *\n * @return the id of the image\n */\n public String getId() {\n return id;\n }\n\n /**\n * Sets the id of the image.\n *\n * @param id the id of the image\n */\n public void setId(String id) {\n this.id = id;\n }\n /**\n * Gets the path of the image.\n *\n * @return the path of the image\n */\n public String getPath() {\n return path;\n }\n /**\n * Sets the path of the image.\n *\n * @param path the path of the image\n */\n public void setPath(String path) {\n this.path = path;\n }\n /**\n * Gets the title of the image.\n *\n * @return the title of the image\n */\n public String getTitle() {\n return title;\n }\n /**\n * Sets the title of the image.\n *\n * @param title the title of the image\n */\n public void setTitle(String title) {\n this.title = title;\n }\n /**\n * Gets the description of the image.\n *\n * @return the description of the image\n */\n public String getDescription() {\n return description;\n }\n /**\n * Sets the description of the image.\n *\n * @param description the description of the image\n */\n public void setDescription(String description) {\n this.description = description;\n }\n /**\n * Gets the tags of the image in CSV format.\n *\n * @return the tags of the image in CSV format\n */\n public String getTags_csv() {\n return tags_csv;\n }\n /**\n * Sets the tags of the image in CSV format.\n *\n * @param tags_csv the tags of the image in CSV format\n */\n public void setTags_csv(String tags_csv) {\n this.tags_csv = tags_csv;\n }\n}"
},
{
"identifier": "RegularUser",
"path": "app/src/main/java/gr/ihu/geoapp/models/users/RegularUser.java",
"snippet": "public class RegularUser{\n private String user_id;\n private String full_name;\n private String password;\n private String email;\n private String birthdate;\n private String job;\n private String diploma;\n private String api_key;\n private List<Image> imageList;\n\n private static RegularUser instance;\n\n private RegularUser() {\n this.user_id = \"N/A\";\n this.full_name = \"N/A\";\n this.email = \"N/A\";\n this.birthdate = \"N/A\";\n this.job = \"N/A\";\n this.diploma = \"N/A\";\n this.imageList = new ArrayList<>();\n }\n\n public static RegularUser getInstance() {\n if (instance == null) {\n instance = new RegularUser();\n }\n return instance;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUserId() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param userId the user's ID\n */\n public void setUserId(String userId) {\n this.user_id = userId;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFullName() {\n return full_name;\n }\n\n /**\n * Sets the full name of the user.\n *\n * @param fullName the user's full name\n */\n public void setFullName(String fullName) {\n this.full_name = fullName;\n }\n\n /**\n * Gets the email of the user.\n *\n * @return the user's email\n */\n public String getEmail() {\n return email;\n }\n\n /**\n * Sets the email of the user.\n *\n * @param email the user's email\n */\n public void setEmail(String email) {\n this.email = email;\n }\n\n /**\n * Gets the birth date of the user.\n *\n * @return the user's birth date\n */\n public String getBirthdate() {\n return birthdate;\n }\n\n /**\n * Sets the birth date of the user.\n *\n * @param birthdate the user's birth date\n */\n public void setBirthdate(String birthdate) {\n this.birthdate = birthdate;\n }\n\n /**\n * Gets the job of the user.\n *\n * @return the user's job\n */\n public String getJob() {\n return job;\n }\n\n /**\n * Sets the job of the user.\n *\n * @param job the user's job\n */\n public void setJob(String job) {\n this.job = job;\n }\n\n /**\n * Gets the diploma of the user.\n *\n * @return the user's diploma\n */\n public String getDiploma() {\n return diploma;\n }\n\n /**\n * Sets the diploma of the user.\n *\n * @param diploma the user's diploma\n */\n public void setDiploma(String diploma) {\n this.diploma = diploma;\n }\n\n /**\n * Sets the singleton instance of the RegularUser class.\n *\n * @param instance the instance to set\n */\n public static void setInstance(RegularUser instance) {\n RegularUser.instance = instance;\n }\n\n /**\n * Gets the password of the user.\n *\n * @return the user's password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Sets the password of the user.\n *\n * @param password the user's password\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Gets the API key of the user.\n *\n * @return the user's API key\n */\n public String getApi_key() {\n return api_key;\n }\n\n /**\n * Sets the API key of the user.\n *\n * @param api_key the user's API key\n */\n public void setApi_key(String api_key) {\n this.api_key = api_key;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUser_id() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param user_id the user's ID\n */\n public void setUser_id(String user_id) {\n this.user_id = user_id;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFull_name() {\n return full_name;\n }\n /**\n * Sets the full name of the user.\n *\n * @param full_name the user's full name\n */\n public void setFull_name(String full_name) {\n this.full_name = full_name;\n }\n\n /**\n * Gets the list of images associated with the user.\n *\n * @return the list of images\n */\n public List<Image> getImageList() {\n return imageList;\n }\n\n /**\n * Sets the list of images associated with the user.\n *\n * @param imageList the list of images\n */\n public void setImageList(List<Image> imageList) {\n this.imageList = imageList;\n }\n}"
}
] | import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import java.util.List;
import gr.ihu.geoapp.databinding.FragmentHomeBinding;
import gr.ihu.geoapp.models.Image;
import gr.ihu.geoapp.models.users.RegularUser; | 2,606 | package gr.ihu.geoapp.ui.home;
/**
* This class represents the Home Fragment in the application.
* It displays a simple text view.
*/
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
private GridView gridView;
/**
* Initializes the view of the fragment.
* Sets up the observer for the text view.
*
* @param inflater the LayoutInflater to inflate the view
* @param container the container for the view
* @param savedInstanceState the saved instance state
* @return the view of the fragment
*/
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
//final TextView textView = binding.textHome;
//homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
gridView = binding.homeGridView;
| package gr.ihu.geoapp.ui.home;
/**
* This class represents the Home Fragment in the application.
* It displays a simple text view.
*/
public class HomeFragment extends Fragment {
private FragmentHomeBinding binding;
private GridView gridView;
/**
* Initializes the view of the fragment.
* Sets up the observer for the text view.
*
* @param inflater the LayoutInflater to inflate the view
* @param container the container for the view
* @param savedInstanceState the saved instance state
* @return the view of the fragment
*/
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
//final TextView textView = binding.textHome;
//homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
gridView = binding.homeGridView;
| List<Image> imageList = RegularUser.getInstance().getImageList(); | 0 | 2023-11-10 17:43:18+00:00 | 4k |
Nel1yMinecraft/Grim | src/main/java/ac/grim/grimac/utils/nmsutil/BoundingBoxSize.java | [
{
"identifier": "PacketEntity",
"path": "src/main/java/ac/grim/grimac/utils/data/packetentity/PacketEntity.java",
"snippet": "public class PacketEntity {\n public Vector3d serverPos;\n public int lastTransactionHung;\n public EntityType type;\n public org.bukkit.entity.EntityType bukkitEntityType;\n\n public PacketEntity riding;\n public int[] passengers = new int[0];\n public boolean isDead = false;\n public boolean isBaby = false;\n public boolean hasGravity = true;\n private ReachInterpolationData oldPacketLocation;\n private ReachInterpolationData newPacketLocation;\n\n public PacketEntity(GrimPlayer player, EntityType type, double x, double y, double z) {\n this.serverPos = new Vector3d(x, y, z);\n this.type = type;\n this.bukkitEntityType = org.bukkit.entity.EntityType.valueOf(type.toString().toUpperCase(Locale.ROOT));\n this.newPacketLocation = new ReachInterpolationData(GetBoundingBox.getPacketEntityBoundingBox(x, y, z, this),\n serverPos.getX(), serverPos.getY(), serverPos.getZ(), player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9));\n }\n\n // Set the old packet location to the new one\n // Set the new packet location to the updated packet location\n public void onFirstTransaction(double x, double y, double z, GrimPlayer player) {\n this.oldPacketLocation = newPacketLocation;\n this.newPacketLocation = new ReachInterpolationData(oldPacketLocation.getPossibleLocationCombined(), x, y, z, player.getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9));\n }\n\n // Remove the possibility of the old packet location\n public void onSecondTransaction() {\n this.oldPacketLocation = null;\n }\n\n // If the old and new packet location are split, we need to combine bounding boxes\n public void onMovement() {\n newPacketLocation.tickMovement(oldPacketLocation == null);\n\n // Handle uncertainty of second transaction spanning over multiple ticks\n if (oldPacketLocation != null) {\n oldPacketLocation.tickMovement(true);\n newPacketLocation.updatePossibleStartingLocation(oldPacketLocation.getPossibleLocationCombined());\n }\n }\n\n public boolean hasPassenger(int entityID) {\n for (int passenger : passengers) {\n if (passenger == entityID) return true;\n }\n return false;\n }\n\n // This is for handling riding and entities attached to one another.\n public void setPositionRaw(SimpleCollisionBox box) {\n this.newPacketLocation = new ReachInterpolationData(box);\n }\n\n public SimpleCollisionBox getPossibleCollisionBoxes() {\n if (oldPacketLocation == null) {\n return newPacketLocation.getPossibleLocationCombined();\n }\n\n return ReachInterpolationData.combineCollisionBox(oldPacketLocation.getPossibleLocationCombined(), newPacketLocation.getPossibleLocationCombined());\n }\n\n @Override\n public String toString() {\n return \"PlayerReachEntity{\" +\n \"serverPos=\" + serverPos +\n \", oldPacketLocation=\" + oldPacketLocation +\n \", newPacketLocation=\" + newPacketLocation +\n '}';\n }\n}"
},
{
"identifier": "PacketEntityHorse",
"path": "src/main/java/ac/grim/grimac/utils/data/packetentity/PacketEntityHorse.java",
"snippet": "public class PacketEntityHorse extends PacketEntity {\n\n public boolean isRearing = false;\n public boolean hasSaddle = false;\n public float jumpStrength = 0.7f;\n public float movementSpeedAttribute = 0.1f;\n\n // I give up with handling jump boost potions\n // I can't figure out which packet give a horse potion effects\n // Anyways, what's the chances of a plugin:\n // 1) Summoning a horse with packet without a real entity id\n // 2) Having the player ride this horse\n // 3) Giving the horse jump boost, somehow, not sure which packet it is\n //\n // If any one of the three scenarios is false, we are fine\n // If you do see a plugin doing this, please tell me which packet it is\n\n public PacketEntityHorse(GrimPlayer player, ac.grim.grimac.utils.enums.EntityType type, double x, double y, double z) {\n super(player, type, x, y, z);\n }\n}"
},
{
"identifier": "PacketEntitySizeable",
"path": "src/main/java/ac/grim/grimac/utils/data/packetentity/PacketEntitySizeable.java",
"snippet": "public class PacketEntitySizeable extends PacketEntity {\n public int size = 1;\n\n public PacketEntitySizeable(GrimPlayer player, ac.grim.grimac.utils.enums.EntityType type, double x, double y, double z) {\n super(player, type, x, y, z);\n }\n}"
},
{
"identifier": "EntityType",
"path": "src/main/java/ac/grim/grimac/utils/enums/EntityType.java",
"snippet": "public enum EntityType {\n AREA_EFFECT_CLOUD,\n ARMOR_STAND,\n ARROW,\n AXOLOTL,\n BAT,\n BEE,\n BLAZE,\n BOAT,\n CAT,\n CAVE_SPIDER,\n CHICKEN,\n COD,\n COW,\n CREEPER,\n DOLPHIN,\n DONKEY,\n DRAGON_FIREBALL,\n DROPPED_ITEM,\n DROWNED,\n EGG,\n ELDER_GUARDIAN,\n ENDERMAN,\n ENDERMITE,\n ENDER_CRYSTAL,\n ENDER_DRAGON,\n ENDER_PEARL,\n ENDER_SIGNAL,\n EVOKER,\n EVOKER_FANGS,\n EXPERIENCE_ORB,\n FALLING_BLOCK,\n FIREBALL,\n FIREWORK,\n FISHING_HOOK,\n FOX,\n GHAST,\n GIANT,\n GLOW_ITEM_FRAME,\n GLOW_SQUID,\n GOAT,\n GUARDIAN,\n HOGLIN,\n HORSE,\n HUSK,\n ILLUSIONER,\n IRON_GOLEM,\n ITEM_FRAME,\n LEASH_HITCH,\n LIGHTNING,\n LLAMA,\n LLAMA_SPIT,\n MAGMA_CUBE,\n MARKER,\n MINECART,\n MINECART_CHEST,\n MINECART_COMMAND,\n MINECART_FURNACE,\n MINECART_HOPPER,\n MINECART_MOB_SPAWNER,\n MINECART_TNT,\n MULE,\n MUSHROOM_COW,\n OCELOT,\n PAINTING,\n PANDA,\n PARROT,\n PHANTOM,\n PIG,\n PIGLIN,\n PIGLIN_BRUTE,\n PILLAGER,\n PLAYER,\n POLAR_BEAR,\n PRIMED_TNT,\n PUFFERFISH,\n RABBIT,\n RAVAGER,\n SALMON,\n SHEEP,\n SHULKER,\n SHULKER_BULLET,\n SILVERFISH,\n SKELETON,\n SKELETON_HORSE,\n SLIME,\n SMALL_FIREBALL,\n SNOWBALL,\n SNOWMAN,\n SPECTRAL_ARROW,\n SPIDER,\n SPLASH_POTION,\n SQUID,\n STRAY,\n STRIDER,\n THROWN_EXP_BOTTLE,\n TRADER_LLAMA,\n TRIDENT,\n TROPICAL_FISH,\n TURTLE,\n VEX,\n VILLAGER,\n VINDICATOR,\n WANDERING_TRADER,\n WITCH,\n WITHER,\n WITHER_SKELETON,\n WITHER_SKULL,\n WOLF,\n ZOGLIN,\n ZOMBIE,\n ZOMBIE_HORSE,\n ZOMBIE_VILLAGER,\n ZOMBIFIED_PIGLIN;\n\n public static boolean isHorse(EntityType type) {\n switch (type) {\n case DONKEY:\n case HORSE:\n case LLAMA:\n case MULE:\n case SKELETON_HORSE:\n case ZOMBIE_HORSE:\n case TRADER_LLAMA:\n return true;\n default:\n return false;\n }\n }\n\n public static boolean isMinecart(EntityType type) {\n switch (type) {\n case MINECART:\n case MINECART_CHEST:\n case MINECART_COMMAND:\n case MINECART_FURNACE:\n case MINECART_HOPPER:\n case MINECART_MOB_SPAWNER:\n case MINECART_TNT:\n return true;\n default:\n return false;\n }\n }\n\n public static boolean isLivingEntity(org.bukkit.entity.EntityType type) {\n return (type.getEntityClass() != null && LivingEntity.class.isAssignableFrom(type.getEntityClass()));\n }\n\n public static boolean isAgeableEntity(org.bukkit.entity.EntityType type) {\n return (type.getEntityClass() != null && Ageable.class.isAssignableFrom(type.getEntityClass()));\n }\n\n public static boolean isAnimal(org.bukkit.entity.EntityType type) {\n return (type.getEntityClass() != null && Animals.class.isAssignableFrom(type.getEntityClass()));\n }\n\n public static boolean isSize(org.bukkit.entity.EntityType type) {\n if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_13) && type == org.bukkit.entity.EntityType.PHANTOM)\n return true;\n\n return type == org.bukkit.entity.EntityType.SLIME || type == org.bukkit.entity.EntityType.MAGMA_CUBE;\n }\n}"
}
] | import ac.grim.grimac.utils.data.packetentity.PacketEntity;
import ac.grim.grimac.utils.data.packetentity.PacketEntityHorse;
import ac.grim.grimac.utils.data.packetentity.PacketEntitySizeable;
import ac.grim.grimac.utils.enums.EntityType; | 3,483 | case SKELETON_HORSE:
case MULE:
case ZOMBIE_HORSE:
case HORSE:
case ZOGLIN:
return 1.39648;
case BOAT:
return 1.375;
case CHICKEN:
case ENDERMITE:
case RABBIT:
case SILVERFISH:
case VEX:
return 0.4;
case STRIDER:
case COW:
case SHEEP:
case MUSHROOM_COW:
case PIG:
case LLAMA:
case DOLPHIN:
case WITHER:
case TRADER_LLAMA:
return 0.9;
case PHANTOM:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.9 + ((PacketEntitySizeable) packetEntity).size * 0.2;
}
case DONKEY:
return 1.5;
case ELDER_GUARDIAN:
return 1.9975;
case ENDER_CRYSTAL:
return 2.0;
case ENDER_DRAGON:
return 16.0;
case FIREBALL:
return 1;
case GHAST:
return 4.0;
case GIANT:
return 3.6;
case GUARDIAN:
return 0.85;
case IRON_GOLEM:
return 1.4;
case MAGMA_CUBE:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.51000005 * ((PacketEntitySizeable) packetEntity).size;
}
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
return 0.98;
case PLAYER:
return 0.6;
case POLAR_BEAR:
return 1.4;
case RAVAGER:
return 1.95;
case SHULKER:
return 1.0;
case SLIME:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.51000005 * ((PacketEntitySizeable) packetEntity).size;
}
case SMALL_FIREBALL:
return 0.3125;
case SPIDER:
return 1.4;
case SQUID:
return 0.8;
case TURTLE:
return 1.2;
default:
return 0.6;
}
}
public static double getHeight(PacketEntity packetEntity) {
// Turtles are the only baby animal that don't follow the * 0.5 rule
if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.12;
return getHeightMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1);
}
public static double getMyRidingOffset(PacketEntity packetEntity) {
switch (packetEntity.type) {
case PIGLIN:
case ZOMBIFIED_PIGLIN:
case ZOMBIE:
return packetEntity.isBaby ? -0.05 : -0.45;
case SKELETON:
return -0.6;
case ENDERMITE:
case SILVERFISH:
return 0.1;
case EVOKER:
case ILLUSIONER:
case PILLAGER:
case RAVAGER:
case VINDICATOR:
case WITCH:
return -0.45;
case PLAYER:
return -0.35;
}
if (EntityType.isAnimal(packetEntity.bukkitEntityType)) {
return 0.14;
}
return 0;
}
public static double getPassengerRidingOffset(PacketEntity packetEntity) {
| package ac.grim.grimac.utils.nmsutil;
public class BoundingBoxSize {
public static double getWidth(PacketEntity packetEntity) {
// Turtles are the only baby animal that don't follow the * 0.5 rule
if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.36;
return getWidthMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1);
}
private static double getWidthMinusBaby(PacketEntity packetEntity) {
switch (packetEntity.type) {
case AXOLOTL:
case PANDA:
return 1.3;
case BAT:
case PARROT:
case COD:
case EVOKER_FANGS:
case TROPICAL_FISH:
return 0.5;
case BEE:
case PUFFERFISH:
case SALMON:
case SNOWMAN:
case WITHER_SKELETON:
case CAVE_SPIDER:
return 0.7;
case WITHER_SKULL:
case SHULKER_BULLET:
return 0.3125;
case BLAZE:
case OCELOT:
case STRAY:
case HOGLIN:
case SKELETON_HORSE:
case MULE:
case ZOMBIE_HORSE:
case HORSE:
case ZOGLIN:
return 1.39648;
case BOAT:
return 1.375;
case CHICKEN:
case ENDERMITE:
case RABBIT:
case SILVERFISH:
case VEX:
return 0.4;
case STRIDER:
case COW:
case SHEEP:
case MUSHROOM_COW:
case PIG:
case LLAMA:
case DOLPHIN:
case WITHER:
case TRADER_LLAMA:
return 0.9;
case PHANTOM:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.9 + ((PacketEntitySizeable) packetEntity).size * 0.2;
}
case DONKEY:
return 1.5;
case ELDER_GUARDIAN:
return 1.9975;
case ENDER_CRYSTAL:
return 2.0;
case ENDER_DRAGON:
return 16.0;
case FIREBALL:
return 1;
case GHAST:
return 4.0;
case GIANT:
return 3.6;
case GUARDIAN:
return 0.85;
case IRON_GOLEM:
return 1.4;
case MAGMA_CUBE:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.51000005 * ((PacketEntitySizeable) packetEntity).size;
}
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
return 0.98;
case PLAYER:
return 0.6;
case POLAR_BEAR:
return 1.4;
case RAVAGER:
return 1.95;
case SHULKER:
return 1.0;
case SLIME:
if (packetEntity instanceof PacketEntitySizeable) {
return 0.51000005 * ((PacketEntitySizeable) packetEntity).size;
}
case SMALL_FIREBALL:
return 0.3125;
case SPIDER:
return 1.4;
case SQUID:
return 0.8;
case TURTLE:
return 1.2;
default:
return 0.6;
}
}
public static double getHeight(PacketEntity packetEntity) {
// Turtles are the only baby animal that don't follow the * 0.5 rule
if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.12;
return getHeightMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1);
}
public static double getMyRidingOffset(PacketEntity packetEntity) {
switch (packetEntity.type) {
case PIGLIN:
case ZOMBIFIED_PIGLIN:
case ZOMBIE:
return packetEntity.isBaby ? -0.05 : -0.45;
case SKELETON:
return -0.6;
case ENDERMITE:
case SILVERFISH:
return 0.1;
case EVOKER:
case ILLUSIONER:
case PILLAGER:
case RAVAGER:
case VINDICATOR:
case WITCH:
return -0.45;
case PLAYER:
return -0.35;
}
if (EntityType.isAnimal(packetEntity.bukkitEntityType)) {
return 0.14;
}
return 0;
}
public static double getPassengerRidingOffset(PacketEntity packetEntity) {
| if (packetEntity instanceof PacketEntityHorse) | 1 | 2023-11-11 05:14:12+00:00 | 4k |
ImShyMike/QuestCompassPlus | src/main/java/shymike/questcompassplus/QuestCompassPlus.java | [
{
"identifier": "CommandRegister",
"path": "src/main/java/shymike/questcompassplus/commands/CommandRegister.java",
"snippet": "public class CommandRegister {\n\tstatic public void run() {\n\t\tMinecraftClient mc = MinecraftClient.getInstance();\n\t\tClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> {\n\t\t\tLiteralCommandNode<FabricClientCommandSource> mainNode = ClientCommandManager\n\t\t\t\t.literal(\"qcp\")\n\t\t\t\t.executes(context -> {\n\t\t\t throw new SimpleCommandExceptionType(Text.literal(\"Invalid usage. Use \\\"/qcp help\\\" for more information.\")).create();\n\t\t\t })\n\t\t\t .build();\n\t\t\n\t\t LiteralCommandNode<FabricClientCommandSource> helpNode = ClientCommandManager\n\t\t \t.literal(\"help\")\n\t\t\t\t.executes(context -> {\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Quest Compass Plus commands:\"));\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"/qcp help - Display this help message\"));\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"/qcp toggle - Toggle the mod on/off\"));\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"/qcp get - Get current quest location\"));\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"/qcp settings - Change settings\"));\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"/qcp debug - For debugging\"));\n\t\t\t \t\treturn 1;\n\t\t\t \t})\n\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> toggleNode = ClientCommandManager\n\t\t \t.literal(\"toggle\")\n\t\t\t\t.executes(context -> {\n\t\t\t\t\tConfig.toggleIsModEnabled();\n\t\t\t\t\tif (!Config.isModEnabled) { RenderUtils.line1 = \"\"; RenderUtils.line2 = \"\"; } else { RenderUtils.line1 = \"Compass Position: \" + (int)RenderUtils.x + \" \" + (int)RenderUtils.y + \" \" + (int)RenderUtils.z; }\n\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Quest Compass Plus is now \" + (Config.isModEnabled ? \"enabled\" : \"disabled\")));\n\t\t\t \t\treturn 1;\n\t\t\t \t})\n\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> getterNode = ClientCommandManager\n\t\t\t \t.literal(\"get\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t\t\tVec3d playerPos = mc.player.getPos();\n\t\t\t\t\t\tdouble distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, Config.x, Config.z));\n\t\t\t\t\t\tif (Config.waypointCopy) {\n\t\t\t\t\t\t\tcontext.getSource().sendFeedback(Text.literal(\"Compass Position: x=\" + (int)Config.x + \", y=\" + (int)Config.y + \", z=\" + (int)Config.z + \", distance=\" + (int)distance).styled(style -> style\n\t\t\t\t\t\t\t\t\t.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, \"/jm wpedit [name:\\\"Quest Location\\\", x:\"+(int)Config.x+\", y:\"+(int)Config.y+\", z:\"+(int)Config.z+\", dim:minecraft:overworld]\"))\n\t\t\t\t\t\t\t\t\t.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(\"Click to make waypoint!\")))));\n\t\t\t\t\t\t} else if (Config.chatFeedback) {\n\t\t\t\t\t\t\tcontext.getSource().sendFeedback(Text.literal(\"Compass Position: x=\" + (int)Config.x + \", y=\" + (int)Config.y + \", z=\" + (int)Config.z + \", distance=\" + (int)distance).styled(style -> style\n\t\t\t\t\t \t\t\t.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, (int)Config.x+\" \"+(int)Config.y+\" \"+(int)Config.z))\n\t\t\t\t\t \t\t\t.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(\"Click to copy coordinates to clipboard!\")))));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn 1;})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> debugNode = ClientCommandManager\n\t\t\t \t.literal(\"debug\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Is On Monumenta: \" + ServerUtils.isOnMonumenta()));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> forceDebugNode = ClientCommandManager\n\t\t\t \t.literal(\"force\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t \tServerUtils.bypass = !ServerUtils.bypass;\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Bypass is now \" + (ServerUtils.bypass ? \"enabled\" : \"disabled\")));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> settingsNode = ClientCommandManager\n\t\t\t \t.literal(\"settings\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Settings List: chat_feedback, require_compass, waypoint_create\"));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> chatFeedbackNode = ClientCommandManager\n\t\t\t \t.literal(\"chat_feedback\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t\t\tConfig.toggleChatFeedback();\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Chat feedback is now \" + (Config.chatFeedback ? \"enabled\" : \"disabled\")));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> requireCompassNode = ClientCommandManager\n\t\t\t \t.literal(\"require_compass\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t\t\tConfig.toggleRequireCompass();\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Compass required is now \" + (Config.requireCompass ? \"required\" : \"not required\")));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\t\t \n\t\t LiteralCommandNode<FabricClientCommandSource> waypointCreateNode = ClientCommandManager\n\t\t\t \t.literal(\"waypoint_create\")\n\t\t\t\t\t.executes(context -> {\n\t\t\t\t\t\tConfig.toggleWaypointCopy();\n\t\t\t\t \tcontext.getSource().sendFeedback(Text.literal(\"Waypoint create is now \" + (Config.waypointCopy ? \"enabled\" : \"disabled\")));\n\t\t\t\t \t\treturn 1;\n\t\t\t\t \t})\n\t\t\t .build();\n\n\t\t dispatcher.getRoot().addChild(mainNode);\n\t\t\t mainNode.addChild(helpNode);\n\t\t\t mainNode.addChild(toggleNode);\n\t\t\t mainNode.addChild(getterNode);\n\t\t\t mainNode.addChild(settingsNode);\n\t\t\t \tsettingsNode.addChild(chatFeedbackNode);\n\t\t\t \tsettingsNode.addChild(requireCompassNode);\n\t\t\t \tsettingsNode.addChild(waypointCreateNode);\n\t\t\t mainNode.addChild(debugNode);\n\t\t\t \tdebugNode.addChild(forceDebugNode);\n\t\t});\n\t}\n}"
},
{
"identifier": "RenderUtils",
"path": "src/main/java/shymike/questcompassplus/utils/RenderUtils.java",
"snippet": "public class RenderUtils implements HudRenderCallback {\n\tMinecraftClient mc = MinecraftClient.getInstance();\n\tpublic static String line1 = \"Compass Position: 0 0 0\";\n\tpublic static String line2 = \"\";\n\tpublic static double x = 0, y = 0, z = 0;\n\tpublic static String mainHandItem = null;\n\tpublic static boolean isDebugHudEnabled = false;\n\n public static void setCoordinates(double x, double y, double z) {\n \tRenderUtils.x = x;\n \tRenderUtils.y = y;\n \tRenderUtils.z = z;\n }\n \n @Override\n public void onHudRender(MatrixStack matrixStack, float tickDelta) {\n \tif (Config.requireCompass == true) {\n\t\t\tmainHandItem = mc.player.getInventory().getMainHandStack().getItem().toString();\n \t} else { mainHandItem = \"compass\"; }\n \ttry {\n \t\tGameOptions gameOptions = mc.options;\n \t\tRenderUtils.isDebugHudEnabled = gameOptions.debugEnabled;\n \t} catch(Exception e) {\n \t\tRenderUtils.isDebugHudEnabled = false;\n \t}\n \tif (Config.isModEnabled && ServerUtils.isOnMonumenta() && !isDebugHudEnabled && mainHandItem == \"compass\") {\n\t int x = 10, y = 10;\n\t int color = Config.color;\n\t Vec3d playerPos = mc.player.getPos();\n\t \tdouble distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, RenderUtils.x, RenderUtils.z));\n\t \tline2 = \"Distance: \" + (int)distance;\n\t \tString[] lines = {line1, line2};\n\t \tfor (String line : lines) {\n\t\t\t\tTextRenderer textRenderer = mc.textRenderer;\n\t \tText formattedText = Text.literal(line).formatted(Formatting.WHITE);;\n\t DrawableHelper.drawTextWithShadow(matrixStack, textRenderer, formattedText, x, y, color);\n\t y += textRenderer.fontHeight;\n\t \t}\n }\n }\n}"
}
] | import shymike.questcompassplus.commands.CommandRegister;
import shymike.questcompassplus.utils.RenderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; | 2,169 | package shymike.questcompassplus;
public class QuestCompassPlus implements ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("quest-compass-plus");
@Override
public void onInitializeClient() {
LOGGER.info("QuestCompassPlus Loading!");
HudRenderCallback.EVENT.register(new RenderUtils()); | package shymike.questcompassplus;
public class QuestCompassPlus implements ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("quest-compass-plus");
@Override
public void onInitializeClient() {
LOGGER.info("QuestCompassPlus Loading!");
HudRenderCallback.EVENT.register(new RenderUtils()); | CommandRegister.run(); | 0 | 2023-11-14 15:56:39+00:00 | 4k |
kawainime/IOT-Smart_Farming | ICEBURG_AccessControl_V.01/src/UI/Home.java | [
{
"identifier": "Cache_Reader",
"path": "ICEBURG_AccessControl_V.01/src/Core/Cache_Reader.java",
"snippet": "public class Cache_Reader \n{\n public static String reader(String file_name)\n {\n String user_name = null;\n \n try\n {\n String db_name = file_name;\n \n FileInputStream fis = new FileInputStream(db_name);\n \n Scanner output = new Scanner(fis); \n \n while (output.hasNext())\n {\n user_name = output.nextLine(); \n }\n \n return user_name;\n }\n catch(Exception error)\n {\n return user_name;\n }\n \n }\n\n}"
},
{
"identifier": "Log",
"path": "ICEBURG_AccessControl_V.01/src/Core/Log.java",
"snippet": "public class Log \n{\n public static void add_Log(String status)\n {\n Connection conn = Connector.connection();\n \n String Time = get_localDate.Date()+\" | \"+get_localDate.Time();\n \n String query = \"UPDATE devices SET status = '\"+status+\"', last_active = '\"+Time+\"' WHERE device_ID = \"+Cache_Reader.reader(\"device.key\")+\";\";\n \n System.out.println(query);\n \n try\n {\n PreparedStatement preparedStatement = conn.prepareStatement(query);\n\n preparedStatement.executeUpdate();\n \n }\n catch(SQLException ERROR)\n {\n JOptionPane.showMessageDialog(null,\"SQL ERROR : \\n\"+ERROR);\n }\n }\n \n}"
},
{
"identifier": "Presant_Validation",
"path": "ICEBURG_AccessControl_V.01/src/Core/Presant_Validation.java",
"snippet": "public class Presant_Validation \n{\n public static int validation_userID(String index)\n {\n Connection connection = Connector.connection();\n \n String SQL = \"SELECT * FROM employee WHERE Emp_id = \"+index+\" AND \"+Cache_Reader.reader(\"section.key\")+\" = 'true';\";\n \n try\n {\n Statement stmt = connection.createStatement();\n \n ResultSet rs = stmt.executeQuery(SQL);\n \n \n if(!rs.next())\n { \n return 0;\n }\n else\n {\n System.out.print(\"1\");\n \n return 1;\n }\n }\n catch(Exception ERROR)\n {\n System.out.println(ERROR);\n \n return 0;\n }\n }\n}"
},
{
"identifier": "User_Validation",
"path": "ICEBURG_AccessControl_V.01/src/Core/User_Validation.java",
"snippet": "public class User_Validation \n{\n public static int validation_userID(String index)\n {\n Connection connection = Connector.connection();\n \n String SQL = \"SELECT * FROM employee WHERE emp_id = \"+index+\"; \";\n \n try\n {\n Statement stmt = connection.createStatement();\n \n ResultSet rs = stmt.executeQuery(SQL);\n \n \n if(!rs.next())\n {\n System.out.print(rs.getString(\"emp_name\"));\n \n return 0;\n }\n else\n {\n System.out.print(\"1\");\n \n return 1;\n }\n }\n catch(Exception ERROR)\n {\n System.out.println(ERROR);\n \n return 0;\n }\n }\n}"
}
] | import Core.Cache_Reader;
import Core.Log;
import Core.Presant_Validation;
import Core.User_Validation;
import java.awt.Color; | 2,088 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UI;
/**
*
* @author Jayashanka Deshan
*/
public class Home extends javax.swing.JFrame {
/**
* Creates new form Home
*/
public Home() {
initComponents();
Log.add_Log("A");
}
/**
* 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();
roundPanel15 = new com.deshan.swing.RoundPanel();
jTextField8 = new javax.swing.JTextField();
time_zone = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
today = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
roundPanel15.setBackground(new java.awt.Color(255, 255, 255));
jTextField8.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
jTextField8.setForeground(new java.awt.Color(102, 102, 102));
jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField8.setText("SCAN YOUR CARD HERE");
jTextField8.setBorder(null);
jTextField8.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField8FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField8FocusLost(evt);
}
});
jTextField8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField8ActionPerformed(evt);
}
});
jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField8KeyReleased(evt);
}
});
javax.swing.GroupLayout roundPanel15Layout = new javax.swing.GroupLayout(roundPanel15);
roundPanel15.setLayout(roundPanel15Layout);
roundPanel15Layout.setHorizontalGroup(
roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
.addContainerGap())
);
roundPanel15Layout.setVerticalGroup(
roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1.add(roundPanel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(193, 450, 390, -1));
time_zone.setFont(new java.awt.Font("Yu Gothic", 1, 48)); // NOI18N
time_zone.setForeground(new java.awt.Color(102, 102, 102));
time_zone.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
time_zone.setText("10:45 P.M");
jPanel1.add(time_zone, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 800, 50));
jLabel3.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(102, 102, 102));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("ICEBURG ACCESS CONTROL");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 800, 40));
today.setFont(new java.awt.Font("Monospaced", 1, 20)); // NOI18N
today.setForeground(new java.awt.Color(102, 102, 102));
today.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
today.setText("2010.12.22");
jPanel1.add(today, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 800, 30));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/drawable/main.gif"))); // NOI18N
jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 204, 204)));
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, -1));
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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jTextField8FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusGained
if(jTextField8.getText().equals("SCAN YOUR CARD HERE"))
{
jTextField8.setText("");
jTextField8.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField8FocusGained
private void jTextField8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusLost
if(jTextField8.getText().equals(""))
{
jTextField8.setText("SCAN YOUR CARD HERE");
jTextField8.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField8FocusLost
private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField8ActionPerformed
private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
if(jTextField8.getText().length() == 10)
{ | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UI;
/**
*
* @author Jayashanka Deshan
*/
public class Home extends javax.swing.JFrame {
/**
* Creates new form Home
*/
public Home() {
initComponents();
Log.add_Log("A");
}
/**
* 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();
roundPanel15 = new com.deshan.swing.RoundPanel();
jTextField8 = new javax.swing.JTextField();
time_zone = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
today = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
roundPanel15.setBackground(new java.awt.Color(255, 255, 255));
jTextField8.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N
jTextField8.setForeground(new java.awt.Color(102, 102, 102));
jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER);
jTextField8.setText("SCAN YOUR CARD HERE");
jTextField8.setBorder(null);
jTextField8.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField8FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField8FocusLost(evt);
}
});
jTextField8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField8ActionPerformed(evt);
}
});
jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jTextField8KeyReleased(evt);
}
});
javax.swing.GroupLayout roundPanel15Layout = new javax.swing.GroupLayout(roundPanel15);
roundPanel15.setLayout(roundPanel15Layout);
roundPanel15Layout.setHorizontalGroup(
roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(roundPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
.addContainerGap())
);
roundPanel15Layout.setVerticalGroup(
roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1.add(roundPanel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(193, 450, 390, -1));
time_zone.setFont(new java.awt.Font("Yu Gothic", 1, 48)); // NOI18N
time_zone.setForeground(new java.awt.Color(102, 102, 102));
time_zone.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
time_zone.setText("10:45 P.M");
jPanel1.add(time_zone, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 800, 50));
jLabel3.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(102, 102, 102));
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText("ICEBURG ACCESS CONTROL");
jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 800, 40));
today.setFont(new java.awt.Font("Monospaced", 1, 20)); // NOI18N
today.setForeground(new java.awt.Color(102, 102, 102));
today.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
today.setText("2010.12.22");
jPanel1.add(today, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 800, 30));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/drawable/main.gif"))); // NOI18N
jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 204, 204)));
jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, -1));
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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jTextField8FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusGained
if(jTextField8.getText().equals("SCAN YOUR CARD HERE"))
{
jTextField8.setText("");
jTextField8.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField8FocusGained
private void jTextField8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusLost
if(jTextField8.getText().equals(""))
{
jTextField8.setText("SCAN YOUR CARD HERE");
jTextField8.setForeground(new Color(102,102,102));
}
}//GEN-LAST:event_jTextField8FocusLost
private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField8ActionPerformed
private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
if(jTextField8.getText().length() == 10)
{ | if(jTextField8.getText().equals(Cache_Reader.reader("Master_Card.key"))) | 0 | 2023-11-11 08:23:10+00:00 | 4k |
Outer-Fields/item-server | src/main/java/io/mindspice/itemserver/api/Internal.java | [
{
"identifier": "Settings",
"path": "src/main/java/io/mindspice/itemserver/Settings.java",
"snippet": "public class Settings {\n static Settings INSTANCE;\n\n /* Monitor */\n public volatile int startHeight;\n public volatile int chainScanInterval;\n public volatile int heightBuffer;\n public volatile boolean isPaused;\n\n /* Database Config */\n public String okraDBUri;\n public String okraDBUser;\n public String okraDBPass;\n public String chiaDBUri;\n public String chiaDBUser;\n public String chiaDBPass;\n\n /* Internal Services */\n public String authServiceUri;\n public int authServicePort;\n public String authServiceUser;\n public String authServicePass;\n\n /* Card Rarity */\n public int holoPct = 3;\n public int goldPct = 20;\n public int highLvl = 40;\n public String currCollection;\n\n /* Config Paths */\n public String mainNodeConfig;\n public String mintWalletConfig;\n public String transactionWalletConfig;\n public String mintJobConfig;\n public String okraJobConfig;\n public String outrJobConfig;\n\n /* S3 */\n public String s3AccessKey;\n public String s3SecretKey;\n\n\n /* Assets */\n public String boosterAddress;\n public String boosterTail;\n public String starterAddress;\n public String starterTail;\n\n\n /* DID Mint */\n public String didMintToAddr;\n public List<String> didUris;\n public List<String> didMetaUris;\n public List<String> didLicenseUris;\n public String didHash;\n public String didMetaHash;\n public String didLicenseHash;\n\n /* Dispersal Limits */\n public int nftFlagAmount;\n public int okraFlagAmount;\n public int outrFlagAmount;\n\n\n\n static {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n\n File file = new File(\"config.yaml\");\n\n try {\n INSTANCE = mapper.readValue(file, Settings.class);\n } catch (IOException e) {\n try {\n writeBlank();\n } catch (IOException ex) { throw new RuntimeException(ex); }\n throw new RuntimeException(\"Failed to read config file.\", e);\n }\n }\n\n public static Settings get() {\n return INSTANCE;\n }\n\n public static MetaData getAccountMintMetaData() {\n return null;\n }\n\n public static void writeBlank() throws IOException {\n var mapper = new ObjectMapper(new YAMLFactory());\n mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);\n File yamlFile = new File(\"defaults.yaml\");\n mapper.writeValue(yamlFile, new Settings());\n }\n\n\n}"
},
{
"identifier": "AvatarService",
"path": "src/main/java/io/mindspice/itemserver/services/AvatarService.java",
"snippet": "public class AvatarService {\n private final WalletAPI walletAPI;\n private final OkraGameAPI gameApi;\n private final CustomLogger logger;\n private final S3Service s3Service;\n UnsafeHttpClient client = new UnsafeHttpClient(10_000, 10_000, 10_000);\n String uuid = UUID.randomUUID().toString();\n\n public AvatarService(WalletAPI monWalletApi, OkraGameAPI gameApi, S3Service s3Service, CustomLogger logger) {\n this.walletAPI = monWalletApi;\n this.gameApi = gameApi;\n this.s3Service = s3Service;\n this.logger = logger;\n }\n\n public void submit(Pair<Integer, String> updateInfo) {\n logger.logApp(this.getClass(), TLogLevel.DEBUG, \"Received avatar update playerId: \" + updateInfo.first()\n + \" | NFT: \" + updateInfo.second());\n Thread.ofVirtual().start(updateTask(updateInfo.first(), updateInfo.second()));\n }\n\n public Runnable updateTask(int playerId, String nftLauncher) {\n\n return new Runnable() {\n @Override\n public void run() {\n try {\n\n long lastUpdate = gameApi.getLastAvatarUpdate(playerId).data().orElseThrow();\n if (Instant.now().getEpochSecond() - lastUpdate < 86400) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Ignored avatar update: Too soon\");\n return;\n }\n\n NftInfo nftInfo = Utils.nftGetInfoWrapper(walletAPI, nftLauncher);\n List<String> uris = nftInfo.dataUris();\n byte[] imgBytes = getConvertedImage(uris);\n if (imgBytes == null || imgBytes.length > 1024 * 66) {\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Ignored avatar update: Too large of file\");\n return;\n }\n s3Service.uploadBytes(playerId + \".png\", imgBytes);\n gameApi.updatePlayerAvatar(playerId, playerId + \".png\");\n\n logger.logApp(this.getClass(), TLogLevel.INFO, \"Player Id: \" + playerId +\n \" | Updated player avatar with: \" + nftLauncher);\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \" | PlayerId: \" + playerId +\n \" | Failed updating avatar with: \" + nftLauncher +\n \" | Message: \" + e.getMessage(), e);\n }\n }\n };\n }\n\n public byte[] getConvertedImage(List<String> uris) throws IOException {\n\n byte[] imgBytes = null;\n for (var uri : uris) {\n try {\n imgBytes = client.requestBuilder()\n .address(uri)\n .asGet()\n .maxResponseSize(10 * 1024 * 1024)\n .makeAndGetBytes();\n if (imgBytes != null) { break; }\n } catch (Exception ignored) {\n }\n }\n\n if (imgBytes == null) { return null; }\n ByteArrayInputStream imageByteStream = new ByteArrayInputStream(imgBytes);\n if (!checkSafeImage(new ByteArrayInputStream(imgBytes))) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Abuse attempted in ConversionJob: \"\n + uuid + \" with: \" + uris);\n throw new IllegalStateException(\"Validation Fail\");\n }\n\n BufferedImage ogImage = ImageIO.read(imageByteStream);\n\n BufferedImage resizedImage = new BufferedImage(128, 128, BufferedImage.TYPE_INT_RGB);\n Graphics2D g = resizedImage.createGraphics();\n g.drawImage(ogImage, 0, 0, 128, 128, null);\n g.dispose();\n\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n ImageIO.write(resizedImage, \"png\", outputStream);\n return outputStream.toByteArray();\n }\n\n private boolean checkSafeImage(InputStream input) throws IOException {\n ImageInputStream imageInputStream = ImageIO.createImageInputStream(input);\n Iterator<ImageReader> iter = ImageIO.getImageReaders(imageInputStream);\n long maxSize = 2048L * 2048L;\n\n if (!iter.hasNext()) {\n imageInputStream.close();\n return false;\n }\n\n boolean safe = false;\n try {\n ImageReader reader = iter.next();\n reader.setInput(imageInputStream, true, true);\n\n long width = reader.getWidth(0);\n long height = reader.getHeight(0);\n\n safe = (height * width) <= maxSize;\n } finally {\n imageInputStream.close();\n }\n return safe;\n }\n\n}"
},
{
"identifier": "LeaderBoardService",
"path": "src/main/java/io/mindspice/itemserver/services/LeaderBoardService.java",
"snippet": "public class LeaderBoardService {\n private final OkraGameAPI gameAPI;\n public final CustomLogger logger;\n\n private volatile List<PlayerScore> dailyScores;\n private volatile List<PlayerScore> weeklyScores;\n private volatile List<PlayerScore> monthlyScores;\n\n public LeaderBoardService(OkraGameAPI gameAPI, CustomLogger logger) {\n this.gameAPI = gameAPI;\n this.logger = logger;\n }\n\n public Runnable updateScores() {\n return () -> {\n java.time.LocalDate day = java.time.LocalDate.now();\n List<MatchResult> dailyResults = gameAPI.getMatchResults(\n day.atStartOfDay(ZoneId.systemDefault()).minusDays(1).toInstant().toEpochMilli(), //this is right, but workish\n day.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n dailyScores = calcAndSortResults(dailyResults);\n\n java.time.LocalDate week = java.time.LocalDate.now().with(DayOfWeek.MONDAY);\n List<MatchResult> weeklyResults = gameAPI.getMatchResults(\n week.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),\n week.plusWeeks(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n weeklyScores = calcAndSortResults(weeklyResults);\n\n java.time.LocalDate month = LocalDate.now().withDayOfMonth(1);\n List<MatchResult> monthlyResult = gameAPI.getMatchResults(\n month.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli(),\n month.plusMonths(1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() - 1\n ).data().orElseThrow();\n monthlyScores = calcAndSortResults(monthlyResult);\n };\n }\n\n private List<PlayerScore> calcAndSortResults(List<MatchResult> results) {\n HashMap<String, PlayerScore> interimMap = new HashMap<>();\n results.forEach(result -> {\n interimMap.computeIfAbsent(result.player1Name(),\n k -> new PlayerScore(result.player1Name())).addResult(result.player1Won()\n );\n interimMap.computeIfAbsent(result.player2Name(),\n k -> new PlayerScore(result.player2Name())).addResult(result.player2Won()\n );\n }\n );\n interimMap.remove(\"BramBot\");\n return interimMap.values().stream()\n .sorted(Comparator.comparing(PlayerScore::getSortMetric).reversed())\n .limit(35)\n .toList();\n }\n\n public List<PlayerScore> getDailyScores() { return dailyScores; }\n\n public List<PlayerScore> getWeeklyScores() { return weeklyScores; }\n\n public List<PlayerScore> getMonthlyScores() { return monthlyScores; }\n}"
}
] | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.mindspice.databaseservice.client.api.OkraNFTAPI;
import io.mindspice.databaseservice.client.schema.Card;
import io.mindspice.itemserver.schema.ApiMint;
import io.mindspice.itemserver.Settings;
import io.mindspice.itemserver.schema.ApiMintReq;
import io.mindspice.itemserver.services.AvatarService;
import io.mindspice.itemserver.services.LeaderBoardService;
import io.mindspice.jxch.rpc.schemas.wallet.nft.MetaData;
import io.mindspice.jxch.transact.logging.TLogLevel;
import io.mindspice.jxch.transact.logging.TLogger;
import io.mindspice.jxch.transact.service.mint.MintItem;
import io.mindspice.jxch.transact.service.mint.MintService;
import io.mindspice.mindlib.data.tuples.Pair;
import io.mindspice.mindlib.util.JsonUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.*;
import java.util.stream.IntStream; | 3,471 | package io.mindspice.itemserver.api;
@CrossOrigin
@RestController
@RequestMapping("/internal")
public class Internal {
private final MintService mintService;
private final AvatarService avatarService;
private final LeaderBoardService leaderBoardService;
private final OkraNFTAPI nftAPI;
private final MetaData accountNFTMeta;
private final TLogger logger;
public Internal(
@Qualifier("mintService") MintService mintService,
@Qualifier("avatarService") AvatarService avatarService,
@Qualifier("leaderBoardService") LeaderBoardService leaderBoardService,
@Qualifier("okraNFTAPI") OkraNFTAPI nftAPI,
@Qualifier("customLogger") TLogger customLogger,
@Qualifier("accountNFTMeta") MetaData accountNFTMeta
) {
this.mintService = mintService;
this.avatarService = avatarService;
this.leaderBoardService = leaderBoardService;
this.nftAPI = nftAPI;
this.accountNFTMeta = accountNFTMeta;
this.logger = customLogger;
}
@PostMapping("/mint_card_nfts")
public ResponseEntity<String> mintCardNfts(@RequestBody String jsonReq) throws IOException {
try {
ApiMintReq mintReq = JsonUtils.readValue(jsonReq, ApiMintReq.class);
List<Card> cards = nftAPI.getCardCollection(mintReq.collection()).data().orElseThrow();
var mints = mintReq.mint_list().stream().map(m ->
new MintItem(
m.address(),
m.card_uid().equals("DID")
? accountNFTMeta
: cards.stream().filter(c -> c.uid().equals(m.card_uid()))
.findFirst().orElseThrow().metaData()
.cloneSetEdt(nftAPI.getAndIncEdt(mintReq.collection(), m.card_uid()).data().get()),
m.job_uuid())
).toList();
mintService.submit(mints);
} catch (Exception e) {
logger.log(this.getClass(), TLogLevel.ERROR, "Failed to accept api mint", e);
return new ResponseEntity<>(JsonUtils.writeString(JsonUtils.errorMsg(e.getMessage() + " | "
+ Arrays.toString(e.getStackTrace()))), HttpStatus.OK);
}
return new ResponseEntity<>(
JsonUtils.writeString(JsonUtils.successMsg(JsonUtils.newEmptyNode())), HttpStatus.OK
);
}
@PostMapping("update_avatar")
public ResponseEntity<String> updateAvatar(@RequestBody String jsonRequest) throws IOException {
JsonNode node = JsonUtils.readTree(jsonRequest);
String nftId = node.get("nft_id").asText();
int playerId = node.get("player_id").asInt();
if (nftId == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
avatarService.submit(new Pair<>(playerId, nftId));
return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping("/mint_did_nfts")
public ResponseEntity<String> mintDidNfts(@RequestBody String jsonReq) throws JsonProcessingException {
try {
JsonNode node = JsonUtils.readTree(jsonReq);
int amount = node.get("amount").asInt();
String uuid = "account:" + UUID.randomUUID();
List<MintItem> mints = IntStream.range(0, amount) | package io.mindspice.itemserver.api;
@CrossOrigin
@RestController
@RequestMapping("/internal")
public class Internal {
private final MintService mintService;
private final AvatarService avatarService;
private final LeaderBoardService leaderBoardService;
private final OkraNFTAPI nftAPI;
private final MetaData accountNFTMeta;
private final TLogger logger;
public Internal(
@Qualifier("mintService") MintService mintService,
@Qualifier("avatarService") AvatarService avatarService,
@Qualifier("leaderBoardService") LeaderBoardService leaderBoardService,
@Qualifier("okraNFTAPI") OkraNFTAPI nftAPI,
@Qualifier("customLogger") TLogger customLogger,
@Qualifier("accountNFTMeta") MetaData accountNFTMeta
) {
this.mintService = mintService;
this.avatarService = avatarService;
this.leaderBoardService = leaderBoardService;
this.nftAPI = nftAPI;
this.accountNFTMeta = accountNFTMeta;
this.logger = customLogger;
}
@PostMapping("/mint_card_nfts")
public ResponseEntity<String> mintCardNfts(@RequestBody String jsonReq) throws IOException {
try {
ApiMintReq mintReq = JsonUtils.readValue(jsonReq, ApiMintReq.class);
List<Card> cards = nftAPI.getCardCollection(mintReq.collection()).data().orElseThrow();
var mints = mintReq.mint_list().stream().map(m ->
new MintItem(
m.address(),
m.card_uid().equals("DID")
? accountNFTMeta
: cards.stream().filter(c -> c.uid().equals(m.card_uid()))
.findFirst().orElseThrow().metaData()
.cloneSetEdt(nftAPI.getAndIncEdt(mintReq.collection(), m.card_uid()).data().get()),
m.job_uuid())
).toList();
mintService.submit(mints);
} catch (Exception e) {
logger.log(this.getClass(), TLogLevel.ERROR, "Failed to accept api mint", e);
return new ResponseEntity<>(JsonUtils.writeString(JsonUtils.errorMsg(e.getMessage() + " | "
+ Arrays.toString(e.getStackTrace()))), HttpStatus.OK);
}
return new ResponseEntity<>(
JsonUtils.writeString(JsonUtils.successMsg(JsonUtils.newEmptyNode())), HttpStatus.OK
);
}
@PostMapping("update_avatar")
public ResponseEntity<String> updateAvatar(@RequestBody String jsonRequest) throws IOException {
JsonNode node = JsonUtils.readTree(jsonRequest);
String nftId = node.get("nft_id").asText();
int playerId = node.get("player_id").asInt();
if (nftId == null) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
avatarService.submit(new Pair<>(playerId, nftId));
return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping("/mint_did_nfts")
public ResponseEntity<String> mintDidNfts(@RequestBody String jsonReq) throws JsonProcessingException {
try {
JsonNode node = JsonUtils.readTree(jsonReq);
int amount = node.get("amount").asInt();
String uuid = "account:" + UUID.randomUUID();
List<MintItem> mints = IntStream.range(0, amount) | .mapToObj(i -> new MintItem(Settings.get().didMintToAddr, accountNFTMeta, uuid)) | 0 | 2023-11-14 14:56:37+00:00 | 4k |
KvRae/Mobile-Exemple-Java-Android | Project/app/src/main/java/com/example/pharmacie2/Views/Activities/MedecinActivity.java | [
{
"identifier": "PharmacyDB",
"path": "Project/app/src/main/java/com/example/pharmacie2/Data/Database/PharmacyDB.java",
"snippet": "@Database(entities = {User.class, Medicament.class, Medecin.class}, version = 1, exportSchema = false)\n\npublic abstract class PharmacyDB extends RoomDatabase {\n\n private static PharmacyDB instance;\n\n public abstract UserDao userDao();\n\n public abstract MedicamentDao medicamentDao();\n public abstract MedecinDao medecinDao();\n\n public static synchronized PharmacyDB getInstance(Context context) {\n if (instance == null) {\n instance = Room.databaseBuilder(\n context.getApplicationContext(),\n PharmacyDB.class,\n \"user_database,medicament_database,medecin_database\"\n\n )\n .fallbackToDestructiveMigration()\n .build();\n }\n return instance;\n }\n}"
},
{
"identifier": "Medecin",
"path": "Project/app/src/main/java/com/example/pharmacie2/Data/Entities/Medecin.java",
"snippet": "@Entity(tableName = \"medecins\")\npublic class Medecin {\n @PrimaryKey(autoGenerate = true)\n private int id;\n\n private String nom;\n private String prenom;\n private String specialite;\n private String email;\n private int numero;\n\n private String localisation;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getNom() {\n return nom;\n }\n\n public void setNom(String nom) {\n this.nom = nom;\n }\n\n public String getPrenom() {\n return prenom;\n }\n\n public void setPrenom(String prenom) {\n this.prenom = prenom;\n }\n\n public String getSpecialite() {\n return specialite;\n }\n\n public void setSpecialite(String specialite) {\n this.specialite = specialite;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public int getNumero() {\n return numero;\n }\n\n public void setNumero(int numero) {\n this.numero = numero;\n }\n\n public String getLocalisation() {\n return localisation;\n }\n\n public void setLocalisation(String localisation) {\n this.localisation = localisation;\n }\n\n public Medecin() {\n }\n\n public Medecin(int id) {\n this.id = id;\n }\n\n public Medecin(String nom, String prenom, String specialite, String email, int numero, String localisation) {\n this.nom = nom;\n this.prenom = prenom;\n this.specialite = specialite;\n this.email = email;\n this.numero = numero;\n this.localisation = localisation;\n }\n}"
},
{
"identifier": "MedecinAdapter",
"path": "Project/app/src/main/java/com/example/pharmacie2/Utils/MedecinAdapter.java",
"snippet": "public class MedecinAdapter extends RecyclerView.Adapter<MedecinAdapter.MedecinHolderView>{\n private List<Medecin> medecinList;\n private MedecinAdapter.OnDeleteClickListener onDeleteClickListener;\n public interface OnDeleteClickListener {\n void onDeleteClick(Medecin medecin);\n }\n public MedecinAdapter(List<Medecin> medecinList, MedecinAdapter.OnDeleteClickListener onDeleteClickListener) {\n this.medecinList = medecinList;\n this.onDeleteClickListener = onDeleteClickListener;\n\n\n }\n\n @NonNull\n @Override\n public MedecinAdapter.MedecinHolderView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.medecin_item, parent, false);\n return new MedecinAdapter.MedecinHolderView(view);\n }\n\n @Override\n public void onBindViewHolder(@NonNull MedecinHolderView holder, int position) {\n Medecin medecin = medecinList.get(position);\n holder.textViewNomMedecin.setText(Html.fromHtml(\"<b>\" + medecin.getNom() + \"</b>\"));\n\n holder.buttonDelete.setTag(medecin);\n holder.buttonDelete.setOnClickListener(view -> {\n // Retrieve the user from the tag\n Medecin medecinToDelete = (Medecin) view.getTag();\n onDeleteClickListener.onDeleteClick(medecinToDelete);\n });\n\n }\n\n\n\n @Override\n public int getItemCount() {\n return medecinList.size();\n }\n\n public class MedecinHolderView extends RecyclerView.ViewHolder {\n TextView textViewNomMedecin;\n TextView textViewNumeroMedecin;\n ImageButton buttonDelete;\n\n public MedecinHolderView(@NonNull View itemView) {\n super(itemView);\n textViewNomMedecin = itemView.findViewById(R.id.textViewNom);\n textViewNumeroMedecin = itemView.findViewById(R.id.textViewNum);\n buttonDelete = itemView.findViewById(R.id.buttonDelete);\n }\n }\n\n // Add a method to update the list in the adapter\n public void updateList(List<Medecin> newList) {\n medecinList = newList;\n notifyDataSetChanged();\n }\n}"
}
] | import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.pharmacie2.Data.Database.PharmacyDB;
import com.example.pharmacie2.Data.Entities.Medecin;
import com.example.pharmacie2.R;
import com.example.pharmacie2.Utils.MedecinAdapter;
import java.util.List; | 1,642 | package com.example.pharmacie2.Views.Activities;
public class MedecinActivity extends AppCompatActivity implements MedecinAdapter.OnDeleteClickListener{
ImageView backBtn ;
ImageView AddM ;
PharmacyDB db;
private RecyclerView recyclerViewMed;
private MedecinAdapter medecinAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medecin);
db = PharmacyDB.getInstance(this);
recyclerViewMed = findViewById(R.id.recyclerView3);
recyclerViewMed.setLayoutManager(new LinearLayoutManager(this));
backBtn = findViewById(R.id.imageViewCalendrier);
AddM = findViewById(R.id.AddMedi);
new LoadMedTask(recyclerViewMed).execute();
backBtn.setOnClickListener(
e ->{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "main",Toast.LENGTH_SHORT).show();
finish();
}
);
AddM.setOnClickListener(
e ->{
Intent intent = new Intent(this, AjouterMedecinActivity.class);
startActivity(intent);
Toast.makeText(this, "main",Toast.LENGTH_SHORT).show();
finish();
}
);
}
@Override | package com.example.pharmacie2.Views.Activities;
public class MedecinActivity extends AppCompatActivity implements MedecinAdapter.OnDeleteClickListener{
ImageView backBtn ;
ImageView AddM ;
PharmacyDB db;
private RecyclerView recyclerViewMed;
private MedecinAdapter medecinAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medecin);
db = PharmacyDB.getInstance(this);
recyclerViewMed = findViewById(R.id.recyclerView3);
recyclerViewMed.setLayoutManager(new LinearLayoutManager(this));
backBtn = findViewById(R.id.imageViewCalendrier);
AddM = findViewById(R.id.AddMedi);
new LoadMedTask(recyclerViewMed).execute();
backBtn.setOnClickListener(
e ->{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "main",Toast.LENGTH_SHORT).show();
finish();
}
);
AddM.setOnClickListener(
e ->{
Intent intent = new Intent(this, AjouterMedecinActivity.class);
startActivity(intent);
Toast.makeText(this, "main",Toast.LENGTH_SHORT).show();
finish();
}
);
}
@Override | public void onDeleteClick(Medecin medecin) { | 1 | 2023-11-14 22:07:33+00:00 | 4k |
CodecNomad/CodecClient | src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java | [
{
"identifier": "Client",
"path": "src/main/java/com/github/codecnomad/codecclient/Client.java",
"snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft();\n public static Rotation rotation = new Rotation();\n public static Config guiConfig;\n\n static {\n modules.put(\"FishingMacro\", new FishingMacro());\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n guiConfig = new Config();\n\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(rotation);\n\n MinecraftForge.EVENT_BUS.register(MainCommand.pathfinding);\n\n CommandManager.register(new MainCommand());\n }\n\n @SubscribeEvent\n public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {\n for (Map.Entry<String, Module> moduleMap : modules.entrySet()) {\n moduleMap.getValue().unregister();\n }\n }\n}"
},
{
"identifier": "PacketEvent",
"path": "src/main/java/com/github/codecnomad/codecclient/events/PacketEvent.java",
"snippet": "public class PacketEvent extends Event {\n public enum Phase {\n pre,\n post\n }\n\n public final Packet<?> packet;\n public final Phase phase;\n\n\n public PacketEvent(final Packet<?> packet, Phase phase) {\n this.packet = packet;\n this.phase = phase;\n }\n\n public static class ReceiveEvent extends PacketEvent {\n public ReceiveEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n\n public static class SendEvent extends PacketEvent {\n public SendEvent(final Packet<?> packet, Phase phase) {\n super(packet, phase);\n }\n }\n}"
},
{
"identifier": "S19PacketAccessor",
"path": "src/main/java/com/github/codecnomad/codecclient/mixins/S19PacketAccessor.java",
"snippet": "@Mixin(S19PacketEntityHeadLook.class)\npublic interface S19PacketAccessor {\n @Accessor(\"entityId\")\n int getEntityId();\n}"
},
{
"identifier": "Config",
"path": "src/main/java/com/github/codecnomad/codecclient/ui/Config.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class Config extends cc.polyfrost.oneconfig.config.Config {\n @Color(\n name = \"Color\",\n category = \"Visuals\"\n )\n public static OneColor VisualColor = new OneColor(100, 60, 160, 200);\n @KeyBind(\n name = \"Fishing key-bind\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);\n @Number(\n name = \"Catch delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 20\n )\n public static int FishingDelay = 10;\n @Number(\n name = \"Kill delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 40\n )\n public static int KillDelay = 20;\n @Number(\n name = \"Attack c/s\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 20\n )\n public static int AttackCps = 10;\n\n @Number(\n name = \"Smoothing\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 2,\n max = 10\n )\n public static int RotationSmoothing = 4;\n\n @Number(\n name = \"Random movement frequency\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 50\n )\n public static int MovementFrequency = 15;\n\n @Switch(\n name = \"Auto kill\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean AutoKill = true;\n\n @Switch(\n name = \"Only sound failsafe\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean OnlySound = false;\n\n @Number(\n name = \"Weapon slot\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 9\n )\n public static int WeaponSlot = 9;\n\n @Switch(\n name = \"Right click attack\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean RightClick = false;\n\n @HUD(\n name = \"Fishing HUD\",\n category = \"Visuals\"\n )\n public FishingHud hudFishing = new FishingHud();\n\n public Config() {\n super(new Mod(\"CodecClient\", ModType.UTIL_QOL), \"config.json\");\n initialize();\n\n registerKeyBind(FishingKeybinding, () -> toggle(\"FishingMacro\"));\n save();\n }\n\n private static void toggle(String name) {\n Module helperClassModule = Client.modules.get(name);\n if (helperClassModule.state) {\n helperClassModule.unregister();\n } else {\n helperClassModule.register();\n }\n }\n}"
},
{
"identifier": "Math",
"path": "src/main/java/com/github/codecnomad/codecclient/utils/Math.java",
"snippet": "public class Math {\n\n public static float easeInOut(float t) {\n return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;\n }\n\n public static float interpolate(float goal, float current, float time) {\n while (goal - current > 180) {\n current += 360;\n }\n while (goal - current < -180) {\n current -= 360;\n }\n\n float t = easeInOut(time);\n return current + (goal - current) * t;\n }\n\n public static String toClock(int seconds) {\n int hours = seconds / 3600;\n int minutes = (seconds % 3600) / 60;\n int remainingSeconds = seconds % 60;\n\n return String.format(\"%dh, %dm, %ds\", hours, minutes, remainingSeconds);\n }\n\n public static String toFancyNumber(int number) {\n int k = number / 1000;\n int m = number / 1000000;\n int remaining = number % 1000000;\n\n if (m > 0) {\n return String.format(\"%dM\", m);\n } else if (k > 0) {\n return String.format(\"%dk\", k);\n } else {\n return String.format(\"%d\", remaining);\n }\n }\n\n public static float getYaw(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double yawToBlock = java.lang.Math.atan2(-deltaX, deltaZ);\n double yaw = java.lang.Math.toDegrees(yawToBlock);\n\n yaw = (yaw + 360) % 360;\n if (yaw > 180) {\n yaw -= 360;\n }\n\n return (float) yaw;\n }\n\n public static Vec3 fromBlockPos(BlockPos pos) {\n return new Vec3(pos.getX(), pos.getY(), pos.getZ());\n }\n\n public static float getPitch(BlockPos blockPos) {\n double deltaX = blockPos.getX() + 0.5 - Client.mc.thePlayer.posX;\n double deltaY = blockPos.getY() + 0.5 - Client.mc.thePlayer.posY - Client.mc.thePlayer.getEyeHeight();\n double deltaZ = blockPos.getZ() + 0.5 - Client.mc.thePlayer.posZ;\n double distanceXZ = java.lang.Math.sqrt(deltaX * deltaX + deltaZ * deltaZ);\n double pitchToBlock = -java.lang.Math.atan2(deltaY, distanceXZ);\n double pitch = java.lang.Math.toDegrees(pitchToBlock);\n pitch = java.lang.Math.max(-90, java.lang.Math.min(90, pitch));\n return (float) pitch;\n }\n\n public static double getXZDistance(BlockPos pos1, BlockPos pos2) {\n double xDiff = pos1.getX() - pos2.getX();\n double zDiff = pos1.getZ() - pos2.getZ();\n return java.lang.Math.sqrt(xDiff * xDiff + zDiff * zDiff);\n }\n\n}"
}
] | import com.github.codecnomad.codecclient.Client;
import com.github.codecnomad.codecclient.events.PacketEvent;
import com.github.codecnomad.codecclient.mixins.S19PacketAccessor;
import com.github.codecnomad.codecclient.ui.Config;
import com.github.codecnomad.codecclient.utils.Math;
import com.github.codecnomad.codecclient.utils.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityArmorStand;
import net.minecraft.entity.passive.EntitySquid;
import net.minecraft.entity.projectile.EntityFishHook;
import net.minecraft.item.*;
import net.minecraft.network.play.server.*;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.util.List;
import java.util.regex.Matcher; | 2,569 | package com.github.codecnomad.codecclient.modules;
@SuppressWarnings("DuplicatedCode")
public class FishingMacro extends Module {
public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",};
public static int startTime = 0;
public static int catches = 0;
public static float xpGain = 0;
public static FishingSteps currentStep = FishingSteps.FIND_ROD;
public static Counter MainCounter = new Counter();
public static Counter AlternativeCounter = new Counter();
public static Counter FailsafeCounter = new Counter();
public static boolean failSafe = false;
Entity fishingHook = null;
Entity fishingMarker = null;
Entity fishingMonster = null;
public static float lastYaw = 0;
public static float lastPitch = 0;
public static AxisAlignedBB lastAABB = null;
public BlockPos startPos = null;
public static Pathfinding pathfinding = new Pathfinding();
@Override
public void register() {
MinecraftForge.EVENT_BUS.register(this);
this.state = true; | package com.github.codecnomad.codecclient.modules;
@SuppressWarnings("DuplicatedCode")
public class FishingMacro extends Module {
public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",};
public static int startTime = 0;
public static int catches = 0;
public static float xpGain = 0;
public static FishingSteps currentStep = FishingSteps.FIND_ROD;
public static Counter MainCounter = new Counter();
public static Counter AlternativeCounter = new Counter();
public static Counter FailsafeCounter = new Counter();
public static boolean failSafe = false;
Entity fishingHook = null;
Entity fishingMarker = null;
Entity fishingMonster = null;
public static float lastYaw = 0;
public static float lastPitch = 0;
public static AxisAlignedBB lastAABB = null;
public BlockPos startPos = null;
public static Pathfinding pathfinding = new Pathfinding();
@Override
public void register() {
MinecraftForge.EVENT_BUS.register(this);
this.state = true; | lastYaw = Client.mc.thePlayer.rotationYaw; | 0 | 2023-11-16 10:12:20+00:00 | 4k |
maarlakes/common | src/main/java/cn/maarlakes/common/factory/json/JsonFactories.java | [
{
"identifier": "SpiServiceLoader",
"path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java",
"snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader, ConcurrentMap<Class<?>, SpiServiceLoader<?>>> SERVICE_LOADER_CACHE = new ConcurrentHashMap<>();\n\n private final Class<T> service;\n\n private final ClassLoader loader;\n private final boolean isShared;\n\n private final Supplier<List<Holder>> holders = Lazy.of(this::loadServiceHolder);\n private final ConcurrentMap<Class<?>, T> serviceCache = new ConcurrentHashMap<>();\n\n private SpiServiceLoader(@Nonnull Class<T> service, ClassLoader loader, boolean isShared) {\n this.service = Objects.requireNonNull(service, \"Service interface cannot be null\");\n this.loader = (loader == null) ? ClassLoader.getSystemClassLoader() : loader;\n this.isShared = isShared;\n }\n\n public boolean isEmpty() {\n return this.holders.get().isEmpty();\n }\n\n @Nonnull\n public T first() {\n return this.firstOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public T first(@Nonnull Class<? extends T> serviceType) {\n return this.firstOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> firstOptional() {\n return this.firstOptional(this.service);\n }\n\n @Nonnull\n public Optional<T> firstOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream().filter(item -> serviceType.isAssignableFrom(item.serviceType)).map(this::loadService).findFirst();\n }\n\n @Nonnull\n public T last() {\n return this.lastOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional() {\n return this.lastOptional(this.service);\n }\n\n @Nonnull\n public T last(@Nonnull Class<? extends T> serviceType) {\n return this.lastOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream()\n .filter(item -> serviceType.isAssignableFrom(item.serviceType))\n .sorted((left, right) -> Holder.compare(right, left))\n .map(this::loadService)\n .findFirst();\n }\n\n @Nonnull\n @Override\n public Iterator<T> iterator() {\n return this.holders.get().stream().map(this::loadService).iterator();\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service) {\n return load(service, Thread.currentThread().getContextClassLoader());\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return new SpiServiceLoader<>(service, loader, false);\n }\n\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service) {\n return loadShared(service, Thread.currentThread().getContextClassLoader());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return (SpiServiceLoader<S>) SERVICE_LOADER_CACHE.computeIfAbsent(loader, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(service, k -> new SpiServiceLoader<>(service, loader, true));\n }\n\n private T loadService(@Nonnull Holder holder) {\n if (holder.spiService != null && holder.spiService.lifecycle() == SpiService.Lifecycle.SINGLETON) {\n return this.serviceCache.computeIfAbsent(holder.serviceType, k -> this.createService(holder));\n }\n return this.createService(holder);\n }\n\n private T createService(@Nonnull Holder holder) {\n try {\n return this.service.cast(holder.serviceType.getConstructor().newInstance());\n } catch (Exception e) {\n throw new SpiServiceException(e.getMessage(), e);\n }\n }\n\n\n private List<Holder> loadServiceHolder() {\n final Enumeration<URL>[] configArray = this.loadConfigs();\n try {\n final Map<String, Holder> map = new HashMap<>();\n for (Enumeration<URL> configs : configArray) {\n while (configs.hasMoreElements()) {\n final URL url = configs.nextElement();\n try (InputStream in = url.openStream()) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {\n String ln;\n int lineNumber = 0;\n while ((ln = reader.readLine()) != null) {\n lineNumber++;\n final int ci = ln.indexOf('#');\n if (ci >= 0) {\n ln = ln.substring(0, ci);\n }\n ln = ln.trim();\n if (!ln.isEmpty()) {\n this.check(url, ln, lineNumber);\n if (!map.containsKey(ln)) {\n final Class<?> type = Class.forName(ln, false, loader);\n if (!this.service.isAssignableFrom(type)) {\n throw new SpiServiceException(this.service.getName() + \": Provider\" + ln + \" not a subtype\");\n }\n map.put(ln, new Holder(type, type.getAnnotation(SpiService.class)));\n }\n }\n }\n }\n }\n }\n }\n if (map.isEmpty() && this.isShared) {\n // 移除\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n\n return map.values().stream().sorted().collect(Collectors.toList());\n } catch (IOException | ClassNotFoundException e) {\n if (this.isShared) {\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n throw new SpiServiceException(e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private Enumeration<URL>[] loadConfigs() {\n final String fullName = PREFIX + service.getName();\n try {\n return new Enumeration[]{this.loader.getResources(fullName), ClassLoader.getSystemResources(fullName)};\n } catch (IOException e) {\n throw new SpiServiceException(service.getName() + \": Error locating configuration files\", e);\n }\n }\n\n private void check(@Nonnull URL url, @Nonnull String className, int lineNumber) {\n if ((className.indexOf(' ') >= 0) || (className.indexOf('\\t') >= 0)) {\n throw new SpiServiceException(this.service.getName() + \": \" + className + \":\" + lineNumber + \":Illegal configuration-file syntax\");\n }\n int cp = className.codePointAt(0);\n if (!Character.isJavaIdentifierStart(cp)) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n final int length = className.length();\n for (int i = Character.charCount(cp); i < length; i += Character.charCount(cp)) {\n cp = className.codePointAt(i);\n if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n }\n }\n\n private static final class Holder implements Comparable<Holder> {\n\n private final Class<?> serviceType;\n\n private final SpiService spiService;\n\n private Holder(@Nonnull Class<?> serviceType, SpiService spiService) {\n this.serviceType = serviceType;\n this.spiService = spiService;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof Holder) {\n return this.serviceType == ((Holder) obj).serviceType;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(serviceType);\n }\n\n @Override\n public int compareTo(@Nullable Holder o) {\n if (o == null) {\n return 1;\n }\n return Integer.compare(this.spiService == null ? Integer.MAX_VALUE : this.spiService.order(), o.spiService == null ? Integer.MAX_VALUE : o.spiService.order());\n }\n\n public static int compare(Holder left, Holder right) {\n if (left == right) {\n return 0;\n }\n if (left == null) {\n return -1;\n }\n return left.compareTo(right);\n }\n }\n}"
},
{
"identifier": "Lazy",
"path": "src/main/java/cn/maarlakes/common/utils/Lazy.java",
"snippet": "public final class Lazy {\n private Lazy() {\n }\n\n @Nonnull\n public static <T> Supplier<T> of(@Nonnull Supplier<T> action) {\n return new Supplier<T>() {\n\n private volatile T value = null;\n private final Object sync = new Object();\n\n @Override\n public T get() {\n if (this.value == null) {\n synchronized (this.sync) {\n if (this.value == null) {\n this.value = action.get();\n }\n }\n }\n return this.value;\n }\n };\n }\n}"
}
] | import cn.maarlakes.common.spi.SpiServiceLoader;
import cn.maarlakes.common.utils.Lazy;
import jakarta.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier; | 2,335 | package cn.maarlakes.common.factory.json;
/**
* @author linjpxc
*/
public final class JsonFactories {
private JsonFactories() {
}
| package cn.maarlakes.common.factory.json;
/**
* @author linjpxc
*/
public final class JsonFactories {
private JsonFactories() {
}
| private static final Supplier<JsonProvider> PROVIDER = Lazy.of(() -> SpiServiceLoader.loadShared(JsonProvider.class).firstOptional().orElseThrow(() -> new IllegalStateException("No JsonProvider implementation found"))); | 0 | 2023-11-18 07:49:00+00:00 | 4k |
Mightinity/store-management-system | src/main/java/com/systeminventory/controller/cashierController.java | [
{
"identifier": "App",
"path": "src/main/java/com/systeminventory/App.java",
"snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException{\n primaryStage = stage;\n loadLoginScene();\n\n }\n\n public static Stage getPrimaryStage(){\n return primaryStage;\n }\n\n public static void loadLoginScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setResizable(false);\n primaryStage.initStyle(StageStyle.UNDECORATED);\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadLogoutScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"dashboardLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadProductScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"productLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Product - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"cashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Cashier - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n\n }\n public static void loadEmployeeDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeProductLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadEmployeeCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeCashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n}"
},
{
"identifier": "Cashier",
"path": "src/main/java/com/systeminventory/model/Cashier.java",
"snippet": "public class Cashier {\n\n private String cashierName;\n private String cashierNoPhone;\n private String cashierImageSource;\n private String cashierEmail;\n private String cashierPassword;\n private String cashierDateOfBirth;\n private String cashierAddress;\n\n private String keyCashier;\n\n public String getCashierName() {\n return cashierName;\n }\n\n public void setCashierName(String cashierName) {\n this.cashierName = cashierName;\n }\n\n public String getCashierNoPhone() {\n return cashierNoPhone;\n }\n\n public void setCashierNoPhone(String cashierNoPhone) {\n this.cashierNoPhone = cashierNoPhone;\n }\n\n public String getCashierImageSource() {\n return cashierImageSource;\n }\n\n public void setCashierImageSource(String cashierImageSource) {\n this.cashierImageSource = cashierImageSource;\n }\n\n public String getCashierEmail() {\n return cashierEmail;\n }\n\n public void setCashierEmail(String cashierEmail) {\n this.cashierEmail = cashierEmail;\n }\n\n public String getCashierPassword() {\n return cashierPassword;\n }\n\n public void setCashierPassword(String cashierPassword) {\n this.cashierPassword = cashierPassword;\n }\n\n public String getCashierDateOfBirth() {\n return cashierDateOfBirth;\n }\n\n public void setCashierDateOfBirth(String cashierDateOfBirth) {\n this.cashierDateOfBirth = cashierDateOfBirth;\n }\n\n public String getCashierAddress() {\n return cashierAddress;\n }\n\n public void setCashierAddress(String cashierAddress) {\n this.cashierAddress = cashierAddress;\n }\n\n public String getKeyCashier() {\n return keyCashier;\n }\n\n public void setKeyCashier(String keyCashier) {\n this.keyCashier = keyCashier;\n }\n}"
},
{
"identifier": "Product",
"path": "src/main/java/com/systeminventory/model/Product.java",
"snippet": "public class Product {\n private String productName;\n private String imageSource;\n private String productOriginalPrice;\n private String productSellingPrice;\n private String productStock;\n private String keyProduct;\n private String idProduct;\n\n\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getImageSource() {\n return imageSource;\n }\n\n public void setImageSource(String imageSource) {\n this.imageSource = imageSource;\n }\n\n public String getProductSellingPrice() {\n return productSellingPrice;\n }\n\n public void setProductSellingPrice(String productSellingPrice) {\n this.productSellingPrice = productSellingPrice;\n }\n\n public String getProductStock() {\n return productStock;\n }\n\n public void setProductStock(String productStock) {\n this.productStock = productStock;\n }\n\n public String getKeyProduct() {\n return keyProduct;\n }\n\n public void setKeyProduct(String keyProduct) {\n this.keyProduct = keyProduct;\n }\n\n public String getProductOriginalPrice() {\n return productOriginalPrice;\n }\n\n public void setProductOriginalPrice(String productOriginalPrice) {\n this.productOriginalPrice = productOriginalPrice;\n }\n\n public String getIdProduct() {\n return idProduct;\n }\n\n public void setIdProduct(String idProduct) {\n this.idProduct = idProduct;\n }\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.systeminventory.App;
import com.systeminventory.interfaces.*;
import com.systeminventory.model.Cashier;
import com.systeminventory.model.Product;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List; | 2,421 | package com.systeminventory.controller;
public class cashierController {
@FXML
private Pane backgroundPopup;
@FXML
private Button buttonCashier;
@FXML
private Button buttonDashboard;
@FXML
private Button buttonProduct;
@FXML
private Button logoutDropdown;
@FXML
private Pane profileDropdown;
@FXML
private Button settingsDropdown;
@FXML
private Pane addProfilePopup;
@FXML
private Label addProfileNameLabel;
@FXML
private TextField addProfileNameField;
@FXML
private Label addProfileEmailLabel;
@FXML
private TextField addProfileEmailField;
@FXML
private Label addProfileNoPhoneLabel;
@FXML
private TextField addProfileNoPhoneField;
@FXML
private Label addProfileDateOfBirthLabel;
@FXML
private TextField addProfileDateOfBirthField;
@FXML
private Label addProfileAddressLabel;
@FXML
private TextField addProfileAddressField;
@FXML
private Label addProfileProfilePictureLabel;
@FXML
private Label addProfileProfileImagePathLabel;
@FXML
private Button addProfileApplyButton;
@FXML
private Button addProfileCancelButton;
@FXML
private Label addProfileProfileImageFullPathLabel;
@FXML
private Button buttonAddProfile;
@FXML
private Pane addProfileChooseFilePane;
@FXML
private GridPane profileCardContainer;
@FXML
private Label profileDetailsVarFullName;
@FXML
private Label profileDetailsVarPhone;
@FXML
private Label profileDetailsVarDateOfBirth;
@FXML
private Label profileDetailsVarEmail;
@FXML
private Label profileDetailsVarAddress;
@FXML
public Pane paneSelectAProfile;
private ProfileDetailsListener profileDetailsListener;
private DeleteCashierListener deleteCashierListener;
private EditCashierListener editCashierListener;
@FXML
private ImageView profileDetailsVarImage;
@FXML
private TextField searchTermProfile;
@FXML
private Pane confirmDeleteProfilePane;
@FXML
private Label confirmDeleteVariableProfileName;
@FXML
private Button confirmDeleteDeleteButtonProfile;
@FXML
private Button confirmDeleteCancelButtonProfile;
@FXML
private Label confirmDeleteKeyProfile;
@FXML
private Label keyProfileOnPopup;
@FXML
private Label addProfileLabel;
private static String hashMD5(String input) {
StringBuilder result = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] byteData = md.digest();
for (byte aByteData : byteData) {
result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result.toString();
}
@FXML
void onAddProfileChooseFilePaneMouseClick(MouseEvent event) {
FileChooser filechooser = new FileChooser();
filechooser.setTitle("Select profile picture");
filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png")); | package com.systeminventory.controller;
public class cashierController {
@FXML
private Pane backgroundPopup;
@FXML
private Button buttonCashier;
@FXML
private Button buttonDashboard;
@FXML
private Button buttonProduct;
@FXML
private Button logoutDropdown;
@FXML
private Pane profileDropdown;
@FXML
private Button settingsDropdown;
@FXML
private Pane addProfilePopup;
@FXML
private Label addProfileNameLabel;
@FXML
private TextField addProfileNameField;
@FXML
private Label addProfileEmailLabel;
@FXML
private TextField addProfileEmailField;
@FXML
private Label addProfileNoPhoneLabel;
@FXML
private TextField addProfileNoPhoneField;
@FXML
private Label addProfileDateOfBirthLabel;
@FXML
private TextField addProfileDateOfBirthField;
@FXML
private Label addProfileAddressLabel;
@FXML
private TextField addProfileAddressField;
@FXML
private Label addProfileProfilePictureLabel;
@FXML
private Label addProfileProfileImagePathLabel;
@FXML
private Button addProfileApplyButton;
@FXML
private Button addProfileCancelButton;
@FXML
private Label addProfileProfileImageFullPathLabel;
@FXML
private Button buttonAddProfile;
@FXML
private Pane addProfileChooseFilePane;
@FXML
private GridPane profileCardContainer;
@FXML
private Label profileDetailsVarFullName;
@FXML
private Label profileDetailsVarPhone;
@FXML
private Label profileDetailsVarDateOfBirth;
@FXML
private Label profileDetailsVarEmail;
@FXML
private Label profileDetailsVarAddress;
@FXML
public Pane paneSelectAProfile;
private ProfileDetailsListener profileDetailsListener;
private DeleteCashierListener deleteCashierListener;
private EditCashierListener editCashierListener;
@FXML
private ImageView profileDetailsVarImage;
@FXML
private TextField searchTermProfile;
@FXML
private Pane confirmDeleteProfilePane;
@FXML
private Label confirmDeleteVariableProfileName;
@FXML
private Button confirmDeleteDeleteButtonProfile;
@FXML
private Button confirmDeleteCancelButtonProfile;
@FXML
private Label confirmDeleteKeyProfile;
@FXML
private Label keyProfileOnPopup;
@FXML
private Label addProfileLabel;
private static String hashMD5(String input) {
StringBuilder result = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] byteData = md.digest();
for (byte aByteData : byteData) {
result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1));
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result.toString();
}
@FXML
void onAddProfileChooseFilePaneMouseClick(MouseEvent event) {
FileChooser filechooser = new FileChooser();
filechooser.setTitle("Select profile picture");
filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png")); | File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage()); | 0 | 2023-11-18 02:53:02+00:00 | 4k |
CivilisationPlot/CivilisationPlot_Papermc | src/main/java/fr/laptoff/civilisationplot/plots/Plot.java | [
{
"identifier": "CivilisationPlot",
"path": "src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java",
"snippet": "public final class CivilisationPlot extends JavaPlugin {\n\n public static final Logger LOGGER = Logger.getLogger(\"CivilisationPlot\");\n private static CivilisationPlot instance;\n private DatabaseManager database;\n private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml)\n\n @Override\n public void onEnable() {\n instance = this;\n saveDefaultConfig();\n ConfigManager configManagerMessages = new ConfigManager(getConfig().getString(\"Language.language\"));\n configMessages = configManagerMessages.getFileConfiguration();\n\n if (getConfig().getBoolean(\"Database.enable\")){\n database = new DatabaseManager();\n database.connection();\n\n database.setup();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_connection\"));\n }\n\n Civil.load();\n Nation.load();\n\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n getServer().getPluginManager().registerEvents(new joinListener(), this);\n }\n\n @Override\n public void onDisable() {\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n if (DatabaseManager.isOnline()){\n database.disconnection();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_disconnection\"));\n }\n }\n\n public static CivilisationPlot getInstance(){\n return instance;\n }\n\n public DatabaseManager getDatabase(){\n return database;\n }\n\n}"
},
{
"identifier": "DatabaseManager",
"path": "src/main/java/fr/laptoff/civilisationplot/Managers/DatabaseManager.java",
"snippet": "public class DatabaseManager {\n\n private static Connection co;\n private static final CivilisationPlot plugin = CivilisationPlot.getInstance();\n\n public Connection getConnection()\n {\n return co;\n }\n\n public void connection()\n {\n if(!isConnected())\n {\n try\n {\n String motorDriver = \"org.mariadb\";\n\n if (Objects.requireNonNull(plugin.getConfig().getString(\"Database.motor\")).equalsIgnoreCase(\"mysql\"))\n motorDriver = \"com.mysql.cj\";\n\n Class.forName(motorDriver + \".jdbc.Driver\"); //loading of the driver.\n co = DriverManager.getConnection(\"jdbc:\" + plugin.getConfig().getString(\"Database.motor\") + \"://\" + plugin.getConfig().getString(\"Database.host\") + \":\" + plugin.getConfig().getString(\"Database.port\") + \"/\" + plugin.getConfig().getString(\"Database.database_name\"), plugin.getConfig().getString(\"Database.user\"), plugin.getConfig().getString(\"Database.password\"));\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public void disconnection()\n {\n if (isConnected())\n {\n try\n {\n co.close();\n }\n catch(SQLException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n\n\n public static boolean isConnected()\n {\n try {\n return co != null && !co.isClosed() && plugin.getConfig().getBoolean(\"Database.enable\");\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n }\n return false;\n }\n\n public static boolean isOnline() {\n try {\n return !(co == null) || !co.isClosed();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public boolean doesTableExist(String tableName) {\n try {\n DatabaseMetaData metaData = co.getMetaData();\n ResultSet resultSet = metaData.getTables(null, null, tableName, null);\n\n return resultSet.next();\n } catch (SQLException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n\n public void setup(){\n try {\n\n //create the civils table\n if (!doesTableExist(\"civils\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE civils (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), name VARCHAR(50), money INT, nation VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the nations table\n if (!doesTableExist(\"nations\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE nations (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), uuid VARCHAR(50), leader_uuid VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the plots table\n if (!doesTableExist(\"plots\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE plots (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), wordlName VARCHAR(50), xCoordinates DOUBLE, yCoordinates DOUBLE, level TINYINT, propertyType VARCHAR(50), uuidProprietary VARCHAR(50));\");\n pstmt.execute();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "FileManager",
"path": "src/main/java/fr/laptoff/civilisationplot/Managers/FileManager.java",
"snippet": "public class FileManager {\n\n public static void createResourceFile(File file){\n File file_ = new File(CivilisationPlot.getInstance().getDataFolder() + \"/\" + file.getPath());\n if (file_.exists())\n return;\n\n file.getParentFile().mkdirs();\n\n CivilisationPlot.getInstance().saveResource(file.getPath(), false);\n }\n\n public static void createFile(File file){\n if (file.exists())\n return;\n\n file.getParentFile().mkdirs();\n try {\n file.createNewFile();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void rewrite(File file, String text){\n //This method erase the text into the file and write the new text\n if (!file.exists())\n return;\n\n try {\n FileWriter writer = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(writer);\n bw.write(text);\n bw.flush();\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fr.laptoff.civilisationplot.CivilisationPlot;
import fr.laptoff.civilisationplot.Managers.DatabaseManager;
import fr.laptoff.civilisationplot.Managers.FileManager;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 2,532 | package fr.laptoff.civilisationplot.plots;
public class Plot {
private String WorldName;
private double XCoordinate;
private double YCoordinates;
private String PropertyType;
private UUID Proprietary;
private byte Level;
private UUID Uuid;
private File file;
private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json");
private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();
private static List<UUID> plotsList = new ArrayList<UUID>();
public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){
this.WorldName = worldName;
this.XCoordinate = xCoordinates;
this.YCoordinates = yCoordinates;
this.PropertyType = propertyType;
this.Proprietary = proprietary;
this.Level = level;
this.Uuid = uuid;
this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json");
plotsList.add(this.Uuid);
}
public Chunk getChunk(){
return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk();
}
public World getWorld(){
return Bukkit.getWorld(this.WorldName);
}
public String getPropertyType(){
return this.PropertyType;
}
public UUID getProprietary(){
return this.Proprietary;
}
public byte getLevel(){
return this.Level;
}
public UUID getUuid(){
return this.Uuid;
}
public void setWorld(World world){
this.WorldName = world.getName();
}
public void setPropertyType(String s){
this.PropertyType = s;
}
public void setProprietary(UUID uuid){
this.Proprietary = uuid;
}
public void setLevel(byte lvl){
this.Level = lvl;
}
public static List<UUID> getPlotsList(){
return plotsList;
}
//Database
public void updateObjectFromDatabase(){ | package fr.laptoff.civilisationplot.plots;
public class Plot {
private String WorldName;
private double XCoordinate;
private double YCoordinates;
private String PropertyType;
private UUID Proprietary;
private byte Level;
private UUID Uuid;
private File file;
private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json");
private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();
private static List<UUID> plotsList = new ArrayList<UUID>();
public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){
this.WorldName = worldName;
this.XCoordinate = xCoordinates;
this.YCoordinates = yCoordinates;
this.PropertyType = propertyType;
this.Proprietary = proprietary;
this.Level = level;
this.Uuid = uuid;
this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json");
plotsList.add(this.Uuid);
}
public Chunk getChunk(){
return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk();
}
public World getWorld(){
return Bukkit.getWorld(this.WorldName);
}
public String getPropertyType(){
return this.PropertyType;
}
public UUID getProprietary(){
return this.Proprietary;
}
public byte getLevel(){
return this.Level;
}
public UUID getUuid(){
return this.Uuid;
}
public void setWorld(World world){
this.WorldName = world.getName();
}
public void setPropertyType(String s){
this.PropertyType = s;
}
public void setProprietary(UUID uuid){
this.Proprietary = uuid;
}
public void setLevel(byte lvl){
this.Level = lvl;
}
public static List<UUID> getPlotsList(){
return plotsList;
}
//Database
public void updateObjectFromDatabase(){ | if (!DatabaseManager.isOnline()) | 1 | 2023-11-11 18:26:55+00:00 | 4k |
dsntk/dsntk-java-server | src/main/java/io/dsntk/server/rest/dto/SimpleDto.java | [
{
"identifier": "CastType",
"path": "src/main/java/io/dsntk/server/common/CastType.java",
"snippet": "public enum CastType {\n CT_BYTE,\n CT_SHORT,\n CT_INT,\n CT_LONG,\n CT_FLOAT,\n CT_DOUBLE,\n CT_CHAR,\n CT_BOOLEAN,\n CT_STRING,\n CT_OBJECT_ARRAY;\n\n public boolean isPrimitive() {\n return this == CT_BYTE ||\n this == CT_SHORT ||\n this == CT_INT ||\n this == CT_LONG ||\n this == CT_FLOAT ||\n this == CT_DOUBLE ||\n this == CT_CHAR ||\n this == CT_BOOLEAN ||\n this == CT_STRING;\n }\n\n public static CastType fromClass(Class<?> clazz) throws RpcException {\n switch (clazz.getName()) {\n case \"byte\", \"java.lang.Byte\" -> {\n return CT_BYTE;\n }\n case \"short\", \"java.lang.Short\" -> {\n return CT_SHORT;\n }\n case \"int\", \"java.lang.Integer\" -> {\n return CT_INT;\n }\n case \"long\", \"java.lang.Long\" -> {\n return CT_LONG;\n }\n case \"float\", \"java.lang.Float\" -> {\n return CT_FLOAT;\n }\n case \"double\", \"java.lang.Double\" -> {\n return CT_DOUBLE;\n }\n case \"char\", \"java.lang.Character\" -> {\n return CT_CHAR;\n }\n case \"boolean\", \"java.lang.Boolean\" -> {\n return CT_BOOLEAN;\n }\n case \"java.lang.String\" -> {\n return CT_STRING;\n }\n case \"[Ljava.lang.Object;\" -> {\n return CT_OBJECT_ARRAY;\n }\n }\n throw new RpcException(String.format(\"invalid cast class: %s\", clazz.getName()));\n }\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/io/dsntk/server/common/Utils.java",
"snippet": "public class Utils {\n /**\n * When the input string ends with `.0`, then strips this off.\n *\n * @param input String to be stripped off.\n * @return Stripped string.\n */\n public static String stripTrailingZero(String input) {\n if (input.endsWith(\".0\")) {\n return input.substring(0, input.length() - 2);\n } else {\n return input;\n }\n }\n}"
},
{
"identifier": "XsdType",
"path": "src/main/java/io/dsntk/server/common/XsdType.java",
"snippet": "public enum XsdType {\n XSD_STRING,\n XSD_INTEGER,\n XSD_DECIMAL,\n XSD_DOUBLE,\n XSD_BOOLEAN,\n XSD_DATE,\n XSD_DATE_TIME,\n XSD_TIME,\n XSD_DURATION;\n\n /**\n * Returns XSD type created from its textual representation.\n *\n * @param typeName Name of the XSD type.\n * @return XSD type enumeration instance.\n * @throws RpcException when the name of the type is invalid.\n */\n public static XsdType fromString(String typeName) throws RpcException {\n return switch (typeName) {\n case \"xsd:integer\" -> XsdType.XSD_INTEGER;\n case \"xsd:double\" -> XsdType.XSD_DOUBLE;\n case \"xsd:decimal\" -> XsdType.XSD_DECIMAL;\n case \"xsd:string\" -> XsdType.XSD_STRING;\n case \"xsd:boolean\" -> XsdType.XSD_BOOLEAN;\n case \"xsd:date\" -> XsdType.XSD_DATE;\n case \"xsd:time\" -> XsdType.XSD_TIME;\n case \"xsd:dateTime\" -> XsdType.XSD_DATE_TIME;\n case \"xsd:duration\" -> XsdType.XSD_DURATION;\n default -> throw new RpcException(String.format(\"invalid XSD type name: %s\", typeName));\n };\n }\n}"
},
{
"identifier": "RpcException",
"path": "src/main/java/io/dsntk/server/rest/errors/RpcException.java",
"snippet": "public class RpcException extends Exception {\n\n /**\n * Creates RPC exception.\n *\n * @param details Reason of the exception.\n */\n public RpcException(String details) {\n super(details);\n }\n}"
}
] | import com.fasterxml.jackson.annotation.JsonProperty;
import io.dsntk.server.common.CastType;
import io.dsntk.server.common.Utils;
import io.dsntk.server.common.XsdType;
import io.dsntk.server.rest.errors.RpcException;
import lombok.Getter;
import lombok.Setter;
import java.lang.reflect.Array; | 2,071 | package io.dsntk.server.rest.dto;
/**
* DTO representing a simple type value.
*/
@Getter
@Setter
public class SimpleDto {
/** Name of the value's type. */
@JsonProperty("type")
private String typ;
/** Value represented as text. */
@JsonProperty("text")
private String text;
/** Flag indicating if the value is `nil`. */
@JsonProperty("isNil")
private boolean nil;
public Object toObject(Class<?> castClass) throws RpcException {
CastType castType = CastType.fromClass(castClass);
XsdType xsdType = XsdType.fromString(this.typ);
switch (xsdType) {
case XSD_STRING -> {
if (castType == CastType.CT_STRING) {
return this.text;
}
if (castType == CastType.CT_CHAR) {
if (this.text.length() == 1) {
return this.text.charAt(0);
}
}
if (castType == CastType.CT_OBJECT_ARRAY) {
String[] arr = (String[]) Array.newInstance(java.lang.String.class, 1);
Array.set(arr, 0, this.text);
return arr;
}
}
case XSD_INTEGER -> {
if (castType == CastType.CT_BYTE) {
return Byte.valueOf(this.text);
}
if (castType == CastType.CT_SHORT) {
return Short.valueOf(this.text);
}
if (castType == CastType.CT_INT) {
return Integer.valueOf(this.text);
}
if (castType == CastType.CT_LONG) {
return Long.valueOf(this.text);
}
}
case XSD_DOUBLE -> {
if (castType == CastType.CT_FLOAT) {
return Float.valueOf(this.text);
}
if (castType == CastType.CT_DOUBLE) {
return Double.valueOf(this.text);
}
}
case XSD_DECIMAL -> {
if (castType == CastType.CT_BYTE) {
return Byte.valueOf(this.text);
}
if (castType == CastType.CT_SHORT) {
return Short.valueOf(this.text);
}
if (castType == CastType.CT_INT) {
return Integer.valueOf(this.text);
}
if (castType == CastType.CT_LONG) {
return Long.valueOf(this.text);
}
if (castType == CastType.CT_FLOAT) {
return Float.valueOf(this.text);
}
if (castType == CastType.CT_DOUBLE) {
return Double.valueOf(this.text);
}
}
}
throw new RpcException(String.format("simple DTO conversion to object failed, class: %s, type: %s", castClass.getName(), xsdType));
}
public static SimpleDto fromObject(Object object, CastType castType) throws RpcException {
switch (castType) {
case CT_BYTE -> {
return SimpleDto.fromByte((Byte) object);
}
case CT_SHORT -> {
return SimpleDto.fromShort((Short) object);
}
case CT_INT -> {
return SimpleDto.fromInteger((Integer) object);
}
case CT_LONG -> {
return SimpleDto.fromLong((Long) object);
}
case CT_FLOAT -> {
return SimpleDto.fromFloat((Float) object);
}
case CT_DOUBLE -> {
return SimpleDto.fromDouble((Double) object);
}
case CT_CHAR -> {
return SimpleDto.fromCharacter((Character) object);
}
case CT_STRING -> {
return SimpleDto.fromString((String) object);
}
}
throw new RpcException(String.format("simple DTO conversion from object failed, class: %s, type: %s", object.getClass().getName(), castType));
}
private static SimpleDto fromByte(Byte object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromShort(Short object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromInteger(Integer object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromLong(Long object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromFloat(Float object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal"; | package io.dsntk.server.rest.dto;
/**
* DTO representing a simple type value.
*/
@Getter
@Setter
public class SimpleDto {
/** Name of the value's type. */
@JsonProperty("type")
private String typ;
/** Value represented as text. */
@JsonProperty("text")
private String text;
/** Flag indicating if the value is `nil`. */
@JsonProperty("isNil")
private boolean nil;
public Object toObject(Class<?> castClass) throws RpcException {
CastType castType = CastType.fromClass(castClass);
XsdType xsdType = XsdType.fromString(this.typ);
switch (xsdType) {
case XSD_STRING -> {
if (castType == CastType.CT_STRING) {
return this.text;
}
if (castType == CastType.CT_CHAR) {
if (this.text.length() == 1) {
return this.text.charAt(0);
}
}
if (castType == CastType.CT_OBJECT_ARRAY) {
String[] arr = (String[]) Array.newInstance(java.lang.String.class, 1);
Array.set(arr, 0, this.text);
return arr;
}
}
case XSD_INTEGER -> {
if (castType == CastType.CT_BYTE) {
return Byte.valueOf(this.text);
}
if (castType == CastType.CT_SHORT) {
return Short.valueOf(this.text);
}
if (castType == CastType.CT_INT) {
return Integer.valueOf(this.text);
}
if (castType == CastType.CT_LONG) {
return Long.valueOf(this.text);
}
}
case XSD_DOUBLE -> {
if (castType == CastType.CT_FLOAT) {
return Float.valueOf(this.text);
}
if (castType == CastType.CT_DOUBLE) {
return Double.valueOf(this.text);
}
}
case XSD_DECIMAL -> {
if (castType == CastType.CT_BYTE) {
return Byte.valueOf(this.text);
}
if (castType == CastType.CT_SHORT) {
return Short.valueOf(this.text);
}
if (castType == CastType.CT_INT) {
return Integer.valueOf(this.text);
}
if (castType == CastType.CT_LONG) {
return Long.valueOf(this.text);
}
if (castType == CastType.CT_FLOAT) {
return Float.valueOf(this.text);
}
if (castType == CastType.CT_DOUBLE) {
return Double.valueOf(this.text);
}
}
}
throw new RpcException(String.format("simple DTO conversion to object failed, class: %s, type: %s", castClass.getName(), xsdType));
}
public static SimpleDto fromObject(Object object, CastType castType) throws RpcException {
switch (castType) {
case CT_BYTE -> {
return SimpleDto.fromByte((Byte) object);
}
case CT_SHORT -> {
return SimpleDto.fromShort((Short) object);
}
case CT_INT -> {
return SimpleDto.fromInteger((Integer) object);
}
case CT_LONG -> {
return SimpleDto.fromLong((Long) object);
}
case CT_FLOAT -> {
return SimpleDto.fromFloat((Float) object);
}
case CT_DOUBLE -> {
return SimpleDto.fromDouble((Double) object);
}
case CT_CHAR -> {
return SimpleDto.fromCharacter((Character) object);
}
case CT_STRING -> {
return SimpleDto.fromString((String) object);
}
}
throw new RpcException(String.format("simple DTO conversion from object failed, class: %s, type: %s", object.getClass().getName(), castType));
}
private static SimpleDto fromByte(Byte object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromShort(Short object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromInteger(Integer object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromLong(Long object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal";
value.text = String.valueOf(object);
value.nil = false;
return value;
}
private static SimpleDto fromFloat(Float object) {
SimpleDto value = new SimpleDto();
value.typ = "xsd:decimal"; | value.text = Utils.stripTrailingZero(String.format("%s", object)); | 1 | 2023-11-10 18:06:05+00:00 | 4k |
JohnTWD/meteor-rejects-vanillacpvp | src/main/java/anticope/rejects/gui/servers/ServerManagerScreen.java | [
{
"identifier": "MeteorRejectsAddon",
"path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java",
"snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(\"Rejects\", Items.BARRIER.getDefaultStack());\n public static final HudGroup HUD_GROUP = new HudGroup(\"Rejects\");\n\n @Override\n public void onInitialize() {\n LOG.info(\"Initializing Meteor Rejects Addon\");\n\n // Modules\n Modules modules = Modules.get();\n\n modules.add(new BetterAimbot());\n modules.add(new NewerNewChunks());\n modules.add(new BaseFinderNew());\n modules.add(new Shield());\n modules.add(new TestModule());\n modules.add(((new HitboxDesync())));\n modules.add(new Announcer());\n modules.add(new PacketLogger());\n modules.add(new ManualCrystal());\n modules.add(new TweakedAutoTool());\n modules.add(new MacroAnchorAuto());\n modules.add(new AutoMend());\n modules.add(new BowBomb());\n modules.add(new AutoCityPlus());\n modules.add(new PistonAura());\n modules.add(new CevBreaker());\n\n modules.add(new AimAssist());\n modules.add(new AntiBot());\n modules.add(new AntiCrash());\n modules.add(new AntiSpawnpoint());\n modules.add(new AntiVanish());\n modules.add(new ArrowDmg());\n modules.add(new AutoBedTrap());\n modules.add(new AutoCraft());\n modules.add(new AutoExtinguish());\n modules.add(new AutoFarm());\n modules.add(new AutoGrind());\n modules.add(new AutoLogin());\n modules.add(new AutoPot());\n modules.add(new AutoSoup());\n modules.add(new AutoTNT());\n modules.add(new AutoWither());\n modules.add(new BoatGlitch());\n modules.add(new BlockIn());\n modules.add(new BoatPhase());\n modules.add(new Boost());\n modules.add(new BungeeCordSpoof());\n modules.add(new ChatBot());\n modules.add(new ChestAura());\n modules.add(new ChorusExploit());\n modules.add(new ColorSigns());\n modules.add(new Confuse());\n modules.add(new CoordLogger());\n modules.add(new CustomPackets());\n modules.add(new ExtraElytra());\n modules.add(new FullFlight());\n modules.add(new GamemodeNotifier());\n modules.add(new GhostMode());\n modules.add(new Glide());\n modules.add(new InstaMine());\n modules.add(new ItemGenerator());\n modules.add(new InteractionMenu());\n modules.add(new Jetpack());\n modules.add(new KnockbackPlus());\n modules.add(new Lavacast());\n modules.add(new MossBot());\n modules.add(new NewChunks());\n modules.add(new NoJumpDelay());\n modules.add(new ObsidianFarm());\n modules.add(new OreSim());\n modules.add(new PacketFly());\n modules.add(new Painter());\n modules.add(new Rendering());\n modules.add(new RoboWalk());\n modules.add(new ShieldBypass());\n modules.add(new SilentDisconnect());\n modules.add(new SkeletonESP());\n modules.add(new SoundLocator());\n modules.add(new TreeAura());\n modules.add(new VehicleOneHit());\n\n // Commands\n Commands.add(new CenterCommand());\n Commands.add(new ClearChatCommand());\n Commands.add(new GhostCommand());\n Commands.add(new GiveCommand());\n Commands.add(new HeadsCommand());\n Commands.add(new KickCommand());\n Commands.add(new LocateCommand());\n Commands.add(new PanicCommand());\n Commands.add(new ReconnectCommand());\n Commands.add(new ServerCommand());\n Commands.add(new SaveSkinCommand());\n Commands.add(new SeedCommand());\n Commands.add(new SetBlockCommand());\n Commands.add(new SetVelocityCommand());\n Commands.add(new TeleportCommand());\n Commands.add(new TerrainExport());\n Commands.add(new EntityDesyncCommand());\n Commands.add(new BaseFinderNewCommands());\n Commands.add(new NewChunkCounter());\n\n // HUD\n Hud hud = Systems.get(Hud.class);\n hud.register(RadarHud.INFO);\n\n // Themes\n GuiThemes.add(new MeteorRoundedGuiTheme());\n }\n\n @Override\n public void onRegisterCategories() {\n Modules.registerCategory(CATEGORY);\n }\n\n @Override\n public String getWebsite() {\n return \"https://github.com/JohnTWD/meteor-rejects-vanillacpvp\";\n }\n\n @Override\n public GithubRepo getRepo() {\n return new GithubRepo(\"JohnTWD\", \"meteor-rejects-vanilla-cpvp\");\n }\n\n @Override\n public String getCommit() {\n String commit = FabricLoader\n .getInstance()\n .getModContainer(\"meteor-rejects\")\n .get().getMetadata()\n .getCustomValue(\"github:sha\")\n .getAsString();\n LOG.info(String.format(\"Rejects version: %s\", commit));\n return commit.isEmpty() ? null : commit.trim();\n }\n\n public String getPackage() {\n return \"anticope.rejects\";\n }\n}"
},
{
"identifier": "MultiplayerScreenAccessor",
"path": "src/main/java/anticope/rejects/mixin/MultiplayerScreenAccessor.java",
"snippet": "@Mixin(MultiplayerScreen.class)\npublic interface MultiplayerScreenAccessor {\n @Accessor(\"serverListWidget\")\n MultiplayerServerListWidget getServerListWidget();\n}"
},
{
"identifier": "ServerListAccessor",
"path": "src/main/java/anticope/rejects/mixin/ServerListAccessor.java",
"snippet": "@Mixin(ServerList.class)\npublic interface ServerListAccessor {\n @Accessor\n List<ServerInfo> getServers();\n}"
},
{
"identifier": "IPAddress",
"path": "src/main/java/anticope/rejects/utils/server/IPAddress.java",
"snippet": "public class IPAddress {\n private final int[] octets;\n private final int port;\n\n public IPAddress(int o1, int o2, int o3, int o4, int port) {\n this.octets = new int[]{o1, o2, o3, o4};\n this.port = port;\n }\n\n public IPAddress(int[] octets, int port) {\n this.octets = octets;\n this.port = port;\n }\n\n public static IPAddress fromText(String ip) {\n String[] sections = ip.split(\":\");\n if (sections.length < 1 || sections.length > 2)\n return null;\n\n int port = 25565;\n if (sections.length == 2) {\n try {\n port = Integer.parseInt(sections[1].trim());\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n int[] octets = new int[4];\n\n String[] address = sections[0].trim().split(\"\\\\.\");\n if (address.length != 4)\n return null;\n\n for (int i = 0; i < 4; i++) {\n try {\n octets[i] = Integer.parseInt(address[i].trim());\n } catch (NumberFormatException e) {\n return null;\n }\n }\n\n return new IPAddress(octets, port);\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof IPAddress other))\n return false;\n\n if (octets.length != other.octets.length)\n return false;\n\n if (port != other.port)\n return false;\n\n for (int i = 0; i < octets.length; i++)\n if (octets[i] != other.octets[i])\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n assert (octets.length == 4);\n\n int hash = 43;\n hash = hash * 59 + octets[0];\n hash = hash * 83 + octets[1];\n hash = hash * 71 + octets[2];\n hash = hash * 17 + octets[3];\n hash = hash * 31 + port;\n return hash;\n }\n\n @Override\n public String toString() {\n if (octets.length == 0)\n return null;\n\n StringBuilder result = new StringBuilder();\n result.append(octets[0]);\n for (int i = 1; i < octets.length; i++) {\n result.append('.').append(octets[i]);\n }\n result.append(':').append(port);\n return result.toString();\n }\n}"
}
] | import anticope.rejects.MeteorRejectsAddon;
import anticope.rejects.mixin.MultiplayerScreenAccessor;
import anticope.rejects.mixin.ServerListAccessor;
import anticope.rejects.utils.server.IPAddress;
import meteordevelopment.meteorclient.gui.GuiTheme;
import meteordevelopment.meteorclient.gui.WindowScreen;
import meteordevelopment.meteorclient.gui.widgets.containers.WContainer;
import meteordevelopment.meteorclient.gui.widgets.containers.WHorizontalList;
import meteordevelopment.meteorclient.gui.widgets.pressable.WButton;
import meteordevelopment.meteorclient.utils.misc.IGetter;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.option.ServerList;
import net.minecraft.client.toast.SystemToast;
import net.minecraft.text.Text;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryUtil;
import org.lwjgl.util.tinyfd.TinyFileDialogs;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer; | 2,969 | package anticope.rejects.gui.servers;
public class ServerManagerScreen extends WindowScreen {
private static final PointerBuffer saveFileFilters;
static {
saveFileFilters = BufferUtils.createPointerBuffer(1);
saveFileFilters.put(MemoryUtil.memASCII("*.txt"));
saveFileFilters.rewind();
}
private final MultiplayerScreen multiplayerScreen;
public ServerManagerScreen(GuiTheme theme, MultiplayerScreen multiplayerScreen) {
super(theme, "Manage Servers");
this.parent = multiplayerScreen;
this.multiplayerScreen = multiplayerScreen;
}
public static Runnable tryHandle(ThrowingRunnable<?> tr, Consumer<Throwable> handler) {
return Objects.requireNonNull(tr).addHandler(handler);
}
@Override
public void initWidgets() {
WHorizontalList l = add(theme.horizontalList()).expandX().widget();
addButton(l, "Find Servers (new)", () -> new ServerFinderScreen(theme, multiplayerScreen, this));
addButton(l, "Find Servers (legacy)", () -> new LegacyServerFinderScreen(theme, multiplayerScreen, this));
addButton(l, "Clean Up", () -> new CleanUpScreen(theme, multiplayerScreen, this));
l = add(theme.horizontalList()).expandX().widget();
l.add(theme.button("Save IPs")).expandX().widget().action = tryHandle(() -> {
String targetPath = TinyFileDialogs.tinyfd_saveFileDialog("Save IPs", null, saveFileFilters, null);
if (targetPath == null) return;
if (!targetPath.endsWith(".txt")) targetPath += ".txt";
Path filePath = Path.of(targetPath);
int newIPs = 0;
Set<IPAddress> hashedIPs = new HashSet<>();
if (Files.exists(filePath)) {
try {
List<String> ips = Files.readAllLines(filePath);
for (String ip : ips) {
IPAddress parsedIP = IPAddress.fromText(ip);
if (parsedIP != null)
hashedIPs.add(parsedIP);
}
} catch (IOException e) {
e.printStackTrace();
}
}
ServerList servers = multiplayerScreen.getServerList();
for (int i = 0; i < servers.size(); i++) {
ServerInfo info = servers.get(i);
IPAddress addr = IPAddress.fromText(info.address);
if (addr != null && hashedIPs.add(addr))
newIPs++;
}
StringBuilder fileOutput = new StringBuilder();
for (IPAddress ip : hashedIPs) {
String stringIP = ip.toString();
if (stringIP != null)
fileOutput.append(stringIP).append("\n");
}
try {
Files.writeString(filePath, fileOutput.toString());
} catch (IOException e) {
e.printStackTrace();
}
toast("Success!", newIPs == 1 ? "Saved %s new IP" : "Saved %s new IPs", newIPs);
}, e -> {
MeteorRejectsAddon.LOG.error("Could not save IPs");
toast("Something went wrong", "The IPs could not be saved, look at the log for details");
});
l.add(theme.button("Load IPs")).expandX().widget().action = tryHandle(() -> {
String targetPath = TinyFileDialogs.tinyfd_openFileDialog("Load IPs", null, saveFileFilters, "", false);
if (targetPath == null) return;
Path filePath = Path.of(targetPath);
if (!Files.exists(filePath)) return;
| package anticope.rejects.gui.servers;
public class ServerManagerScreen extends WindowScreen {
private static final PointerBuffer saveFileFilters;
static {
saveFileFilters = BufferUtils.createPointerBuffer(1);
saveFileFilters.put(MemoryUtil.memASCII("*.txt"));
saveFileFilters.rewind();
}
private final MultiplayerScreen multiplayerScreen;
public ServerManagerScreen(GuiTheme theme, MultiplayerScreen multiplayerScreen) {
super(theme, "Manage Servers");
this.parent = multiplayerScreen;
this.multiplayerScreen = multiplayerScreen;
}
public static Runnable tryHandle(ThrowingRunnable<?> tr, Consumer<Throwable> handler) {
return Objects.requireNonNull(tr).addHandler(handler);
}
@Override
public void initWidgets() {
WHorizontalList l = add(theme.horizontalList()).expandX().widget();
addButton(l, "Find Servers (new)", () -> new ServerFinderScreen(theme, multiplayerScreen, this));
addButton(l, "Find Servers (legacy)", () -> new LegacyServerFinderScreen(theme, multiplayerScreen, this));
addButton(l, "Clean Up", () -> new CleanUpScreen(theme, multiplayerScreen, this));
l = add(theme.horizontalList()).expandX().widget();
l.add(theme.button("Save IPs")).expandX().widget().action = tryHandle(() -> {
String targetPath = TinyFileDialogs.tinyfd_saveFileDialog("Save IPs", null, saveFileFilters, null);
if (targetPath == null) return;
if (!targetPath.endsWith(".txt")) targetPath += ".txt";
Path filePath = Path.of(targetPath);
int newIPs = 0;
Set<IPAddress> hashedIPs = new HashSet<>();
if (Files.exists(filePath)) {
try {
List<String> ips = Files.readAllLines(filePath);
for (String ip : ips) {
IPAddress parsedIP = IPAddress.fromText(ip);
if (parsedIP != null)
hashedIPs.add(parsedIP);
}
} catch (IOException e) {
e.printStackTrace();
}
}
ServerList servers = multiplayerScreen.getServerList();
for (int i = 0; i < servers.size(); i++) {
ServerInfo info = servers.get(i);
IPAddress addr = IPAddress.fromText(info.address);
if (addr != null && hashedIPs.add(addr))
newIPs++;
}
StringBuilder fileOutput = new StringBuilder();
for (IPAddress ip : hashedIPs) {
String stringIP = ip.toString();
if (stringIP != null)
fileOutput.append(stringIP).append("\n");
}
try {
Files.writeString(filePath, fileOutput.toString());
} catch (IOException e) {
e.printStackTrace();
}
toast("Success!", newIPs == 1 ? "Saved %s new IP" : "Saved %s new IPs", newIPs);
}, e -> {
MeteorRejectsAddon.LOG.error("Could not save IPs");
toast("Something went wrong", "The IPs could not be saved, look at the log for details");
});
l.add(theme.button("Load IPs")).expandX().widget().action = tryHandle(() -> {
String targetPath = TinyFileDialogs.tinyfd_openFileDialog("Load IPs", null, saveFileFilters, "", false);
if (targetPath == null) return;
Path filePath = Path.of(targetPath);
if (!Files.exists(filePath)) return;
| List<ServerInfo> servers = ((ServerListAccessor) multiplayerScreen.getServerList()).getServers(); | 2 | 2023-11-13 08:11:28+00:00 | 4k |
stiemannkj1/java-utilities | src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java | [
{
"identifier": "binarySearchArrayPrefixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(prefixes);\n}"
},
{
"identifier": "binarySearchArraySuffixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutableSuffixMapping<T> binarySearchArraySuffixMapping(\n final Map<String, T> suffixes) {\n return new BinarySearchArraySuffixMapping<>(suffixes);\n}"
},
{
"identifier": "limitedCharArrayTriePrefixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutablePrefixMapping<T> limitedCharArrayTriePrefixMapping(\n final char min, final char max, final Map<String, T> prefixes) {\n return new LimitedCharArrayTriePrefixMapping<>(min, max, prefixes);\n}"
},
{
"identifier": "limitedCharArrayTrieSuffixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public static <T> ImmutableSuffixMapping<T> limitedCharArrayTrieSuffixMapping(\n final char min, final char max, final Map<String, T> suffixes) {\n return new LimitedCharArrayTrieSuffixMapping<>(min, max, suffixes);\n}"
},
{
"identifier": "ImmutablePrefixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public interface ImmutablePrefixMapping<T> extends ImmutablePrefixMatcher {\n\n @Override\n default boolean matchesAnyPrefix(final String string) {\n return keyAndValueForPrefix(string) != null;\n }\n\n default T valueForPrefix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForPrefix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForPrefix(final String string);\n}"
},
{
"identifier": "ImmutableSuffixMapping",
"path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java",
"snippet": "public interface ImmutableSuffixMapping<T> extends ImmutableSuffixMatcher {\n\n @Override\n default boolean matchesAnySuffix(final String string) {\n return keyAndValueForSuffix(string) != null;\n }\n\n default T valueForSuffix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForSuffix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForSuffix(final String string);\n}"
},
{
"identifier": "Pair",
"path": "src/main/java/dev/stiemannkj1/util/Pair.java",
"snippet": "public class Pair<T1, T2> implements Map.Entry<T1, T2> {\n public final T1 first;\n public final T2 second;\n\n private Pair(final T1 first, final T2 second) {\n this.first = first;\n this.second = second;\n }\n\n public T1 first() {\n return first;\n }\n\n public T2 second() {\n return second;\n }\n\n public T1 left() {\n return first;\n }\n\n public T2 right() {\n return second;\n }\n\n public T1 key() {\n return first;\n }\n\n public T2 value() {\n return second;\n }\n\n @Override\n public T1 getKey() {\n return first;\n }\n\n @Override\n public T2 getValue() {\n return second;\n }\n\n @Override\n public T2 setValue(final T2 value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(final Object o) {\n\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Pair<?, ?> pair = (Pair<?, ?>) o;\n\n return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(first, second);\n }\n\n @Override\n public String toString() {\n return \"{\" + first + ',' + second + '}';\n }\n\n public static <T1, T2> Pair<T1, T2> of(final T1 first, final T2 second) {\n return new Pair<>(first, second);\n }\n\n public static <K, V> Pair<K, V> fromEntry(final Map.Entry<K, V> entry) {\n return new Pair<>(entry.getKey(), entry.getValue());\n }\n\n public static final class NameValue<V> extends Pair<String, V> {\n private NameValue(final String name, final V value) {\n super(name, value);\n }\n\n public String name() {\n return first;\n }\n }\n\n public static <V> NameValue<V> nameValuePair(final String name, final V value) {\n return new NameValue<>(name, value);\n }\n}"
}
] | import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping;
import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping;
import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping;
import dev.stiemannkj1.util.Pair;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource; | 3,175 | final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of prefixes.
prefixes.put("aaa", 4);
prefixMap = newPrefixMap(prefixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_prefixes_with_matching_suffixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newPrefixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidPrefixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidPrefixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> prefixes) {
final Class<? extends Exception> expectedExceptionType =
prefixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes));
}
ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes);
}
interface SuffixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"1abc,true,0",
"abe,true,1",
"abed,false,null",
"abd,false,null",
"aba,false,null",
"at,false,null",
"ate,true,2",
"cate,true,2",
"icate,true,2",
"dicate,true,2",
"bdicate,true,2",
"abdicate,true,3",
"i abdicate,true,3",
"abdicated,false,null",
"z,false,null",
"yz,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_suffixes(
final String string, final boolean expectSuffixed, final Integer expectedValue) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
| /*
Copyright 2023 Kyle J. Stiemann
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dev.stiemannkj1.collection.fixmapping;
final class FixMappingsTests {
// TODO test unicode
interface PrefixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"abe,true,1",
"abd,true,2",
"aba,false,null",
"abd,true,2",
"abdi,true,2",
"abdic,true,2",
"abdica,true,2",
"abdicat,true,2",
"abdicat,true,2",
"abdicate,true,3",
"abdicated,true,3",
"x,false,null",
"xy,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_prefixes(
final String string, final boolean expectPrefixed, final Integer expectedValue) {
// Test odd number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
// Test odd number of prefixes.
prefixes.put("xyz", 4);
prefixMap = newPrefixMap(prefixes);
assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string));
assertEquals(expectedValue, prefixMap.valueForPrefix(string));
assertEquals(
getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string));
assertFirstMatchSearchTakesLessSteps(
string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap);
}
@SuppressWarnings("unchecked")
default void detects_prefixes_with_minimal_steps(
final String string,
final String firstMatchEvenKeys,
final String firstMatchOddKeys,
final int firstMatchStepsEvenKeys,
final int longestMatchStepsEvenKeys,
final int firstMatchStepsOddKeys,
final int longestMatchStepsOddKeys) {
// Test even number of prefixes.
final Map<String, Integer> prefixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map;
ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes);
final AtomicLong firstSearchSteps = new AtomicLong();
final AtomicLong longestSearchSteps = new AtomicLong();
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get());
// Test odd number of prefixes.
prefixes.put("aaa", 4);
prefixMap = newPrefixMap(prefixes);
firstSearchSteps.set(0);
longestSearchSteps.set(0);
assertEquals(
Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(false, string, firstSearchSteps));
assertEquals(
Pair.of("abdicate", 3),
((FixMappings.FixMapping<Integer>) prefixMap)
.getKeyAndValue(true, string, longestSearchSteps));
assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get());
assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get());
}
@Test
default void allows_prefixes_with_matching_suffixes() {
// Test odd number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map;
assertDoesNotThrow(() -> newPrefixMap(suffixes));
}
static Stream<Map<String, Integer>> invalidPrefixes() {
return Stream.of(
Collections.emptyMap(),
newTestMapBuilder().add(null, 1).map,
newTestMapBuilder().add(null, 1).add("asdf", 1).map,
newTestMapBuilder().add("", 1).map,
newTestMapBuilder().add("", 1).add("asdf", 1).map,
// Invalid map with duplicate keys:
toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))),
// Invalid map with null entry:
toMap(Arrays.asList(null, Pair.of("asdf", 1))));
}
@MethodSource("invalidPrefixes")
@ParameterizedTest
default void throws_illegal_arg_when_provided_invalid_values(
final Map<String, Integer> prefixes) {
final Class<? extends Exception> expectedExceptionType =
prefixes != null ? IllegalArgumentException.class : NullPointerException.class;
assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes));
}
ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes);
}
interface SuffixMappersTests {
@CsvSource(
value = {
"null,false,null",
",false,null",
"123456,false,null",
"~~~~~~,false,null",
"a,false,null",
"ab,false,null",
"abc,true,0",
"1abc,true,0",
"abe,true,1",
"abed,false,null",
"abd,false,null",
"aba,false,null",
"at,false,null",
"ate,true,2",
"cate,true,2",
"icate,true,2",
"dicate,true,2",
"bdicate,true,2",
"abdicate,true,3",
"i abdicate,true,3",
"abdicated,false,null",
"z,false,null",
"yz,false,null"
},
nullValues = "null")
@ParameterizedTest
@SuppressWarnings("unchecked")
default void detects_suffixes(
final String string, final boolean expectSuffixed, final Integer expectedValue) {
// Test even number of suffixes.
final Map<String, Integer> suffixes =
newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
| ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes); | 5 | 2023-11-12 05:05:22+00:00 | 4k |
slow3586/HypersomniaMapGen | src/main/java/com/slow3586/Main.java | [
{
"identifier": "RoomStyle",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}"
},
{
"identifier": "ExternalResource",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Builder\n@Value\npublic static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n}"
},
{
"identifier": "WHITE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "public static Color WHITE = new Color(255, 255, 255, 255);"
},
{
"identifier": "Layer",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\npublic static class Layer {\n String id;\n List<String> nodes;\n}"
},
{
"identifier": "Node",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\n@Builder\npublic static class Node {\n @Builder.Default\n String id = String.valueOf(Map.nodeIndex.getAndIncrement());\n String type;\n float[] pos;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n Float rotation = 0.0f;\n String faction;\n String letter;\n Float positional_vibration;\n Float intensity_vibration;\n Falloff falloff;\n int[] color;\n int num_particles;\n\n static final String FACTION_RESISTANCE = \"RESISTANCE\";\n static final String TYPE_BOMBSITE = \"bombsite\";\n static final String LETTER_A = \"A\";\n static final String TYPE_BUY_ZONE = \"buy_zone\";\n static final String FACTION_METROPOLIS = \"METROPOLIS\";\n static final String TYPE_TEAM_SPAWN = \"team_spawn\";\n static final String LETTER_B = \"B\";\n\n @Value\n public static class Falloff {\n float radius;\n int strength;\n }\n\n @Builder\n @Value\n public static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n }\n\n @Value\n @Builder\n public static class AsPhysical {\n // lombok \"'is' getter\" fix\n @JsonProperty(\"is_static\")\n @Getter(AccessLevel.NONE)\n boolean is_static;\n @JsonProperty(\"is_see_through\")\n @Getter(AccessLevel.NONE)\n boolean is_see_through;\n @JsonProperty(\"is_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_throw_through;\n @JsonProperty(\"is_melee_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_melee_throw_through;\n @JsonProperty(\"is_shoot_through\")\n @Getter(AccessLevel.NONE)\n boolean is_shoot_through;\n Float density; // 0.7\n Float friction; // 0.0\n Float bounciness; // 0.2\n Float penetrability; // 1\n Float collision_sound_sensitivity; // 1\n Float linear_damping; // 6.5\n Float angular_damping; // 6.5\n CustomShape custom_shape;\n\n static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();\n\n @Value\n public static class CustomShape {\n float[][] source_polygon;\n\n public CustomShape mul(float mul) {\n float[][] result = new float[4][2];\n for (int y = 0; y < 4; y++) {\n for (int x = 0; x < 2; x++) {\n result[y][x] = CRATE_SHAPE.source_polygon[y][x] * mul;\n }\n }\n return new CustomShape(result);\n }\n\n static final CustomShape CRATE_SHAPE = new CustomShape(\n new float[][]{\n new float[]{-32.0f, -32.0f},\n new float[]{32.0f, -32.0f},\n new float[]{32.0f, 32.0f},\n new float[]{-32.0f, 32.0f},\n });\n }\n }\n\n @Value\n public static class AsNonPhysical {\n boolean full_illumination;\n\n static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);\n }\n}"
},
{
"identifier": "AS_NON_PHYSICAL_DEFAULT",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);"
},
{
"identifier": "AS_PHYSICAL_DEFAULT",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();"
},
{
"identifier": "BASE_PNG_TEXTURE_FILENAME",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";"
},
{
"identifier": "CRATE_BLOCKING",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String CRATE_BLOCKING = \"crate_blocking\";"
},
{
"identifier": "CRATE_NON_BLOCKING",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";"
},
{
"identifier": "DOMAIN_FOREGROUND",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String DOMAIN_FOREGROUND = \"FOREGROUND\";"
},
{
"identifier": "DOMAIN_PHYSICAL",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String DOMAIN_PHYSICAL = \"PHYSICAL\";"
},
{
"identifier": "LINE_FLOOR",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String LINE_FLOOR = \"line_floor\";"
},
{
"identifier": "LINE_WALL",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String LINE_WALL = \"line_wall\";"
},
{
"identifier": "MAP_GFX_PATH",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String MAP_GFX_PATH = \"gfx/\";"
},
{
"identifier": "PNG_EXT",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String PNG_EXT = \".png\";"
},
{
"identifier": "RESOURCE_FLOOR_ID",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String RESOURCE_FLOOR_ID = \"style_floor\";"
},
{
"identifier": "RESOURCE_ID_PREFIX",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String RESOURCE_ID_PREFIX = \"@\";"
},
{
"identifier": "RESOURCE_WALL_ID",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String RESOURCE_WALL_ID = \"style_wall\";"
},
{
"identifier": "ROOM_NOISE_CIRCLE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";"
},
{
"identifier": "SHADOW_FLOOR_CORNER",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";"
},
{
"identifier": "SHADOW_FLOOR_LINE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";"
},
{
"identifier": "SHADOW_WALL_CORNER",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";"
},
{
"identifier": "SHADOW_WALL_LINE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "static final String SHADOW_WALL_LINE = \"shadow_wall_line\";"
},
{
"identifier": "Playtesting",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "@Value\npublic static class Playtesting {\n static final String QUICK_TEST = \"quick_test\";\n String mode;\n}"
},
{
"identifier": "CRATE_SIZE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "public static Size CRATE_SIZE = new Size(104, 104);"
},
{
"identifier": "TILE_SIZE",
"path": "src/main/java/com/slow3586/Main.java",
"snippet": "public static Size TILE_SIZE = new Size(128, 128);"
}
] | import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.slow3586.Main.Room.RoomStyle;
import com.slow3586.Main.Settings.Node.ExternalResource;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.ToString;
import lombok.Value;
import org.jooq.lambda.Sneaky;
import org.jooq.lambda.function.Consumer1;
import org.jooq.lambda.function.Consumer2;
import org.jooq.lambda.function.Consumer4;
import org.jooq.lambda.function.Function1;
import org.jooq.lambda.function.Function3;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.slow3586.Main.Color.WHITE;
import static com.slow3586.Main.MapTile.TileType.DOOR;
import static com.slow3586.Main.MapTile.TileType.WALL;
import static com.slow3586.Main.Settings.Layer;
import static com.slow3586.Main.Settings.Node;
import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT;
import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND;
import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR;
import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL;
import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH;
import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX;
import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID;
import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER;
import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE;
import static com.slow3586.Main.Settings.Playtesting;
import static com.slow3586.Main.Size.CRATE_SIZE;
import static com.slow3586.Main.Size.TILE_SIZE; | 3,441 | package com.slow3586;
public class Main {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static Random baseRandom;
static Configuration config;
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) throws IOException {
//region CONFIGURATION
final String configStr = Files.readString(Path.of("config.json"));
config = OBJECT_MAPPER.readValue(configStr, Configuration.class);
baseRandom = new Random(config.randomSeed);
final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName);
//endregion
//region GENERATION: ROOMS
//region RANDOMIZE DIAGONAL ROOM SIZES
final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize())
.limit(Math.max(config.roomsCount.x, config.roomsCount.y))
.toArray(Size[]::new);
//endregion
//region RANDOMIZE ROOM STYLES | package com.slow3586;
public class Main {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static Random baseRandom;
static Configuration config;
static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public static void main(String[] args) throws IOException {
//region CONFIGURATION
final String configStr = Files.readString(Path.of("config.json"));
config = OBJECT_MAPPER.readValue(configStr, Configuration.class);
baseRandom = new Random(config.randomSeed);
final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName);
//endregion
//region GENERATION: ROOMS
//region RANDOMIZE DIAGONAL ROOM SIZES
final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize())
.limit(Math.max(config.roomsCount.x, config.roomsCount.y))
.toArray(Size[]::new);
//endregion
//region RANDOMIZE ROOM STYLES | final RoomStyle[] styles = IntStream.range(0, config.styleCount) | 0 | 2023-11-18 14:36:04+00:00 | 4k |
intrepidLi/BUAA_Food | app/src/main/java/com/buaa/food/ui/activity/CameraActivity.java | [
{
"identifier": "BaseActivity",
"path": "library/base/src/main/java/com/hjq/base/BaseActivity.java",
"snippet": "public abstract class BaseActivity extends AppCompatActivity\n implements ActivityAction, ClickAction,\n HandlerAction, BundleAction, KeyboardAction {\n\n /** 错误结果码 */\n public static final int RESULT_ERROR = -2;\n\n /** Activity 回调集合 */\n private SparseArray<OnActivityCallback> mActivityCallbacks;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initActivity();\n }\n\n protected void initActivity() {\n initLayout();\n initView();\n initData();\n }\n\n /**\n * 获取布局 ID\n */\n protected abstract int getLayoutId();\n\n /**\n * 初始化控件\n */\n protected abstract void initView();\n\n /**\n * 初始化数据\n */\n protected abstract void initData();\n\n /**\n * 初始化布局\n */\n protected void initLayout() {\n if (getLayoutId() > 0) {\n setContentView(getLayoutId());\n initSoftKeyboard();\n }\n }\n\n /**\n * 初始化软键盘\n */\n protected void initSoftKeyboard() {\n // 点击外部隐藏软键盘,提升用户体验\n getContentView().setOnClickListener(v -> {\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n });\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n removeCallbacks();\n }\n\n @Override\n public void finish() {\n super.finish();\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n }\n\n /**\n * 如果当前的 Activity(singleTop 启动模式) 被复用时会回调\n */\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n // 设置为当前的 Intent,避免 Activity 被杀死后重启 Intent 还是最原先的那个\n setIntent(intent);\n }\n\n @Override\n public Bundle getBundle() {\n return getIntent().getExtras();\n }\n\n /**\n * 和 setContentView 对应的方法\n */\n public ViewGroup getContentView() {\n return findViewById(Window.ID_ANDROID_CONTENT);\n }\n\n @Override\n public Context getContext() {\n return this;\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n List<Fragment> fragments = getSupportFragmentManager().getFragments();\n for (Fragment fragment : fragments) {\n // 这个 Fragment 必须是 BaseFragment 的子类,并且处于可见状态\n if (!(fragment instanceof BaseFragment) ||\n fragment.getLifecycle().getCurrentState() != Lifecycle.State.RESUMED) {\n continue;\n }\n // 将按键事件派发给 Fragment 进行处理\n if (((BaseFragment<?>) fragment).dispatchKeyEvent(event)) {\n // 如果 Fragment 拦截了这个事件,那么就不交给 Activity 处理\n return true;\n }\n }\n return super.dispatchKeyEvent(event);\n }\n\n @SuppressWarnings(\"deprecation\")\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n // 查看源码得知 startActivity 最终也会调用 startActivityForResult\n super.startActivityForResult(intent, requestCode, options);\n }\n\n /**\n * startActivityForResult 方法优化\n */\n\n public void startActivityForResult(Class<? extends Activity> clazz, OnActivityCallback callback) {\n startActivityForResult(new Intent(this, clazz), null, callback);\n }\n\n public void startActivityForResult(Intent intent, OnActivityCallback callback) {\n startActivityForResult(intent, null, callback);\n }\n\n public void startActivityForResult(Intent intent, @Nullable Bundle options, OnActivityCallback callback) {\n if (mActivityCallbacks == null) {\n mActivityCallbacks = new SparseArray<>(1);\n }\n // 请求码必须在 2 的 16 次方以内\n int requestCode = new Random().nextInt((int) Math.pow(2, 16));\n mActivityCallbacks.put(requestCode, callback);\n startActivityForResult(intent, requestCode, options);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\n OnActivityCallback callback;\n if (mActivityCallbacks != null && (callback = mActivityCallbacks.get(requestCode)) != null) {\n callback.onActivityResult(resultCode, data);\n mActivityCallbacks.remove(requestCode);\n return;\n }\n super.onActivityResult(requestCode, resultCode, data);\n }\n\n public interface OnActivityCallback {\n\n /**\n * 结果回调\n *\n * @param resultCode 结果码\n * @param data 数据\n */\n void onActivityResult(int resultCode, @Nullable Intent data);\n }\n}"
},
{
"identifier": "AppActivity",
"path": "app/src/main/java/com/buaa/food/app/AppActivity.java",
"snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n /** 加载对话框 */\n private BaseDialog mDialog;\n /** 对话框数量 */\n private int mDialogCount;\n\n /**\n * 当前加载对话框是否在显示中\n */\n public boolean isShowDialog() {\n return mDialog != null && mDialog.isShowing();\n }\n\n /**\n * 显示加载对话框\n */\n public void showDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n mDialogCount++;\n postDelayed(() -> {\n if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialog == null) {\n mDialog = new WaitDialog.Builder(this)\n .setCancelable(false)\n .create();\n }\n if (!mDialog.isShowing()) {\n mDialog.show();\n }\n }, 300);\n }\n\n /**\n * 隐藏加载对话框\n */\n public void hideDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialogCount > 0) {\n mDialogCount--;\n }\n\n if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {\n return;\n }\n\n mDialog.dismiss();\n }\n\n @Override\n protected void initLayout() {\n super.initLayout();\n\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n // 初始化沉浸式状态栏\n if (isStatusBarEnabled()) {\n getStatusBarConfig().init();\n\n // 设置标题栏沉浸\n if (getTitleBar() != null) {\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n /**\n * 是否使用沉浸式状态栏\n */\n protected boolean isStatusBarEnabled() {\n return true;\n }\n\n /**\n * 状态栏字体深色模式\n */\n protected boolean isStatusBarDarkFont() {\n return true;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n public ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式状态栏\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(@StringRes int id) {\n setTitle(getString(id));\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (getTitleBar() != null) {\n getTitleBar().setTitle(title);\n }\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null) {\n mTitleBar = obtainTitleBar(getContentView());\n }\n return mTitleBar;\n }\n\n @Override\n public void onLeftClick(View view) {\n onBackPressed();\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n super.startActivityForResult(intent, requestCode, options);\n overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);\n }\n\n /**\n * {@link OnHttpListener}\n */\n\n @Override\n public void onStart(Call call) {\n showDialog();\n }\n\n @Override\n public void onSucceed(Object result) {\n if (result instanceof HttpData) {\n toast(((HttpData<?>) result).getMessage());\n }\n }\n\n @Override\n public void onFail(Exception e) {\n toast(e.getMessage());\n }\n\n @Override\n public void onEnd(Call call) {\n hideDialog();\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (isShowDialog()) {\n hideDialog();\n }\n mDialog = null;\n }\n}"
},
{
"identifier": "AppConfig",
"path": "app/src/main/java/com/buaa/food/other/AppConfig.java",
"snippet": "public final class AppConfig {\n\n /**\n * 当前是否为调试模式\n */\n public static boolean isDebug() {\n return BuildConfig.DEBUG;\n }\n\n /**\n * 获取当前构建的模式\n */\n public static String getBuildType() {\n return BuildConfig.BUILD_TYPE;\n }\n\n /**\n * 当前是否要开启日志打印功能\n */\n public static boolean isLogEnable() {\n return BuildConfig.LOG_ENABLE;\n }\n\n /**\n * 获取当前应用的包名\n */\n public static String getPackageName() {\n return BuildConfig.APPLICATION_ID;\n }\n\n /**\n * 获取当前应用的版本名\n */\n public static String getVersionName() {\n return BuildConfig.VERSION_NAME;\n }\n\n /**\n * 获取当前应用的版本码\n */\n public static int getVersionCode() {\n return BuildConfig.VERSION_CODE;\n }\n\n /**\n * 获取 Bugly Id\n */\n public static String getBuglyId() {\n return BuildConfig.BUGLY_ID;\n }\n\n /**\n * 获取服务器主机地址\n */\n public static String getHostUrl() {\n return BuildConfig.HOST_URL;\n }\n}"
}
] | import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;
import com.hjq.base.BaseActivity;
import com.buaa.food.R;
import com.buaa.food.aop.Log;
import com.buaa.food.aop.Permissions;
import com.buaa.food.app.AppActivity;
import com.buaa.food.other.AppConfig;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale; | 3,168 | package com.buaa.food.ui.activity;
public final class CameraActivity extends AppActivity {
public static final String INTENT_KEY_IN_FILE = "file";
public static final String INTENT_KEY_IN_VIDEO = "video";
public static final String INTENT_KEY_OUT_ERROR = "error";
| package com.buaa.food.ui.activity;
public final class CameraActivity extends AppActivity {
public static final String INTENT_KEY_IN_FILE = "file";
public static final String INTENT_KEY_IN_VIDEO = "video";
public static final String INTENT_KEY_OUT_ERROR = "error";
| public static void start(BaseActivity activity, OnCameraListener listener) { | 0 | 2023-11-14 10:04:26+00:00 | 4k |
WallasAR/GUITest | src/main/java/com/session/employee/medOrderController.java | [
{
"identifier": "Main",
"path": "src/main/java/com/example/guitest/Main.java",
"snippet": "public class Main extends Application {\n\n private static Stage stage; // Variavel estaticas para fazer a mudança de tela\n\n private static Scene mainScene, homeScene, funcScene, medScene, clientScene, recordScene, funcServiceScene, medOrderScene, funcClientScene; // variavel do tipo Scene\n\n @Override\n public void start(Stage primaryStage) throws Exception { // Metodo padrão do JavaFX\n stage = primaryStage; // inicializando a variavel stage\n\n primaryStage.setTitle(\"UmbrellaCorp. System\");\n stage.getIcons().add(new Image(\"icon.png\"));\n primaryStage.initStyle(StageStyle.UNDECORATED);\n\n Parent fxmlLogin = FXMLLoader.load(getClass().getResource(\"TelaLogin.fxml\"));\n mainScene = new Scene(fxmlLogin, 700, 500); // Cache tela 1\n\n Parent fxmlHome = FXMLLoader.load(getClass().getResource(\"homePage.fxml\"));\n homeScene = new Scene(fxmlHome, 1920, 1080); // Cache tela 2\n\n Parent fxmlFunc = FXMLLoader.load(getClass().getResource(\"funcPage.fxml\"));\n funcScene = new Scene(fxmlFunc, 1920, 1080); // Cache tela 3\n\n Parent fxmlMed = FXMLLoader.load(getClass().getResource(\"medPage.fxml\"));\n medScene = new Scene(fxmlMed, 1920, 1080); // Cache tela 4\n\n Parent fxmlClient = FXMLLoader.load(getClass().getResource(\"clientPage.fxml\"));\n clientScene = new Scene(fxmlClient, 1920, 1080); // Cache tela\n\n Parent fxmlRecord = FXMLLoader.load(getClass().getResource(\"RecordPage.fxml\"));\n recordScene = new Scene(fxmlRecord, 1920, 1080); // Cache tela\n\n Parent fxmlfuncService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/PurchasePage.fxml\"));\n funcServiceScene = new Scene(fxmlfuncService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncMedOrderService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/medicineOrderPage.fxml\"));\n medOrderScene = new Scene(fxmlfuncMedOrderService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncClientService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/employeeClientPage.fxml\"));\n funcClientScene = new Scene(fxmlfuncClientService, 1920, 1080);\n\n primaryStage.setScene(mainScene); // Definindo tela principal/inicial\n primaryStage.show(); // mostrando a cena\n Banco banco = new Banco();\n banco.registro();\n banco.carrinho();\n banco.tablecliete();\n banco.encomendas();\n }\n\n public static void changedScene(String scr){ // metodo que muda a tela\n switch (scr){\n case \"main\":\n stage.setScene(mainScene);\n stage.centerOnScreen();\n break;\n case \"home\":\n stage.setScene(homeScene);\n stage.centerOnScreen();\n break;\n case \"func\":\n stage.setScene(funcScene);\n stage.centerOnScreen();\n break;\n case \"med\":\n stage.setScene(medScene);\n stage.centerOnScreen();\n break;\n case \"client\":\n stage.setScene(clientScene);\n stage.centerOnScreen();\n break;\n case \"sale\":\n stage.setScene(funcServiceScene);\n stage.centerOnScreen();\n break;\n case \"medOrder\":\n stage.setScene(medOrderScene);\n stage.centerOnScreen();\n break;\n case \"ClientAdmFunc\":\n stage.setScene(funcClientScene);\n stage.centerOnScreen();\n break;\n case \"record\":\n stage.setScene(recordScene);\n stage.centerOnScreen();\n break;\n }\n }\n\n public static void main(String[] args) {\n launch();\n }\n}"
},
{
"identifier": "EncomendasTable",
"path": "src/main/java/com/table/view/EncomendasTable.java",
"snippet": "public class EncomendasTable {\n private int id;\n private String user;\n private String medicine;\n private int amount;\n private float price;\n private String date;\n private String phone;\n private String status;\n\n public EncomendasTable(int id, String user, String medicine, int amount, float price, String date, String phone, String status) {\n this.id = id;\n this.user = user;\n this.medicine = medicine;\n this.amount = amount;\n this.price = price;\n this.date = date;\n this.phone = phone;\n this.status = status;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getUser() {\n return user;\n }\n\n public void setUser(String user) {\n this.user = user;\n }\n\n public String getMedicine() {\n return medicine;\n }\n\n public void setMedicine(String medicine) {\n this.medicine = medicine;\n }\n\n public int getAmount() {\n return amount;\n }\n\n public void setAmount(int amount) {\n this.amount = amount;\n }\n\n public float getPrice() {\n return price;\n }\n\n public void setPrice(float price) {\n this.price = price;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n}"
},
{
"identifier": "AlertMsg",
"path": "src/main/java/com/warning/alert/AlertMsg.java",
"snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}"
},
{
"identifier": "connection",
"path": "src/main/java/com/db/bank/Banco.java",
"snippet": "public static Connection connection = conexao();"
}
] | import com.example.guitest.Main;
import com.table.view.EncomendasTable;
import com.warning.alert.AlertMsg;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import static com.db.bank.Banco.connection;
import javafx.scene.control.cell.PropertyValueFactory;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle; | 2,118 | package com.session.employee;
public class medOrderController implements Initializable {
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void SaleAction(MouseEvent e) {
Main.changedScene("sale");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
@FXML
private TableColumn tcDateOrder;
@FXML
private TableColumn tcIdOrder;
@FXML
private TableColumn tcMedOrder;
@FXML
private TableColumn tcPhoneOrder;
@FXML
private TableColumn tcPriceOrder;
@FXML
private TableColumn tcQuantOrder;
@FXML
private TableColumn tcStatusOrder;
@FXML
private TableColumn tcUserOrder;
@FXML
private TableView tvOrder;
@FXML
private TextField tfSearch;
@FXML
private TextField tfUpdateStatus;
@FXML
private TextField tfIdStatus;
public void tableOrder()throws SQLException{
List<EncomendasTable> order = new ArrayList<>();
String consultaSQLcliente = "SELECT * FROM encomendas"; | package com.session.employee;
public class medOrderController implements Initializable {
@FXML
protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
Main.changedScene("main");
}
}
@FXML
protected void SaleAction(MouseEvent e) {
Main.changedScene("sale");
}
@FXML
protected void ClientAction(MouseEvent e) {
Main.changedScene("ClientAdmFunc");
}
@FXML
private TableColumn tcDateOrder;
@FXML
private TableColumn tcIdOrder;
@FXML
private TableColumn tcMedOrder;
@FXML
private TableColumn tcPhoneOrder;
@FXML
private TableColumn tcPriceOrder;
@FXML
private TableColumn tcQuantOrder;
@FXML
private TableColumn tcStatusOrder;
@FXML
private TableColumn tcUserOrder;
@FXML
private TableView tvOrder;
@FXML
private TextField tfSearch;
@FXML
private TextField tfUpdateStatus;
@FXML
private TextField tfIdStatus;
public void tableOrder()throws SQLException{
List<EncomendasTable> order = new ArrayList<>();
String consultaSQLcliente = "SELECT * FROM encomendas"; | Statement statement = connection.createStatement(); | 3 | 2023-11-16 14:55:08+00:00 | 4k |
wzh933/Buffer-Manager | src/test/java/cs/adb/wzh/bufferManager/BMgrTest.java | [
{
"identifier": "Buffer",
"path": "src/main/java/cs/adb/wzh/Storage/Buffer.java",
"snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n }\n\n\n public Buffer() {\n final int DEF_BUF_SIZE = 1024;\n this.bufSize = DEF_BUF_SIZE;\n this.buf = new Frame[DEF_BUF_SIZE];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n /**\n * @param bufSize:用户自定义的缓存区大小\n */\n public Buffer(int bufSize) throws Exception {\n if (bufSize <= 0) {\n throw new Exception(\"缓存区大小不可以为非正数!\");\n }\n this.bufSize = bufSize;\n this.buf = new Frame[bufSize];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n public Frame readFrame(int frameId) {\n return buf[frameId];\n }\n\n public void writeFrame(Page page, int frameId) {\n //先不进行任何操作\n }\n\n}"
},
{
"identifier": "Disk",
"path": "src/main/java/cs/adb/wzh/Storage/Disk.java",
"snippet": "public class Disk {\n private final int diskSize;\n private final Page[] disk;\n\n public int getDiskSize() {\n return diskSize;\n }\n\n public Page[] getDisk() {\n return disk;\n }\n\n\n public Disk() {\n final int DEF_BUF_SIZE = 65536;//256MB的磁盘\n this.diskSize = DEF_BUF_SIZE;\n this.disk = new Page[DEF_BUF_SIZE];\n //初始化磁盘空间\n for (int pageId = 0; pageId < this.diskSize; pageId++) {\n this.disk[pageId] = new Page();\n }\n }\n\n\n}"
},
{
"identifier": "BCB",
"path": "src/main/java/cs/adb/wzh/bufferControlBlocks/BCB.java",
"snippet": "public class BCB {\n private int pageId;\n private final int frameId;\n private int latch;\n private int count;\n private int dirty = 0;\n private int referenced = 1;\n private BCB next;\n private BCB pre;\n\n /**\n * BCB块的id对应其在缓存区中的frameId\n *\n * @param frameId:缓存区页号\n */\n public BCB(int frameId) {\n this.frameId = frameId;\n }\n\n\n public void setPageId(int pageId) {\n this.pageId = pageId;\n }\n\n public void setNext(BCB next) {\n this.next = next;\n }\n\n public void setPre(BCB pre) {\n this.pre = pre;\n }\n\n public void setDirty(int dirty) {\n this.dirty = dirty;\n }\n\n public void setReferenced(int referenced) {\n this.referenced = referenced;\n }\n\n public BCB getNext() {\n return next;\n }\n\n\n public BCB getPre() {\n return pre;\n }\n\n public int getPageId() {\n return pageId;\n }\n\n public int getFrameId() {\n return frameId;\n }\n\n public int getDirty() {\n return dirty;\n }\n\n public int getReferenced() {\n return referenced;\n }\n}"
},
{
"identifier": "PageRequestReader",
"path": "src/main/java/cs/adb/wzh/utils/PageRequestReader.java",
"snippet": "public class PageRequestReader {\n private final ArrayList<Integer> operations = new ArrayList<>();//0读1写\n private final ArrayList<Integer> pageIds = new ArrayList<>();//页号列表\n\n public PageRequestReader(String filePath) throws IOException {\n File fin = new File(filePath);\n FileInputStream fis = new FileInputStream(fin);\n\n //Construct BufferedReader from InputStreamReader\n BufferedReader br = new BufferedReader(new InputStreamReader(fis));\n\n String line;\n while ((line = br.readLine()) != null) {\n String[] str = line.split(\",\");\n operations.add(Integer.valueOf(str[0]));\n pageIds.add(Integer.valueOf(str[1]));\n }\n\n br.close();\n fis.close();\n\n }\n\n public int getOperation(int requestId) {\n return operations.get(requestId);\n }\n\n public int getPageId(int requestId) {\n return pageIds.get(requestId);\n }\n\n public int getRequestNum() {\n return pageIds.size();\n }\n}"
},
{
"identifier": "SwapMethod",
"path": "src/main/java/cs/adb/wzh/utils/SwapMethod.java",
"snippet": "public enum SwapMethod {\n LRU, CLOCK;\n}"
}
] | import cs.adb.wzh.Storage.Buffer;
import cs.adb.wzh.Storage.Disk;
import cs.adb.wzh.bufferControlBlocks.BCB;
import cs.adb.wzh.utils.PageRequestReader;
import cs.adb.wzh.utils.SwapMethod;
import org.junit.jupiter.api.Test; | 1,930 | package cs.adb.wzh.bufferManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
class BMgrTest {
@Test
void bMgrTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) {
System.out.println(p.getFrameId());
}
System.out.println();
for (BCB p = bMgr.getTail().getPre(); p.getFrameId() != -1; p = p.getPre()) {
System.out.println(p.getFrameId());
}
// System.out.println(bMgr.getTail().getFrameId());
}
@Test
void bcbTableTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
BCB[] bcbTable = bMgr.getBcbTable();
for (BCB bcb : bcbTable) {
System.out.println(bcb.getFrameId());
}
System.out.println();
for (BCB bcb : bcbTable) {
System.out.println(bcb.getNext().getFrameId());
}
}
@Test
void bcbMove2HeadTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
BCB[] bcbTable = bMgr.getBcbTable();
bMgr.move2Head(bMgr.getTail().getPre());
for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) {
System.out.println(p.getFrameId());
}
}
@Test
void fixPageTest() throws Exception {
Buffer bf = new Buffer();
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
bMgr.setSwapMethod(SwapMethod.CLOCK);
// bMgr.setSwapMethod(SwapMethod.LRU);
/*
//这样就会有”当前磁盘已满,无法分配新页面!“的警告
for (int i = 0; i < 65537; i++) {
System.out.println(bMgr.fixNewPage());
}
bMgr.fixNewPage();
bMgr.fixPage(10);
*/
int fileLength = 50000;
int[] pageIds = new int[fileLength];
for (int i = 0; i < fileLength; i++) {
pageIds[i] = bMgr.fixNewPage();
}
// PageRequestReader prr = new PageRequestReader("src/main/resources/testTxt1.txt"); | package cs.adb.wzh.bufferManager;
/**
* @author Wang Zihui
* @date 2023/11/12
**/
class BMgrTest {
@Test
void bMgrTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) {
System.out.println(p.getFrameId());
}
System.out.println();
for (BCB p = bMgr.getTail().getPre(); p.getFrameId() != -1; p = p.getPre()) {
System.out.println(p.getFrameId());
}
// System.out.println(bMgr.getTail().getFrameId());
}
@Test
void bcbTableTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
BCB[] bcbTable = bMgr.getBcbTable();
for (BCB bcb : bcbTable) {
System.out.println(bcb.getFrameId());
}
System.out.println();
for (BCB bcb : bcbTable) {
System.out.println(bcb.getNext().getFrameId());
}
}
@Test
void bcbMove2HeadTest() throws Exception {
Buffer bf = new Buffer(8);
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
BCB[] bcbTable = bMgr.getBcbTable();
bMgr.move2Head(bMgr.getTail().getPre());
for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) {
System.out.println(p.getFrameId());
}
}
@Test
void fixPageTest() throws Exception {
Buffer bf = new Buffer();
Disk disk = new Disk();
BMgr bMgr = new BMgr(bf, disk);
bMgr.setSwapMethod(SwapMethod.CLOCK);
// bMgr.setSwapMethod(SwapMethod.LRU);
/*
//这样就会有”当前磁盘已满,无法分配新页面!“的警告
for (int i = 0; i < 65537; i++) {
System.out.println(bMgr.fixNewPage());
}
bMgr.fixNewPage();
bMgr.fixPage(10);
*/
int fileLength = 50000;
int[] pageIds = new int[fileLength];
for (int i = 0; i < fileLength; i++) {
pageIds[i] = bMgr.fixNewPage();
}
// PageRequestReader prr = new PageRequestReader("src/main/resources/testTxt1.txt"); | PageRequestReader prr = new PageRequestReader("src/main/resources/data-5w-50w-zipf.txt"); | 3 | 2023-11-15 16:30:06+00:00 | 4k |
UselessBullets/DragonFly | src/main/java/useless/dragonfly/utilities/Utilities.java | [
{
"identifier": "DragonFly",
"path": "src/main/java/useless/dragonfly/DragonFly.java",
"snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static final Gson GSON = new GsonBuilder().registerTypeAdapter(Animation.class, new AnimationDeserializer()).create();\n\tpublic static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST};\n\tpublic static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES;\n\tpublic static String version;\n\tpublic static boolean isDev;\n\tpublic static String renderState = \"gui\";\n\tstatic {\n\t\tversion = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString();\n\t\tisDev = version.equals(\"${version}\") || version.contains(\"dev\");\n\t}\n\t@Override\n\tpublic void beforeGameStart() {\n\t\tif (isDev){\n\t\t\tLOGGER.info(\"DragonFly \" + version + \" loading debug assets\");\n\t\t\tDebugMain.init();\n\t\t}\n\t\tLOGGER.info(\"DragonFly initialized.\");\n\t}\n\n\t@Override\n\tpublic void afterGameStart() {\n\n\t}\n}"
},
{
"identifier": "Vector3f",
"path": "src/main/java/useless/dragonfly/utilities/vector/Vector3f.java",
"snippet": "public class Vector3f extends Vector implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic float x, y, z;\n\n\t/**\n\t * Constructor for Vector3f.\n\t */\n\tpublic Vector3f() {\n\t\tsuper();\n\t}\n\n\t/**\n\t * Constructor\n\t */\n\tpublic Vector3f(ReadableVector3f src) {\n\t\tset(src);\n\t}\n\n\t/**\n\t * Constructor\n\t */\n\tpublic Vector3f(float x, float y, float z) {\n\t\tset(x, y, z);\n\t}\n\n\t/* (non-Javadoc)\n\t * @see WritableVector2f#set(float, float)\n\t */\n\tpublic void set(float x, float y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see WritableVector3f#set(float, float, float)\n\t */\n\tpublic void set(float x, float y, float z) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n\t/**\n\t * Load from another Vector3f\n\t * @param src The source vector\n\t * @return this\n\t */\n\tpublic Vector3f set(ReadableVector3f src) {\n\t\tx = src.getX();\n\t\ty = src.getY();\n\t\tz = src.getZ();\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return the length squared of the vector\n\t */\n\tpublic float lengthSquared() {\n\t\treturn x * x + y * y + z * z;\n\t}\n\n\t/**\n\t * Translate a vector\n\t * @param x The translation in x\n\t * @param y the translation in y\n\t * @return this\n\t */\n\tpublic Vector3f translate(float x, float y, float z) {\n\t\tthis.x += x;\n\t\tthis.y += y;\n\t\tthis.z += z;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Add a vector to another vector and place the result in a destination\n\t * vector.\n\t * @param left The LHS vector\n\t * @param right The RHS vector\n\t * @param dest The destination vector, or null if a new vector is to be created\n\t * @return the sum of left and right in dest\n\t */\n\tpublic static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) {\n\t\tif (dest == null)\n\t\t\treturn new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z);\n\t\telse {\n\t\t\tdest.set(left.x + right.x, left.y + right.y, left.z + right.z);\n\t\t\treturn dest;\n\t\t}\n\t}\n\n\t/**\n\t * Subtract a vector from another vector and place the result in a destination\n\t * vector.\n\t * @param left The LHS vector\n\t * @param right The RHS vector\n\t * @param dest The destination vector, or null if a new vector is to be created\n\t * @return left minus right in dest\n\t */\n\tpublic static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) {\n\t\tif (dest == null)\n\t\t\treturn new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z);\n\t\telse {\n\t\t\tdest.set(left.x - right.x, left.y - right.y, left.z - right.z);\n\t\t\treturn dest;\n\t\t}\n\t}\n\n\t/**\n\t * The cross product of two vectors.\n\t *\n\t * @param left The LHS vector\n\t * @param right The RHS vector\n\t * @param dest The destination result, or null if a new vector is to be created\n\t * @return left cross right\n\t */\n\tpublic static Vector3f cross(\n\t\tVector3f left,\n\t\tVector3f right,\n\t\tVector3f dest)\n\t{\n\n\t\tif (dest == null)\n\t\t\tdest = new Vector3f();\n\n\t\tdest.set(\n\t\t\tleft.y * right.z - left.z * right.y,\n\t\t\tright.x * left.z - right.z * left.x,\n\t\t\tleft.x * right.y - left.y * right.x\n\t\t);\n\n\t\treturn dest;\n\t}\n\n\n\n\t/**\n\t * Negate a vector\n\t * @return this\n\t */\n\tpublic Vector negate() {\n\t\tx = -x;\n\t\ty = -y;\n\t\tz = -z;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Negate a vector and place the result in a destination vector.\n\t * @param dest The destination vector or null if a new vector is to be created\n\t * @return the negated vector\n\t */\n\tpublic Vector3f negate(Vector3f dest) {\n\t\tif (dest == null)\n\t\t\tdest = new Vector3f();\n\t\tdest.x = -x;\n\t\tdest.y = -y;\n\t\tdest.z = -z;\n\t\treturn dest;\n\t}\n\n\n\t/**\n\t * Normalise this vector and place the result in another vector.\n\t * @param dest The destination vector, or null if a new vector is to be created\n\t * @return the normalised vector\n\t */\n\tpublic Vector3f normalise(Vector3f dest) {\n\t\tfloat l = length();\n\n\t\tif (dest == null)\n\t\t\tdest = new Vector3f(x / l, y / l, z / l);\n\t\telse\n\t\t\tdest.set(x / l, y / l, z / l);\n\n\t\treturn dest;\n\t}\n\n\t/**\n\t * The dot product of two vectors is calculated as\n\t * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z\n\t * @param left The LHS vector\n\t * @param right The RHS vector\n\t * @return left dot right\n\t */\n\tpublic static float dot(Vector3f left, Vector3f right) {\n\t\treturn left.x * right.x + left.y * right.y + left.z * right.z;\n\t}\n\n\t/**\n\t * Calculate the angle between two vectors, in radians\n\t * @param a A vector\n\t * @param b The other vector\n\t * @return the angle between the two vectors, in radians\n\t */\n\tpublic static float angle(Vector3f a, Vector3f b) {\n\t\tfloat dls = dot(a, b) / (a.length() * b.length());\n\t\tif (dls < -1f)\n\t\t\tdls = -1f;\n\t\telse if (dls > 1.0f)\n\t\t\tdls = 1.0f;\n\t\treturn (float)Math.acos(dls);\n\t}\n\n\t/* (non-Javadoc)\n\t * @see org.lwjgl.vector.Vector#load(FloatBuffer)\n\t */\n\tpublic Vector load(FloatBuffer buf) {\n\t\tx = buf.get();\n\t\ty = buf.get();\n\t\tz = buf.get();\n\t\treturn this;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see org.lwjgl.vector.Vector#scale(float)\n\t */\n\tpublic Vector scale(float scale) {\n\n\t\tx *= scale;\n\t\ty *= scale;\n\t\tz *= scale;\n\n\t\treturn this;\n\n\t}\n\n\t/* (non-Javadoc)\n\t * @see org.lwjgl.vector.Vector#store(FloatBuffer)\n\t */\n\tpublic Vector store(FloatBuffer buf) {\n\n\t\tbuf.put(x);\n\t\tbuf.put(y);\n\t\tbuf.put(z);\n\n\t\treturn this;\n\t}\n\n\t/* (non-Javadoc)\n\t * @see java.lang.Object#toString()\n\t */\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder(64);\n\n\t\tsb.append(\"Vector3f[\");\n\t\tsb.append(x);\n\t\tsb.append(\", \");\n\t\tsb.append(y);\n\t\tsb.append(\", \");\n\t\tsb.append(z);\n\t\tsb.append(']');\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * @return x\n\t */\n\tpublic final float getX() {\n\t\treturn x;\n\t}\n\n\t/**\n\t * @return y\n\t */\n\tpublic final float getY() {\n\t\treturn y;\n\t}\n\n\t/**\n\t * Set X\n\t * @param x\n\t */\n\tpublic final void setX(float x) {\n\t\tthis.x = x;\n\t}\n\n\t/**\n\t * Set Y\n\t * @param y\n\t */\n\tpublic final void setY(float y) {\n\t\tthis.y = y;\n\t}\n\n\t/**\n\t * Set Z\n\t * @param z\n\t */\n\tpublic void setZ(float z) {\n\t\tthis.z = z;\n\t}\n\n\t/* (Overrides)\n\t * @see org.lwjgl.vector.ReadableVector3f#getZ()\n\t */\n\tpublic float getZ() {\n\t\treturn z;\n\t}\n\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) return true;\n\t\tif (obj == null) return false;\n\t\tif (getClass() != obj.getClass()) return false;\n\t\tVector3f other = (Vector3f)obj;\n\n\t\tif (x == other.x && y == other.y && z == other.z) return true;\n\n\t\treturn false;\n\t}\n\n\t// =================================================================\n\t// Below this line is additional methods made for DragonFly\n\t// =================================================================\n\tpublic static Vector3f origin = new Vector3f(0.5f, 0.5f, 0.5f);\n\tpublic Vector3f rotateAroundX(Vector3f origin, float angle){\n\t\tif (angle == 0) return this;\n\t\tangle = (float) ((angle) * (Math.PI/180)); // Convert to radians\n\t\tfloat y = getY();\n\t\tfloat z = getZ();\n\t\tz -= origin.getZ();\n\t\ty -= origin.getY();\n\n\t\tfloat newZ = (float) (z * Math.cos(angle) - y * Math.sin(angle));\n\t\tfloat newY = (float) (z * Math.sin(angle) + y * Math.cos(angle));\n\n\t\tz = newZ + origin.getZ();\n\t\ty = newY + origin.getY();\n\t\treturn new Vector3f(getX(), y, z);\n\t}\n\n\tpublic Vector3f rotateAroundY(Vector3f origin, float angle){\n\t\tif (angle == 0) return this;\n\t\tangle = (float) ((angle) * (Math.PI/180)); // Convert to radians\n\t\tfloat x = getX();\n\t\tfloat z = getZ();\n\t\tz -= origin.getZ();\n\t\tx -= origin.getX();\n\n\t\tfloat newZ = (float) (z * Math.cos(angle) - x * Math.sin(angle));\n\t\tfloat newX = (float) (z * Math.sin(angle) + x * Math.cos(angle));\n\n\t\tz = newZ + origin.getZ();\n\t\tx = newX + origin.getX();\n\t\treturn new Vector3f(x, getY(), z);\n\t}\n\tpublic Vector3f rotateAroundZ(Vector3f origin, float angle){\n\t\tif (angle == 0) return this;\n\t\tangle = (float) ((angle) * (Math.PI/180)); // Convert to radians\n\t\tfloat x = getX();\n\t\tfloat y = getY();\n\t\ty -= origin.getY();\n\t\tx -= origin.getX();\n\n\t\tfloat newZ = (float) (y * Math.cos(angle) - x * Math.sin(angle));\n\t\tfloat newY = (float) (y * Math.sin(angle) + x * Math.cos(angle));\n\n\t\ty = newZ + origin.getY();\n\t\tx = newY + origin.getX();\n\t\treturn new Vector3f(x, y, getZ());\n\t}\n\n}"
}
] | import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.Minecraft;
import net.minecraft.core.Global;
import net.minecraft.core.data.DataLoader;
import useless.dragonfly.DragonFly;
import useless.dragonfly.utilities.vector.Vector3f;
import java.io.InputStream;
import java.lang.reflect.Field; | 3,502 | package useless.dragonfly.utilities;
public class Utilities {
public static final float COMPARE_CONST = 0.001f;
public static String writeFields(Class<?> clazz){
Field[] fields = clazz.getFields();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
builder.append(field.getName()).append(": ").append(field.getClass().cast(field));
if (i < fields.length-1){
builder.append("\n");
}
}
return builder.toString();
}
public static String tabBlock(String string, int tabAmount){
StringBuilder builder = new StringBuilder();
for (String line: string.split("\n")) {
builder.append(tabString(tabAmount)).append(line).append("\n");
}
return builder.toString();
}
public static String tabString(int tabAmount){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tabAmount; i++) {
builder.append("\t");
}
return builder.toString();
}
public static boolean equalFloats(float a, float b){
return Math.abs(Float.compare(a, b)) < COMPARE_CONST;
} | package useless.dragonfly.utilities;
public class Utilities {
public static final float COMPARE_CONST = 0.001f;
public static String writeFields(Class<?> clazz){
Field[] fields = clazz.getFields();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
builder.append(field.getName()).append(": ").append(field.getClass().cast(field));
if (i < fields.length-1){
builder.append("\n");
}
}
return builder.toString();
}
public static String tabBlock(String string, int tabAmount){
StringBuilder builder = new StringBuilder();
for (String line: string.split("\n")) {
builder.append(tabString(tabAmount)).append(line).append("\n");
}
return builder.toString();
}
public static String tabString(int tabAmount){
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tabAmount; i++) {
builder.append("\t");
}
return builder.toString();
}
public static boolean equalFloats(float a, float b){
return Math.abs(Float.compare(a, b)) < COMPARE_CONST;
} | public static Vector3f rotatePoint(Vector3f point, Vector3f origin, String axis, float angle){ | 1 | 2023-11-16 01:10:52+00:00 | 4k |
AntonyCheng/ai-bi | src/main/java/top/sharehome/springbootinittemplate/config/oss/minio/MinioConfiguration.java | [
{
"identifier": "Constants",
"path": "src/main/java/top/sharehome/springbootinittemplate/common/base/Constants.java",
"snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n * www主域\n */\n String WWW = \"www.\";\n\n /**\n * http请求\n */\n String HTTP = \"http://\";\n\n /**\n * https请求\n */\n String HTTPS = \"https://\";\n\n /**\n * 成功标记\n */\n Integer SUCCESS = HttpStatus.SUCCESS;\n\n /**\n * 失败标记\n */\n Integer FAIL = HttpStatus.ERROR;\n\n /**\n * 登录成功状态\n */\n String LOGIN_SUCCESS_STATUS = \"0\";\n\n /**\n * 登录失败状态\n */\n String LOGIN_FAIL_STATUS = \"1\";\n\n /**\n * 登录成功\n */\n String LOGIN_SUCCESS = \"LoginSuccess\";\n\n /**\n * 注销\n */\n String LOGOUT = \"Logout\";\n\n /**\n * 注册\n */\n String REGISTER = \"Register\";\n\n /**\n * 登录失败\n */\n String LOGIN_FAIL = \"LoginFail\";\n\n /**\n * 验证码有效期(分钟)\n */\n long CAPTCHA_EXPIRATION = 2;\n\n /**\n * 存放在缓存中的用户键\n */\n String LOGIN_USER_KEY = \"loginUser\";\n\n /**\n * 用户角色admin\n */\n String USER_ROLE_ADMIN = \"admin\";\n\n /**\n * 用户角色user\n */\n String USER_ROLE_USER = \"user\";\n\n /**\n * 只包含数字和英文的正则表达式\n */\n String REGEX_NUMBER_AND_LETTER = \"^[0-9a-zA-Z]+$\";\n\n /**\n * 邮箱的正则表达式\n */\n String REGEX_MAIL = \"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\\\.[a-zA-Z0-9_-]+)+$\";\n\n /**\n * 未知文件类型后缀\n */\n String UNKNOWN_FILE_TYPE_SUFFIX = \"unknown\";\n\n /**\n * 未知文件ContentType\n */\n String UNKNOWN_FILE_CONTENT_TYPE = \"application/octet-stream\";\n\n}"
},
{
"identifier": "ReturnCode",
"path": "src/main/java/top/sharehome/springbootinittemplate/common/base/ReturnCode.java",
"snippet": "@Getter\npublic enum ReturnCode {\n\n /**\n * 操作成功 200\n */\n SUCCESS(HttpStatus.SUCCESS, \"操作成功\"),\n\n /**\n * 操作失败 500\n */\n FAIL(HttpStatus.ERROR, \"操作失败\"),\n\n /**\n * 系统警告 600\n */\n WARN(HttpStatus.WARN, \"系统警告\"),\n\n /**\n * 账户名称校验失败 11000\n */\n USERNAME_VALIDATION_FAILED(11000, \"账户名称校验失败\"),\n\n /**\n * 账户名称已经存在 11001\n */\n USERNAME_ALREADY_EXISTS(11001, \"账户名称已经存在\"),\n\n /**\n * 账户名称包含特殊字符 11002\n */\n PASSWORD_AND_SECONDARY_PASSWORD_NOT_SAME(11002, \"密码和二次密码不相同\"),\n\n /**\n * 密码校验失败 11003\n */\n PASSWORD_VERIFICATION_FAILED(11003, \"密码校验失败\"),\n\n /**\n * 用户基本信息校验失败 11004\n */\n USER_BASIC_INFORMATION_VERIFICATION_FAILED(11004, \"用户基本信息校验失败\"),\n\n /**\n * 用户账户不存在 11005\n */\n USER_ACCOUNT_DOES_NOT_EXIST(11005, \"用户账户不存在\"),\n\n /**\n * 用户账户被封禁 11006\n */\n USER_ACCOUNT_BANNED(11006, \"用户账户被封禁\"),\n\n /**\n * 用户账号或密码错误 11007\n */\n WRONG_USER_ACCOUNT_OR_PASSWORD(11007, \"用户账号或密码错误\"),\n\n /**\n * 用户登录已过期 11008\n */\n USER_LOGIN_HAS_EXPIRED(11008, \"用户登录已过期\"),\n\n /**\n * 用户操作异常 11009\n */\n ABNORMAL_USER_OPERATION(11009, \"用户操作异常\"),\n\n /**\n * 用户设备异常 11010\n */\n ABNORMAL_USER_EQUIPMENT(11010, \"用户设备异常\"),\n\n /**\n * 用户登录验证码为空 11011\n */\n CAPTCHA_IS_EMPTY(11011, \"验证码为空\"),\n\n /**\n * 用户登录验证码已过期 11012\n */\n CAPTCHA_HAS_EXPIRED(11012, \"验证码已过期\"),\n\n /**\n * 用户登录验证码无效 11013\n */\n CAPTCHA_IS_INVALID(11013, \"验证码无效\"),\n\n /**\n * 用户登录验证码无效 11014\n */\n CAPTCHA_IS_INCORRECT(11014, \"验证码错误\"),\n\n /**\n * 用户发出无效请求 11015\n */\n USER_SENT_INVALID_REQUEST(11015, \"用户发出无效请求\"),\n\n /**\n * 手机格式校验失败 12000\n */\n PHONE_FORMAT_VERIFICATION_FAILED(12000, \"手机格式校验失败\"),\n\n /**\n * 邮箱格式校验失败 12001\n */\n EMAIL_FORMAT_VERIFICATION_FAILED(12001, \"邮箱格式校验失败\"),\n\n /**\n * 访问未授权 13000\n */\n ACCESS_UNAUTHORIZED(13000, \"访问未授权\"),\n\n /**\n * 请求必填参数为空 13001\n */\n REQUEST_REQUIRED_PARAMETER_IS_EMPTY(13001, \"请求必填参数为空\"),\n\n /**\n * 参数格式不匹配 13002\n */\n PARAMETER_FORMAT_MISMATCH(13002, \"参数格式不匹配\"),\n\n /**\n * 用户请求次数太多 13003\n */\n TOO_MANY_REQUESTS(13003, \"用户请求次数太多\"),\n\n /**\n * 用户上传文件异常 14000\n */\n FILE_UPLOAD_EXCEPTION(14000, \"用户上传文件异常\"),\n\n /**\n * 用户没有上传文件 14001\n */\n USER_DO_NOT_UPLOAD_FILE(14001, \"用户没有上传文件\"),\n\n /**\n * 用户上传文件类型不匹配 14002\n */\n USER_UPLOADED_FILE_TYPE_MISMATCH(14002, \"用户上传文件类型不匹配\"),\n\n /**\n * 用户上传文件太大 14003\n */\n USER_UPLOADED_FILE_IS_TOO_LARGE(14003, \"用户上传文件太大\"),\n\n /**\n * 用户上传图片太大 14004\n */\n USER_UPLOADED_IMAGE_IS_TOO_LARGE(14004, \"用户上传图片太大\"),\n\n /**\n * 用户上传视频太大 14005\n */\n USER_UPLOADED_VIDEO_IS_TOO_LARGE(14005, \"用户上传视频太大\"),\n\n /**\n * 用户上传压缩文件太大 14006\n */\n USER_UPLOADED_ZIP_IS_TOO_LARGE(14006, \"用户上传压缩文件太大\"),\n\n /**\n * 用户文件地址异常 14007\n */\n USER_FILE_ADDRESS_IS_ABNORMAL(14007, \"用户文件地址异常\"),\n\n /**\n * 用户文件删除异常 14008\n */\n USER_FILE_DELETION_IS_ABNORMAL(14008, \"用户文件删除异常\"),\n\n /**\n * 系统文件地址异常 14009\n */\n SYSTEM_FILE_ADDRESS_IS_ABNORMAL(14007, \"系统文件地址异常\"),\n\n /**\n * 邮件发送异常 15000\n */\n EMAIL_WAS_SENT_ABNORMALLY(15000, \"邮件发送异常\"),\n\n /**\n * 数据库服务出错 20000\n */\n ERRORS_OCCURRED_IN_THE_DATABASE_SERVICE(20000, \"数据库服务出错\"),\n\n /**\n * 消息中间件服务出错 30000\n */\n MQ_SERVICE_ERROR(30000, \"消息中间件服务出错\"),\n\n /**\n * 内存数据库服务出错 30001\n */\n MAIN_MEMORY_DATABASE_SERVICE_ERROR(30001, \"内存数据库服务出错\"),\n\n /**\n * 搜索引擎服务出错 30002\n */\n SEARCH_ENGINE_SERVICE_ERROR(30002, \"搜索引擎服务出错\"),\n\n /**\n * 网关服务出错 30003\n */\n GATEWAY_SERVICE_ERROR(30003, \"网关服务出错\"),\n\n /**\n * 分布式锁服务出错 30004\n */\n LOCK_SERVICE_ERROR(30004, \"分布式锁服务出错\"),\n\n /**\n * 分布式锁设计出错 30005\n */\n LOCK_DESIGN_ERROR(30005, \"分布式锁设计出错\");\n\n final private int code;\n\n final private String msg;\n\n ReturnCode(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}"
},
{
"identifier": "OssMinioCondition",
"path": "src/main/java/top/sharehome/springbootinittemplate/config/oss/minio/condition/OssMinioCondition.java",
"snippet": "public class OssMinioCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {\n String property = context.getEnvironment().getProperty(\"oss.minio.enable\");\n return StringUtils.equals(\"true\", property);\n }\n\n}"
},
{
"identifier": "MinioProperties",
"path": "src/main/java/top/sharehome/springbootinittemplate/config/oss/minio/properties/MinioProperties.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"oss.minio\")\npublic class MinioProperties {\n\n /**\n * 是否开启\n */\n private Boolean enable = false;\n\n /**\n * 域名(一定是协议前缀+ip+port)\n */\n private String endpoint;\n\n /**\n * 是否开启TLS\n */\n private Boolean enableTls = false;\n\n /**\n * 用户的 SecretId\n */\n private String secretId;\n\n /**\n * 用户的 SecretKey\n */\n private String secretKey;\n\n /**\n * 桶名称\n */\n private String bucketName;\n\n}"
},
{
"identifier": "CustomizeFileException",
"path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeFileException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeFileException extends RuntimeException {\n\n private ReturnCode returnCode;\n\n private String msg;\n\n public <T> CustomizeFileException() {\n this.returnCode = ReturnCode.FAIL;\n this.msg = ReturnCode.FAIL.getMsg();\n }\n\n public <T> CustomizeFileException(ReturnCode returnCode) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg();\n }\n\n public <T> CustomizeFileException(ReturnCode returnCode, String msg) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg() + \" ==> [\" + msg + \"]\";\n }\n\n @Override\n public String getMessage() {\n return this.msg;\n }\n\n}"
},
{
"identifier": "CustomizeReturnException",
"path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeReturnException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeReturnException extends RuntimeException {\n\n private ReturnCode returnCode;\n\n private String msg;\n\n public <T> CustomizeReturnException() {\n this.returnCode = ReturnCode.FAIL;\n this.msg = ReturnCode.FAIL.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg();\n }\n\n public <T> CustomizeReturnException(ReturnCode returnCode, String msg) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg() + \" ==> [\" + msg + \"]\";\n }\n\n @Override\n public String getMessage() {\n return this.msg;\n }\n\n}"
}
] | import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import top.sharehome.springbootinittemplate.common.base.Constants;
import top.sharehome.springbootinittemplate.common.base.ReturnCode;
import top.sharehome.springbootinittemplate.config.oss.minio.condition.OssMinioCondition;
import top.sharehome.springbootinittemplate.config.oss.minio.properties.MinioProperties;
import top.sharehome.springbootinittemplate.exception.customize.CustomizeFileException;
import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException;
import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID; | 3,559 | package top.sharehome.springbootinittemplate.config.oss.minio;
/**
* MinIO配置
*
* @author AntonyCheng
*/
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@AllArgsConstructor
@Slf4j
@Conditional(OssMinioCondition.class)
public class MinioConfiguration {
private final MinioProperties minioProperties;
/**
* 上传文件到MinIO
*
* @param file 待上传的文件
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public String uploadToMinio(MultipartFile file, String rootPath) {
MinioClient minioClient = getMinioClient();
String key;
try {
if (file == null) { | package top.sharehome.springbootinittemplate.config.oss.minio;
/**
* MinIO配置
*
* @author AntonyCheng
*/
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@AllArgsConstructor
@Slf4j
@Conditional(OssMinioCondition.class)
public class MinioConfiguration {
private final MinioProperties minioProperties;
/**
* 上传文件到MinIO
*
* @param file 待上传的文件
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public String uploadToMinio(MultipartFile file, String rootPath) {
MinioClient minioClient = getMinioClient();
String key;
try {
if (file == null) { | throw new CustomizeFileException(ReturnCode.USER_DO_NOT_UPLOAD_FILE); | 4 | 2023-11-12 07:49:59+00:00 | 4k |
rmheuer/azalea | azalea-core/src/main/java/com/github/rmheuer/azalea/render/Window.java | [
{
"identifier": "EventBus",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/event/EventBus.java",
"snippet": "public final class EventBus {\n private static final class HandlerFn implements Comparable<HandlerFn> {\n private final Listener listener;\n private final Method method;\n private final EventPriority priority;\n\n public HandlerFn(Listener listener, Method method, EventPriority priority) {\n this.listener = listener;\n this.method = method;\n this.priority = priority;\n }\n\n public void invoke(Event event) {\n try {\n method.invoke(listener, event);\n } catch (ReflectiveOperationException e) {\n System.err.println(\"Failed to invoke event handler \" + method);\n e.printStackTrace();\n }\n }\n\n @Override\n public int compareTo(HandlerFn o) {\n // Comparison intentionally backwards, this makes higher priority\n // handlers happen earlier\n return Integer.compare(o.priority.getLevel(), this.priority.getLevel());\n }\n\n @Override\n public String toString() {\n return method.getDeclaringClass().getSimpleName() + \"#\" + method.getName();\n }\n }\n\n private static final class HandlerSet {\n private final List<HandlerFn> handlers;\n\n public HandlerSet() {\n handlers = new ArrayList<>();\n }\n\n public void add(HandlerFn handler) {\n handlers.add(handler);\n }\n\n public List<HandlerFn> getHandlers() {\n return handlers;\n }\n }\n\n private final Map<Class<? extends Event>, HandlerSet> handlerSets;\n\n public EventBus() {\n handlerSets = new HashMap<>();\n }\n\n private void dispatch(Class<?> type, Event event) {\n // Collect handlers for event and all supertypes of event\n List<HandlerFn> handlers = new ArrayList<>();\n while (Event.class.isAssignableFrom(type)) {\n // Put them at the beginning so superclasses get called first\n HandlerSet set = handlerSets.get(type);\n if (set != null)\n handlers.addAll(0, set.getHandlers());\n\n type = type.getSuperclass();\n }\n\n // Put in priority order\n handlers.sort(Comparator.naturalOrder());\n\n // Call them\n for (HandlerFn fn : handlers) {\n if (event.isCancelled())\n break;\n fn.invoke(event);\n }\n }\n\n /**\n * Call handlers for an event and its superclasses. Superclasses are called\n * first, then handlers are called going down the type hierarchy.\n *\n * @param event event to dispatch\n */\n public void dispatchEvent(Event event) {\n dispatch(event.getClass(), event);\n }\n\n /**\n * Registers a listener to receive events. All methods in the listener\n * annotated with {@link EventHandler} are registered to handle events.\n *\n * @param listener listener to register\n */\n public void registerListener(Listener listener) {\n for (Method method : listener.getClass().getMethods()) {\n EventHandler annotation = method.getAnnotation(EventHandler.class);\n if (annotation == null)\n continue;\n\n Class<?>[] params = method.getParameterTypes();\n if (params.length != 1 || !Event.class.isAssignableFrom(params[0])) {\n System.err.println(\"Invalid event listener: \" + method);\n continue;\n }\n\n handlerSets.computeIfAbsent(params[0].asSubclass(Event.class), (t) -> new HandlerSet())\n .add(new HandlerFn(listener, method, annotation.priority()));\n }\n }\n\n /**\n * Unregisters a listener from receiving events. After unregistering, it\n * will no longer receive events.\n *\n * @param listener listener to unregister\n */\n public void unregisterListener(Listener listener) {\n // TODO\n }\n}"
},
{
"identifier": "Keyboard",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/input/keyboard/Keyboard.java",
"snippet": "public interface Keyboard {\n boolean isKeyPressed(Key key);\n}"
},
{
"identifier": "Mouse",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/input/mouse/Mouse.java",
"snippet": "public interface Mouse {\n Vector2d getCursorPos();\n boolean isButtonPressed(MouseButton button);\n}"
},
{
"identifier": "OpenGLWindow",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/opengl/OpenGLWindow.java",
"snippet": "public final class OpenGLWindow extends GlfwWindow {\n private OpenGLRenderer renderer;\n\n public OpenGLWindow(WindowSettings settings) {\n super(settings);\n }\n\n @Override\n protected void setContextWindowHints() {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);\n }\n\n @Override\n protected void initContext() {\n GL.createCapabilities(true);\n renderer = new OpenGLRenderer();\n }\n\n @Override\n public Renderer getRenderer() {\n return renderer;\n }\n}"
},
{
"identifier": "SafeCloseable",
"path": "azalea-core/src/main/java/com/github/rmheuer/azalea/utils/SafeCloseable.java",
"snippet": "public interface SafeCloseable extends AutoCloseable {\n @Override\n void close();\n}"
}
] | import com.github.rmheuer.azalea.event.EventBus;
import com.github.rmheuer.azalea.input.keyboard.Keyboard;
import com.github.rmheuer.azalea.input.mouse.Mouse;
import com.github.rmheuer.azalea.render.opengl.OpenGLWindow;
import com.github.rmheuer.azalea.utils.SafeCloseable;
import org.joml.Vector2i; | 1,701 | package com.github.rmheuer.azalea.render;
/**
* Represents the platform window graphics are rendered into. There can
* currently only be one window at a time.
*/
public interface Window extends SafeCloseable {
/**
* Gets the renderer used to render into this window.
*
* @return renderer
*/
Renderer getRenderer();
/**
* Gets whether the window should currently close. This will be true after
* something has requested the window to close, such as pressing its close
* button.
*
* @return whether the window should close
*/
boolean shouldClose();
/**
* Updates the contents of the window. This will show the result of
* rendering done using {@link #getRenderer()}. This may temporarily block
* if VSync is enabled, in order to limit the frame rate.
*/
void update();
/**
* Sets the window title. This is typically shown in the window's title
* bar.
*
* @param title new window title
*/
void setTitle(String title);
/**
* Gets the size of the window's framebuffer. This is not necessarily the
* same as the window's size, since the framebuffer may be larger on high
* DPI displays.
*
* @return size of the framebuffer
*/
Vector2i getFramebufferSize();
/**
* Gets the size of the window.
*
* @return window size
*/
Vector2i getSize();
/**
* Gets the window's keyboard input.
*
* @return keyboard input
*/ | package com.github.rmheuer.azalea.render;
/**
* Represents the platform window graphics are rendered into. There can
* currently only be one window at a time.
*/
public interface Window extends SafeCloseable {
/**
* Gets the renderer used to render into this window.
*
* @return renderer
*/
Renderer getRenderer();
/**
* Gets whether the window should currently close. This will be true after
* something has requested the window to close, such as pressing its close
* button.
*
* @return whether the window should close
*/
boolean shouldClose();
/**
* Updates the contents of the window. This will show the result of
* rendering done using {@link #getRenderer()}. This may temporarily block
* if VSync is enabled, in order to limit the frame rate.
*/
void update();
/**
* Sets the window title. This is typically shown in the window's title
* bar.
*
* @param title new window title
*/
void setTitle(String title);
/**
* Gets the size of the window's framebuffer. This is not necessarily the
* same as the window's size, since the framebuffer may be larger on high
* DPI displays.
*
* @return size of the framebuffer
*/
Vector2i getFramebufferSize();
/**
* Gets the size of the window.
*
* @return window size
*/
Vector2i getSize();
/**
* Gets the window's keyboard input.
*
* @return keyboard input
*/ | Keyboard getKeyboard(); | 1 | 2023-11-16 04:46:53+00:00 | 4k |
orijer/IvritInterpreter | src/Evaluation/EvaluationController.java | [
{
"identifier": "BooleanVariable",
"path": "src/Variables/BooleanVariable.java",
"snippet": "public class BooleanVariable extends AbstractVariable<Boolean> {\r\n //An array of all the operators boolean values support:\r\n public static String[] BOOLEAN_OPERATORS = { \"שווה\", \"לא-שווה\", \"וגם\", \"או\", \">\", \"<\" };\r\n\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public BooleanVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n if (value) {\r\n return \"אמת\";\r\n }\r\n\r\n return \"שקר\";\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n if (newValue.equals(\"אמת\")) {\r\n this.value = true;\r\n } else if (newValue.equals(\"שקר\")) {\r\n this.value = false;\r\n } else {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג טענה.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked\r\n * @return true IFF checkValue is a valid boolean value in Ivrit.\r\n */\r\n public static boolean isBooleanValue(String checkValue) {\r\n return checkValue.equals(\"אמת\") || checkValue.equals(\"שקר\");\r\n }\r\n\r\n //Static methods:\r\n\r\n /**\r\n * @return true IFF the given data contains a boolean expression (that isn't in quotes, \"\"וגם\"\" doesn't count)\r\n */\r\n public static boolean containsBooleanExpression(String data) {\r\n boolean inQuotes = false;\r\n\r\n for (int index = 0; index < data.length(); index++) {\r\n if (data.charAt(index) == '\"')\r\n inQuotes = !inQuotes;\r\n else if (!inQuotes) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n //Check if the data contains an operator here that isn't in quotes:\r\n if (data.startsWith(operator, index))\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * @return 0 if the given string doesn't start with a boolean operatorm or the operator length (how many characters it has) otherwise.\r\n */\r\n public static int startsWithBooleanOperator(String data) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n if (data.startsWith(operator))\r\n return operator.length();\r\n }\r\n\r\n return 0;\r\n }\r\n}\r"
},
{
"identifier": "StringVariable",
"path": "src/Variables/StringVariable.java",
"snippet": "public class StringVariable extends AbstractVariable<String> {\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public StringVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n return this.value;\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n if (newValue.charAt(0) == '\"' && newValue.charAt(newValue.length() - 1) == '\"') {\r\n this.value = newValue;\r\n } else {\r\n throw new NumberFormatException(\r\n \"הערך \" + newValue + \" לא מתאים למשתנה מסוג משפט. ודאו שאכן השתמשתם במרכאות מסביב לקטע הרצוי.\");\r\n }\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return this.value.substring(1, this.value.length() - 1);\r\n }\r\n\r\n //Static methods:\r\n\r\n /**\r\n * @param checkValue - The value to be checked.\r\n * @return true IFF checkValue is a valid string value in Ivrit.\r\n */\r\n public static boolean isStringValue(String checkValue) {\r\n return (checkValue.charAt(0) == '\"' && checkValue.charAt(checkValue.length() - 1) == '\"');\r\n }\r\n\r\n /**\r\n * @param str - The string to check.\r\n * @return true IFF the given string contains an Ivrit string in it (either by value: \"משהו משהו\", or by the name of a StringVariable).\r\n */\r\n public static boolean containsLiteralStrings(String str) {\r\n return (str.indexOf(\"\\\"\") != str.lastIndexOf(\"\\\"\"));\r\n }\r\n}\r"
},
{
"identifier": "VariablesController",
"path": "src/Variables/VariablesController.java",
"snippet": "public class VariablesController {\r\n //A map that connects between the name of the variable to its value:\r\n private Map<String, Variable> dataMap;\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public VariablesController() {\r\n this.dataMap = new HashMap<>();\r\n }\r\n\r\n /**\r\n * @param name - The name of the variable to check.\r\n * @return true IFF there is already a variable with the given name stored.\r\n */\r\n public boolean isVariable(String name) {\r\n return this.dataMap.containsKey(name);\r\n }\r\n\r\n /**\r\n * Creates a new variable.\r\n * @param variableName - The name of the new variable.\r\n * @param variableType - The type of the new variable.\r\n * @param variableValue - the value of the new variable.\r\n */\r\n public void createVariable(String variableName, String variableType, String variableValue) {\r\n Variable variable;\r\n if (this.dataMap.containsKey(variableValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable = VariablesFactory.createVariable(variableType, this.dataMap.get(variableValue).getValue());\r\n\r\n } else {\r\n //We are creating a variable from the value:\r\n variable = VariablesFactory.createVariable(variableType, variableValue);\r\n\r\n }\r\n\r\n this.dataMap.put(variableName, variable);\r\n }\r\n\r\n /**\r\n * Deletes the given variable from the program.\r\n * @param variableName - The name of the variable to delete.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void deleteVariable(String variableName) {\r\n if (!this.dataMap.containsKey(variableName))\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n\r\n this.dataMap.remove(variableName);\r\n }\r\n\r\n /**\r\n * Updates the value of an existing variable.\r\n * @param variableName - The name of the variable to be updated.\r\n * @param newValue - The new value.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void updateVariable(String variableName, String newValue) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n if (this.dataMap.containsKey(newValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable.updateValue(this.dataMap.get(newValue).getValue());\r\n } else {\r\n //We are updating from the value:\r\n variable.updateValue(newValue);\r\n\r\n }\r\n }\r\n\r\n /**\r\n * @param variableName - The name of the variable we wan the value of.\r\n * @return the value of the variable with the given name.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public String getVariableValue(String variableName) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n return variable.getValue();\r\n }\r\n\r\n /**\r\n * Clears all the variables created.\r\n */\r\n public void clear() {\r\n this.dataMap.clear();\r\n }\r\n\r\n /**\r\n * Prints all the variables in the format (variableName : variableValue).\r\n */\r\n public void printVariables() {\r\n for (Map.Entry<String, Variable> entry : this.dataMap.entrySet()) {\r\n System.out.println(\"(\" + entry.getKey() + \" : \" + entry.getValue().toString() + \")\");\r\n }\r\n }\r\n}\r"
}
] | import Variables.BooleanVariable;
import Variables.StringVariable;
import Variables.VariablesController;
| 2,232 | package Evaluation;
/**
* Handles evaluating a string based on its expected value type.
*/
public class EvaluationController {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - Contains the variables of the program.
*/
public EvaluationController(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Evaluates a given data string.
* @param data - The data to evaluate.
* @return the evaluated value of the given string (still represented as a string).
*/
public String evaluate(String data) {
//We first switch all variables with their values, so now we only deal with the values themselves:
VariableValueSwapper swapper = new VariableValueSwapper(this.variablesController);
data = swapper.swap(data);
Evaluator evaluator;
//Find the correct evaluator type:
if (BooleanVariable.containsBooleanExpression(data)) {
//Boolean evaluator:
evaluator = new BooleanEvaluator();
| package Evaluation;
/**
* Handles evaluating a string based on its expected value type.
*/
public class EvaluationController {
//Contains the variables of the program:
private VariablesController variablesController;
/**
* Constructor.
* @param variablesController - Contains the variables of the program.
*/
public EvaluationController(VariablesController variablesController) {
this.variablesController = variablesController;
}
/**
* Evaluates a given data string.
* @param data - The data to evaluate.
* @return the evaluated value of the given string (still represented as a string).
*/
public String evaluate(String data) {
//We first switch all variables with their values, so now we only deal with the values themselves:
VariableValueSwapper swapper = new VariableValueSwapper(this.variablesController);
data = swapper.swap(data);
Evaluator evaluator;
//Find the correct evaluator type:
if (BooleanVariable.containsBooleanExpression(data)) {
//Boolean evaluator:
evaluator = new BooleanEvaluator();
| } else if (StringVariable.containsLiteralStrings(data)) {
| 1 | 2023-11-17 09:15:07+00:00 | 4k |
WuKongOpenSource/Wukong_HRM | common/common-web/src/main/java/com/kakarote/core/config/WebConfig.java | [
{
"identifier": "Const",
"path": "common/common-web/src/main/java/com/kakarote/core/common/Const.java",
"snippet": "public class Const implements Serializable {\n\n /**\n * 项目版本\n */\n public static final String PROJECT_VERSION = \"12.3.6\";\n\n /**\n * 默认分隔符\n */\n public static final String SEPARATOR = \",\";\n\n /**\n * 查询数据权限递归次数,可以通过继承这个类修改\n */\n public static final int AUTH_DATA_RECURSION_NUM = 20;\n\n /**\n * 业务token在header中的名称\n */\n public static final String TOKEN_NAME = \"Admin-Token\";\n\n /**\n * 默认的token名称\n */\n public static final String DEFAULT_TOKEN_NAME = \"AUTH-TOKEN\";\n\n /**\n * 默认编码\n */\n public static final String DEFAULT_CONTENT_TYPE = \"application/json;charset=UTF-8\";\n\n /**\n * sql最大查询条数限制,以及字段数量限制\n */\n public static final Long QUERY_MAX_SIZE = 100L;\n\n /**\n * PC端登录的userKey\n */\n public static final String USER_TOKEN = \"WK:USER:TOKEN:\";\n\n /**\n * 临时token前缀\n */\n public static final String TEMP_TOKEN_PREFIX = \"TEMP:\";\n\n /**\n * 用户token的最长过期时间\n */\n public static final Integer MAX_USER_EXIST_TIME = 3600 * 24 * 7;\n\n /**\n * 批量保存的条数\n */\n public static final int BATCH_SAVE_SIZE = 200;\n\n\n /**\n * 默认的企业人数\n */\n public static final Integer DEFAULT_COMPANY_NUMBER = 999;\n\n public static final String DEFAULT_DOMAIN = \"www.72crm.com\";\n\n /**\n * 用户名称缓存key\n */\n public static final String ADMIN_USER_NAME_CACHE_NAME = \"ADMIN:USER:CACHE:\";\n\n /**\n * 部门名称缓存key\n */\n public static final String ADMIN_DEPT_NAME_CACHE_NAME = \"ADMIN:DEPT:CACHE:\";\n\n /**\n * 企业安全配置缓存key 前缀\n */\n public static final String COMPANY_SECURITY_CONFIG_KEY=\"COMPANY:SECURITY:CONFIG:\";\n\n /**\n * PC端登录的userKey\n */\n public static final String MULT_DEVICE_USER_TOKEN = \"MULT:DEVICE:USER:TOKEN:\";\n\n /**\n * 用户上次登录时间缓存key\n */\n public static final String USER_LOGIN_LASTED_TIME = \"USER:LOGIN:LASTED:TIME:\";\n\n /**\n * 移动端上次登录信息缓存\n */\n public static final String USER_LOGIN_LASTED_TIME_MOBILE = \"USER:LOGIN:LASTED:TIME:MOBILE:\";\n\n /**\n * 密码强度正则 大写字母、小写字母、数字、特殊符号\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_UPPER_LETTER_CHAR=\"^(?![0-9A-Za-z]+$)(?![0-9A-Z\\\\W]+$)(?![0-9a-z\\\\W]+$)(?![A-Za-z\\\\W]+$)[0-9A-Za-z~!@#$%^&*()_+`\\\\-={}|\\\\[\\\\]\\\\\\\\:\\\";'<>?,./]{\";\n /* \"/*8,16}$\";*/\n\n /**\n *密码强度正则 字母加数字\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_LETTER=\"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{\";\n\n /**\n * 密码强度正则 大小写字母加数字\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_UPPER_LETTER=\"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)[a-zA-Z\\\\d]{\";\n /**\n *密码强度正则 字母 数字 特殊字符\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_LETTER_CHAR=\"^(?=.*[a-zA-Z])(?=.*\\\\d)(?=.*[^a-zA-Z0-9])(?=.{8,})[A-Za-z\\\\d\\\\W]{\";\n\n /**\n * 密码强度正则后缀\n */\n public static final String PASSWORD_REG_SUFFIX=\",20}$\";\n\n public static final String NO_AUTH_MENU_CACHE_KEY = \"USER_NO_AUTH_URL:\";\n\n public static final String TOKEN_CACHE_NAME = \"_token\";\n\n}"
},
{
"identifier": "BaseUtil",
"path": "common/common-web/src/main/java/com/kakarote/core/utils/BaseUtil.java",
"snippet": "public class BaseUtil {\n\n private static final Snowflake SNOWFLAKE;\n\n\n static {\n /*\n TODO 目前使用自动生成的工作节点ID和数据中心ID,可使用自定义的数据中心ID\n */\n\n SNOWFLAKE = IdUtil.getSnowflake();\n }\n\n /**\n * 获取redis\n *\n * @return redis\n */\n public static Redis getRedis() {\n return UserCacheUtil.ME.redis;\n }\n\n /**\n * 获取当前年月的字符串\n *\n * @return yyyyMMdd\n */\n public static String getDate() {\n return DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMAT);\n }\n\n\n /**\n * 获取long类型的id,雪花算法\n * @return id\n */\n public static Long getNextId(){\n return SNOWFLAKE.nextId();\n }\n\n\n /**\n * 获取response对象\n *\n * @return response\n */\n public static HttpServletResponse getResponse() {\n ServletRequestAttributes attributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());\n return Optional.ofNullable(attributes).map(ServletRequestAttributes::getResponse).orElse(null);\n }\n\n /**\n * 默认的上传文件路径\n */\n public final static String UPLOAD_PATH = BaseUtil.isWindows() ? \"D:\\\\upload\\\\\" : \"/usr/local/upload/\";\n\n /**\n * 获取当前是否是windows系统\n * @return true代表为真\n */\n public static boolean isWindows() {\n return System.getProperty(\"os.name\").toLowerCase().contains(\"windows\");\n }\n\n public static String getIp(){\n return \"127.0.0.1\";\n }\n\n /**\n * 判断字符串是否是json数组\n *\n * @param str 字符串\n * @return true代表是\n */\n public static boolean isJSONArray(String str) {\n if (str == null) {\n return false;\n }\n return JSONValidator.from(str).getType() == JSONValidator.Type.Array;\n }\n\n /**\n * 判断字符串是否是json对象\n *\n * @param str 字符串\n * @return true代表是\n */\n public static boolean isJSONObject(String str) {\n if (str == null) {\n return false;\n }\n return JSONValidator.from(str).getType() == JSONValidator.Type.Object;\n }\n\n /**\n * 判断字符串是否是json\n *\n * @param str 字符串\n * @return true代表是\n */\n public static boolean isJSON(String str) {\n return isJSONArray(str) || isJSONObject(str);\n }\n}"
}
] | import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.kakarote.core.common.Const;
import com.kakarote.core.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.TimeZone; | 2,782 | package com.kakarote.core.config;
/**
* web配置类 以及分页配置
* @author zhangzhiwei
*/
@Configuration
public class WebConfig {
@Value("${spring.jackson.timeZone:GMT+8}")
private String timeZone;
/**
* long类型数据统一处理转换为string
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
jacksonObjectMapperBuilder.deserializerByType(Date.class, new DateDeSerializer());
//localDate类型的序列化
jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
//localDate类型的反序列化
jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
};
}
/**
* 对objectMapper增加一些时间类型的处理
*
* @return objectMapper
*/
@Bean
public ObjectMapper buildObjectMapper() {
ObjectMapper objectMapper = new JsonMapper();
objectMapper.registerModule(new Jdk8Module());
objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));
objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
javaTimeModule.addDeserializer(Date.class, new DateDeSerializer());
javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance);
javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(List<InnerInterceptor> interceptors) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
for (InnerInterceptor innerInterceptor : interceptors) {
interceptor.addInnerInterceptor(innerInterceptor);
}
return interceptor;
}
@Bean
public PaginationInnerInterceptor paginationInterceptor() {
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); | package com.kakarote.core.config;
/**
* web配置类 以及分页配置
* @author zhangzhiwei
*/
@Configuration
public class WebConfig {
@Value("${spring.jackson.timeZone:GMT+8}")
private String timeZone;
/**
* long类型数据统一处理转换为string
*/
@Bean
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return jacksonObjectMapperBuilder -> {
jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance);
jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
jacksonObjectMapperBuilder.deserializerByType(Date.class, new DateDeSerializer());
//localDate类型的序列化
jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
//localDate类型的反序列化
jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
};
}
/**
* 对objectMapper增加一些时间类型的处理
*
* @return objectMapper
*/
@Bean
public ObjectMapper buildObjectMapper() {
ObjectMapper objectMapper = new JsonMapper();
objectMapper.registerModule(new Jdk8Module());
objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN));
objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone));
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER));
javaTimeModule.addDeserializer(Date.class, new DateDeSerializer());
javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance);
javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(List<InnerInterceptor> interceptors) {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
for (InnerInterceptor innerInterceptor : interceptors) {
interceptor.addInnerInterceptor(innerInterceptor);
}
return interceptor;
}
@Bean
public PaginationInnerInterceptor paginationInterceptor() {
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL); | paginationInterceptor.setMaxLimit(Const.QUERY_MAX_SIZE * 100); | 0 | 2023-10-17 05:49:52+00:00 | 4k |
WisdomShell/codeshell-intellij | src/main/java/com/codeshell/intellij/actions/assistants/StyleCheck.java | [
{
"identifier": "PrefixString",
"path": "src/main/java/com/codeshell/intellij/constant/PrefixString.java",
"snippet": "public interface PrefixString {\n\n String EXPLAIN_CODE = \"请解释以下%s代码: %s\";\n\n String OPTIMIZE_CODE = \"请优化以下%s代码: %s\";\n\n String CLEAN_CODE = \"请清理以下%s代码: %s\";\n\n String COMMENT_CODE = \"请为以下%s代码的每一行生成注释: %s\";\n\n String UNIT_TEST_CODE = \"请为以下%s代码生成单元测试: %s\";\n\n String PERFORMANCE_CODE = \"检查以下%s代码,是否存在性能问题,请给出优化建议: %s\";\n\n String STYLE_CODE = \"检查以下%s代码的风格样式,请给出优化建议: %s\";\n\n String SECURITY_CODE = \"检查以下%s代码,是否存在安全性问题,请给出优化建议: %s\";\n\n String MARKDOWN_CODE_FIX = \"```\";\n\n String REQUST_END_TAG = \"|<end>|\";\n\n String RESPONSE_END_TAG = \"<|endoftext|>\";\n}"
},
{
"identifier": "CodeShellSideWindowService",
"path": "src/main/java/com/codeshell/intellij/services/CodeShellSideWindowService.java",
"snippet": "@Service\npublic final class CodeShellSideWindowService {\n\n private final Project project;\n private final CodeShellSideWindow codeShellSideWindow;\n\n public Project getProject() {\n return this.project;\n }\n\n public CodeShellSideWindow getCodeShellSideWindow() {\n return this.codeShellSideWindow;\n }\n\n public CodeShellSideWindowService(Project project) {\n this.project = project;\n this.codeShellSideWindow = new CodeShellSideWindow(project);\n }\n\n\n public void notifyIdeAppInstance(@NotNull JsonObject result) {\n CefBrowser browser = this.getCodeShellSideWindow().jbCefBrowser().getCefBrowser();\n browser.executeJavaScript(\"window.postMessage(\" + result + \",'*');\", browser.getURL(), 0);\n }\n}"
},
{
"identifier": "EditorUtils",
"path": "src/main/java/com/codeshell/intellij/utils/EditorUtils.java",
"snippet": "public class EditorUtils {\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, String preText) {\n return getFileSelectionDetails(editor, psiFile, false, preText);\n }\n\n public static boolean isNoneTextSelected(Editor editor) {\n return Objects.isNull(editor) || StringUtils.isEmpty(editor.getCaretModel().getCurrentCaret().getSelectedText());\n }\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, boolean isCodeNote, String preText) {\n if (Objects.isNull(editor)) {\n return getEmptyRange();\n } else {\n Document document = editor.getDocument();\n int startOffset;\n int endOffset;\n String editorText;\n\n if (editor.getSelectionModel().hasSelection()) {\n startOffset = editor.getSelectionModel().getSelectionStart();\n endOffset = editor.getSelectionModel().getSelectionEnd();\n editorText = editor.getSelectionModel().getSelectedText();\n } else {\n LogicalPosition logicalPos = editor.getCaretModel().getCurrentCaret().getLogicalPosition();\n int line = logicalPos.line;\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(line, Integer.MAX_VALUE));\n editorText = lspPosition(document, endOffset).get(\"text\").toString();\n if (isCodeNote) {\n editor.getDocument();\n for (int linenumber = 0; linenumber < editor.getDocument().getLineCount(); ++linenumber) {\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, Integer.MAX_VALUE));\n String tempText = lspPosition(document, endOffset).get(\"text\").toString();\n if (Objects.nonNull(tempText) && !\"\\\"\\\"\".equals(tempText.trim()) && !tempText.trim().isEmpty()) {\n editorText = tempText;\n break;\n }\n }\n }\n }\n JsonObject range = new JsonObject();\n range.add(\"start\", lspPosition(document, startOffset));\n range.add(\"end\", lspPosition(document, endOffset));\n range.addProperty(\"selectedText\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject sendText = new JsonObject();\n sendText.addProperty(\"inputs\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject parameters = new JsonObject();\n parameters.addProperty(\"max_new_tokens\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n sendText.add(\"parameters\", parameters);\n\n JsonObject returnObj = new JsonObject();\n returnObj.add(\"range\", range);\n if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"CPU\");\n }else{\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"GPU\");\n }\n returnObj.addProperty(\"maxToken\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n returnObj.add(\"sendText\", sendText);\n return returnObj;\n }\n }\n\n public static JsonObject lspPosition(Document document, int offset) {\n int line = document.getLineNumber(offset);\n int lineStart = document.getLineStartOffset(line);\n String lineTextBeforeOffset = document.getText(TextRange.create(lineStart, offset));\n int column = lineTextBeforeOffset.length();\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"line\", line);\n jsonObject.addProperty(\"column\", column);\n jsonObject.addProperty(\"text\", lineTextBeforeOffset);\n return jsonObject;\n }\n\n public static JsonObject getEmptyRange() {\n JsonObject jsonObject = new JsonObject();\n JsonObject range = new JsonObject();\n JsonObject lineCol = new JsonObject();\n lineCol.addProperty(\"line\", \"0\");\n lineCol.addProperty(\"column\", \"0\");\n lineCol.addProperty(\"text\", \"0\");\n range.add(\"start\", lineCol);\n range.add(\"end\", lineCol);\n jsonObject.add(\"range\", range);\n jsonObject.addProperty(\"selectedText\", \"\");\n return jsonObject;\n }\n\n private static String includePreText(String preText, String language, String text) {\n String sufText = \"\\n```\" + language + \"\\n\" + text + \"\\n```\\n\";\n return String.format(preText, language, sufText);\n }\n\n public static boolean isMainEditor(Editor editor) {\n return editor.getEditorKind() == EditorKind.MAIN_EDITOR || ApplicationManager.getApplication().isUnitTestMode();\n }\n\n}"
}
] | import com.codeshell.intellij.constant.PrefixString;
import com.codeshell.intellij.services.CodeShellSideWindowService;
import com.codeshell.intellij.utils.EditorUtils;
import com.google.gson.JsonObject;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.util.IntentionFamilyName;
import com.intellij.codeInspection.util.IntentionName;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.Objects; | 2,074 | package com.codeshell.intellij.actions.assistants;
public class StyleCheck extends DumbAwareAction implements IntentionAction {
@SafeFieldForPreview
private Logger logger = Logger.getInstance(this.getClass());
@Override
@IntentionName
@NotNull
public String getText() {
return "Style Check";
}
@Override
@NotNull
@IntentionFamilyName
public String getFamilyName() {
return "CodeShell";
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return false;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
}
@Override
public boolean startInWriteAction() {
return true;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getData(LangDataKeys.PROJECT);
if (Objects.isNull(project)) {
return;
}
ApplicationManager.getApplication().invokeLater(() -> {
VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); | package com.codeshell.intellij.actions.assistants;
public class StyleCheck extends DumbAwareAction implements IntentionAction {
@SafeFieldForPreview
private Logger logger = Logger.getInstance(this.getClass());
@Override
@IntentionName
@NotNull
public String getText() {
return "Style Check";
}
@Override
@NotNull
@IntentionFamilyName
public String getFamilyName() {
return "CodeShell";
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return false;
}
@Override
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
}
@Override
public boolean startInWriteAction() {
return true;
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getData(LangDataKeys.PROJECT);
if (Objects.isNull(project)) {
return;
}
ApplicationManager.getApplication().invokeLater(() -> {
VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR); | if (EditorUtils.isNoneTextSelected(editor)) { | 2 | 2023-10-18 06:29:13+00:00 | 4k |
djkcyl/Shamrock | qqinterface/src/main/java/tencent/im/oidb/cmd0x8fc/Oidb_0x8fc.java | [
{
"identifier": "ByteStringMicro",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java",
"snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr, int i2, int i3) {\n return null;\n }\n\n public static ByteStringMicro copyFromUtf8(String str) {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public int size() {\n return 0;\n }\n\n public byte[] toByteArray() {\n return null;\n }\n\n public String toString(String str) {\n return \"\";\n }\n\n public String toStringUtf8() {\n return \"\";\n }\n}"
},
{
"identifier": "MessageMicro",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/MessageMicro.java",
"snippet": "public class MessageMicro<T extends MessageMicro<T>> {\n public final T mergeFrom(byte[] bArr) {\n return null;\n }\n\n public final byte[] toByteArray() {\n return null;\n }\n\n public T get() {\n return null;\n }\n\n public void set(T t) {\n }\n}"
},
{
"identifier": "PBBytesField",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBytesField.java",
"snippet": "public class PBBytesField extends PBPrimitiveField<ByteStringMicro> {\n public static PBField<ByteStringMicro> __repeatHelper__;\n\n public PBBytesField(ByteStringMicro byteStringMicro, boolean z) {\n }\n\n public ByteStringMicro get() {\n return null;\n }\n\n public void set(ByteStringMicro byteStringMicro) {\n }\n}"
},
{
"identifier": "PBEnumField",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBEnumField.java",
"snippet": "public class PBEnumField extends PBPrimitiveField<Integer>{\n public PBEnumField(int i2, boolean z) {\n }\n\n public int get() {\n return 0;\n }\n\n public void set(int i2) {\n }\n\n}"
},
{
"identifier": "PBField",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBField.java",
"snippet": "public abstract class PBField<T> {\n public static <T extends MessageMicro<T>> PBRepeatMessageField<T> initRepeatMessage(Class<T> cls) {\n return new PBRepeatMessageField<>(cls);\n }\n\n public static <T> PBRepeatField<T> initRepeat(PBField<T> pBField) {\n return new PBRepeatField<>(pBField);\n }\n\n public static PBUInt32Field initUInt32(int i2) {\n return new PBUInt32Field(i2, false);\n }\n\n public static PBStringField initString(String str) {\n return new PBStringField(str, false);\n }\n\n public static PBBytesField initBytes(ByteStringMicro byteStringMicro) {\n return new PBBytesField(byteStringMicro, false);\n }\n\n public static PBBoolField initBool(boolean z) {\n return new PBBoolField(z, false);\n }\n\n public static PBInt32Field initInt32(int i2) {\n return new PBInt32Field(i2, false);\n }\n\n public static PBUInt64Field initUInt64(long j2) {\n return new PBUInt64Field(j2, false);\n }\n\n public static PBInt64Field initInt64(long j2) {\n return new PBInt64Field(j2, false);\n }\n\n public static PBEnumField initEnum(int i2) {\n return new PBEnumField(i2, false);\n }\n}"
},
{
"identifier": "PBRepeatMessageField",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBRepeatMessageField.java",
"snippet": "public final class PBRepeatMessageField<T extends MessageMicro<T>> extends PBField<List<T>> {\n public PBRepeatMessageField(Class<T> cls) {\n\n }\n\n public void add(T t) {\n\n }\n\n public T get(int pos) {\n return null;\n }\n\n public List<T> get() {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public void set(int i2, T t) {\n }\n\n public void set(List<T> list) {\n }\n\n public int size() {\n return 0;\n }\n\n\n}"
},
{
"identifier": "PBStringField",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBStringField.java",
"snippet": "public class PBStringField extends PBPrimitiveField<String>{\n public PBStringField(String str, boolean z) {\n }\n\n public void set(String str, boolean z) {\n }\n\n public void set(String str) {\n }\n\n public String get() {\n return \"\";\n }\n}"
},
{
"identifier": "PBUInt32Field",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt32Field.java",
"snippet": "public class PBUInt32Field extends PBPrimitiveField<Integer> {\n public static PBUInt32Field __repeatHelper__;\n\n public PBUInt32Field(int i2, boolean z) {\n }\n\n public void set(int i2) {\n\n }\n\n public int get() {\n return 0;\n }\n}"
},
{
"identifier": "PBUInt64Field",
"path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt64Field.java",
"snippet": "public class PBUInt64Field extends PBPrimitiveField<Long> {\n public static PBField<Long> __repeatHelper__;\n\n public PBUInt64Field(long i2, boolean z) {\n }\n\n public void set(long i2) {\n\n }\n\n public long get() {\n return 0;\n }\n}"
}
] | import com.tencent.mobileqq.pb.ByteStringMicro;
import com.tencent.mobileqq.pb.MessageMicro;
import com.tencent.mobileqq.pb.PBBytesField;
import com.tencent.mobileqq.pb.PBEnumField;
import com.tencent.mobileqq.pb.PBField;
import com.tencent.mobileqq.pb.PBRepeatMessageField;
import com.tencent.mobileqq.pb.PBStringField;
import com.tencent.mobileqq.pb.PBUInt32Field;
import com.tencent.mobileqq.pb.PBUInt64Field; | 1,752 | package tencent.im.oidb.cmd0x8fc;
public class Oidb_0x8fc {
public static final class ReqBody extends MessageMicro<ReqBody> {
public final PBUInt64Field uint64_group_code = PBField.initUInt64(0);
public final PBUInt32Field uint32_show_flag = PBField.initUInt32(0);
public final PBRepeatMessageField<MemberInfo> rpt_mem_level_info = PBField.initRepeatMessage(MemberInfo.class);
public final PBRepeatMessageField<LevelName> rpt_level_name = PBField.initRepeatMessage(LevelName.class);
public final PBUInt32Field uint32_update_time = PBField.initUInt32(0);
public final PBUInt32Field uint32_office_mode = PBField.initUInt32(0);
public final PBUInt32Field uint32_group_open_appid = PBField.initUInt32(0);
public ClientInfo msg_client_info = new ClientInfo(); | package tencent.im.oidb.cmd0x8fc;
public class Oidb_0x8fc {
public static final class ReqBody extends MessageMicro<ReqBody> {
public final PBUInt64Field uint64_group_code = PBField.initUInt64(0);
public final PBUInt32Field uint32_show_flag = PBField.initUInt32(0);
public final PBRepeatMessageField<MemberInfo> rpt_mem_level_info = PBField.initRepeatMessage(MemberInfo.class);
public final PBRepeatMessageField<LevelName> rpt_level_name = PBField.initRepeatMessage(LevelName.class);
public final PBUInt32Field uint32_update_time = PBField.initUInt32(0);
public final PBUInt32Field uint32_office_mode = PBField.initUInt32(0);
public final PBUInt32Field uint32_group_open_appid = PBField.initUInt32(0);
public ClientInfo msg_client_info = new ClientInfo(); | public final PBBytesField bytes_auth_key = PBField.initBytes(ByteStringMicro.EMPTY); | 0 | 2023-10-20 10:43:47+00:00 | 4k |
ballerina-platform/module-ballerinax-copybook | native/src/main/java/io/ballerina/lib/copybook/runtime/convertor/Utils.java | [
{
"identifier": "Copybook",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/Copybook.java",
"snippet": "public class Copybook {\n\n private Copybook() {\n }\n\n public static Schema parse(String schemaPath) throws IOException {\n CopybookLexer lexer = new CopybookLexer(CharStreams.fromStream(new FileInputStream(schemaPath)));\n CommonTokenStream tokens = new CommonTokenStream(lexer);\n CopybookParser parser = new CopybookParser(tokens);\n\n parser.removeErrorListeners();\n CopybookErrorListener errorListener = new CopybookErrorListener();\n parser.addErrorListener(errorListener);\n\n CopybookParser.StartRuleContext startRule = parser.startRule();\n SchemaBuilder visitor = new SchemaBuilder();\n try {\n startRule.accept(visitor);\n } catch (Exception e) {\n // Intentionally kept empty, already handled by the error listener.\n }\n Schema schema = visitor.getSchema();\n schema.addErrors(errorListener.getErrors());\n return schema;\n }\n}"
},
{
"identifier": "CopybookNode",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/CopybookNode.java",
"snippet": "public interface CopybookNode {\n int getLevel();\n String getName();\n int getOccurringCount();\n String getRedefinedItemName();\n}"
},
{
"identifier": "DataItem",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/DataItem.java",
"snippet": "public class DataItem implements CopybookNode {\n private final int level;\n private final String name;\n private final String picture;\n private final boolean isNumeric;\n private final int occurs;\n private final int readLength;\n private final boolean isSinged;\n private final int floatingPointLength;\n private final String redefinedItemName;\n\n public DataItem(int level, String name, String picture, boolean isNumeric, int readLength, int occurs,\n int floatingPointLength, String redefinedItemName, GroupItem parent) {\n this.level = level;\n this.name = name;\n this.picture = picture;\n this.isNumeric = isNumeric;\n this.readLength = readLength;\n this.occurs = occurs;\n this.isSinged = Utils.isSigned(picture);\n this.floatingPointLength = floatingPointLength;\n this.redefinedItemName = redefinedItemName;\n if (parent != null) {\n parent.addChild(this);\n }\n }\n\n @Override\n public int getLevel() {\n return this.level;\n }\n\n public String getName() {\n return this.name;\n }\n\n public String getPicture() {\n return this.picture;\n }\n\n public boolean isNumeric() {\n return this.isNumeric;\n }\n\n public int getOccurringCount() {\n return this.occurs;\n }\n\n public int getReadLength() {\n return this.readLength;\n }\n\n public boolean isSinged() {\n return this.isSinged;\n }\n\n public int getFloatingPointLength() {\n return this.floatingPointLength;\n }\n\n public String getRedefinedItemName() {\n return redefinedItemName;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(\"\\\"level\\\":\").append(this.level).append(\", \\\"name\\\":\\\"\").append(this.name).append(\"\\\"\")\n .append(\", \\\"picture\\\":\\\"\").append(this.picture).append(\"\\\"\").append(\", \\\"readLength\\\":\")\n .append(this.readLength).append(\", \\\"numeric\\\":\").append(this.isNumeric);\n\n if (this.occurs > -1) {\n sb.append(\", \\\"occurs\\\":\").append(this.occurs);\n }\n if (this.isNumeric) {\n sb.append(\", \\\"isSigned\\\":\").append(this.isSinged);\n }\n if (this.floatingPointLength > 0) {\n sb.append(\", \\\"floatingPointLength\\\":\").append(this.floatingPointLength);\n }\n if (this.redefinedItemName != null) {\n sb.append(\", \\\"redefinedItemName\\\": \\\"\").append(this.redefinedItemName).append(\"\\\"\");\n }\n sb.append(\"}\");\n return sb.toString();\n }\n}"
},
{
"identifier": "GroupItem",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/GroupItem.java",
"snippet": "public class GroupItem implements CopybookNode {\n private final int level;\n private final String name;\n private final int occurs;\n private final GroupItem parent;\n public List<CopybookNode> children;\n private final String redefinedItemName;\n\n public GroupItem(int level, String name, int occurs, String redefinedItemName,\n GroupItem parent) {\n this.level = level;\n this.name = name;\n this.occurs = occurs;\n this.parent = parent;\n this.children = new CopybookNodeList();\n this.redefinedItemName = redefinedItemName;\n if (parent != null) {\n this.parent.addChild(this);\n }\n }\n\n public void addChild(CopybookNode copybookNode) {\n this.children.add(copybookNode);\n }\n\n @Override\n public int getLevel() {\n return this.level;\n }\n\n public String getName() {\n return this.name;\n }\n\n public int getOccurringCount() {\n return this.occurs;\n }\n\n public GroupItem getParent() {\n return this.parent;\n }\n\n public List<CopybookNode> getChildren() {\n return this.children;\n }\n\n public String getRedefinedItemName() {\n return redefinedItemName;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\").append(\"\\\"level\\\":\").append(this.level).append(\", \\\"name\\\":\\\"\").append(this.name).append(\"\\\"\")\n .append(\", \\\"children\\\":\").append(this.children);\n if (this.occurs > -1) {\n sb.append(\", \\\"occurs\\\":\").append(this.occurs);\n }\n if (this.redefinedItemName != null) {\n sb.append(\", \\\"redefinedItemName\\\": \\\"\").append(this.redefinedItemName).append(\"\\\"\");\n }\n sb.append(\"}\");\n return sb.toString();\n }\n}"
},
{
"identifier": "Schema",
"path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/Schema.java",
"snippet": "public class Schema {\n private final List<CopybookNode> typeDefinitions = new CopybookNodeList();\n private final Map<String, CopybookNode> redefinedItems = new HashMap<>();\n private final List<String> errors = new ArrayList<>();\n\n void addTypeDefinition(CopybookNode copybookNode) {\n this.typeDefinitions.add(copybookNode);\n }\n\n void addRedefinedItem(CopybookNode copybookNode) {\n this.redefinedItems.put(copybookNode.getName(), copybookNode);\n }\n\n public List<CopybookNode> getTypeDefinitions() {\n return typeDefinitions;\n }\n\n public Map<String, CopybookNode> getRedefinedItems() {\n return redefinedItems;\n }\n\n @Override\n public String toString() {\n return \"{\" + \"\\\"schema\\\"\" + \":\" + typeDefinitions + \"}\";\n }\n\n void addErrors(List<String> errors) {\n this.errors.addAll(errors);\n }\n\n public List<String> getErrors() {\n return errors;\n }\n}"
},
{
"identifier": "getModule",
"path": "native/src/main/java/io/ballerina/lib/copybook/runtime/convertor/ModuleUtils.java",
"snippet": "public static Module getModule() {\n return copybookModule;\n}"
}
] | import io.ballerina.lib.copybook.commons.schema.Copybook;
import io.ballerina.lib.copybook.commons.schema.CopybookNode;
import io.ballerina.lib.copybook.commons.schema.DataItem;
import io.ballerina.lib.copybook.commons.schema.GroupItem;
import io.ballerina.lib.copybook.commons.schema.Schema;
import io.ballerina.runtime.api.Environment;
import io.ballerina.runtime.api.Future;
import io.ballerina.runtime.api.PredefinedTypes;
import io.ballerina.runtime.api.creators.ErrorCreator;
import io.ballerina.runtime.api.creators.TypeCreator;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.types.ArrayType;
import io.ballerina.runtime.api.types.MapType;
import io.ballerina.runtime.api.types.ObjectType;
import io.ballerina.runtime.api.utils.StringUtils;
import io.ballerina.runtime.api.values.BArray;
import io.ballerina.runtime.api.values.BError;
import io.ballerina.runtime.api.values.BMap;
import io.ballerina.runtime.api.values.BObject;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.api.values.BTypedesc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static io.ballerina.lib.copybook.runtime.converter.ModuleUtils.getModule; | 2,651 | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.lib.copybook.runtime.converter;
public final class Utils {
private static final String NATIVE_VALUE = "native-value";
private static final String TO_RECORD_METHOD_NAME = "toRecord";
private static final String NODE_TYPE_NAME = "Node";
private static final String SCHEMA_TYPE_NAME = "Schema";
private static final String GROUP_ITEM_TYPE_NAME = "GroupItem";
private static final String DATA_ITEM_TYPE_NAME = "DataItem";
private static final String ERROR_TYPE_NAME = "Error";
private Utils() {
}
public static Object parseSchemaFile(BString schemaPath) {
BObject schema = ValueCreator.createObjectValue(getModule(), SCHEMA_TYPE_NAME);
try {
Schema nativeSchema = Copybook.parse(schemaPath.getValue());
if (!nativeSchema.getErrors().isEmpty()) {
return handleParsingError(nativeSchema);
}
schema.addNativeData(NATIVE_VALUE, nativeSchema);
return schema;
} catch (IOException e) {
return createError(e.getMessage());
}
}
private static BError handleParsingError(Schema nativeSchema) {
BString[] bStrings = nativeSchema.getErrors().stream().map(StringUtils::fromString).toArray(BString[]::new);
BArray errors = ValueCreator.createArrayValue(bStrings);
BMap<BString, Object> errorDetail = ValueCreator.createMapValue();
errorDetail.put(StringUtils.fromString("parser-errors"), errors);
return createError("Error while parsing the Copybook schema.", errorDetail);
}
private static BError createError(String message, BMap<BString, Object> errorDetail) {
return ErrorCreator.createError(getModule(), ERROR_TYPE_NAME, StringUtils.fromString(message), null,
errorDetail);
}
private static BError createError(String message) {
return createError(message, null);
}
public static int getLevel(BObject bObject) { | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.lib.copybook.runtime.converter;
public final class Utils {
private static final String NATIVE_VALUE = "native-value";
private static final String TO_RECORD_METHOD_NAME = "toRecord";
private static final String NODE_TYPE_NAME = "Node";
private static final String SCHEMA_TYPE_NAME = "Schema";
private static final String GROUP_ITEM_TYPE_NAME = "GroupItem";
private static final String DATA_ITEM_TYPE_NAME = "DataItem";
private static final String ERROR_TYPE_NAME = "Error";
private Utils() {
}
public static Object parseSchemaFile(BString schemaPath) {
BObject schema = ValueCreator.createObjectValue(getModule(), SCHEMA_TYPE_NAME);
try {
Schema nativeSchema = Copybook.parse(schemaPath.getValue());
if (!nativeSchema.getErrors().isEmpty()) {
return handleParsingError(nativeSchema);
}
schema.addNativeData(NATIVE_VALUE, nativeSchema);
return schema;
} catch (IOException e) {
return createError(e.getMessage());
}
}
private static BError handleParsingError(Schema nativeSchema) {
BString[] bStrings = nativeSchema.getErrors().stream().map(StringUtils::fromString).toArray(BString[]::new);
BArray errors = ValueCreator.createArrayValue(bStrings);
BMap<BString, Object> errorDetail = ValueCreator.createMapValue();
errorDetail.put(StringUtils.fromString("parser-errors"), errors);
return createError("Error while parsing the Copybook schema.", errorDetail);
}
private static BError createError(String message, BMap<BString, Object> errorDetail) {
return ErrorCreator.createError(getModule(), ERROR_TYPE_NAME, StringUtils.fromString(message), null,
errorDetail);
}
private static BError createError(String message) {
return createError(message, null);
}
public static int getLevel(BObject bObject) { | CopybookNode copybookNode = (CopybookNode) bObject.getNativeData(NATIVE_VALUE); | 1 | 2023-10-24 04:51:53+00:00 | 4k |
ballerina-platform/copybook-tools | copybook-cli/src/main/java/io/ballerina/tools/copybook/cmd/CopybookCmd.java | [
{
"identifier": "Constants",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/diagnostic/Constants.java",
"snippet": "public class Constants {\n\n public static final String MESSAGE_FOR_INVALID_FILE_EXTENSION = \"File \\\"%s\\\" is invalid. Copybook tool support\" +\n \" only the Copybook definition files with .cpy or .cob extension. %nPlease provide the path of the input \" +\n \" file with -i or --input flag.%ne.g: bal copybook --input <Copybook Definition File>\";\n public static final String MESSAGE_CAN_NOT_READ_COPYBOOK_FILE =\n \"Provided definition file \\\"%s\\\" is not allowed to be read\";\n public static final String MESSAGE_FOR_INVALID_COPYBOOK_PATH =\n \"The copybook definition file does not exist in the given path\";\n}"
},
{
"identifier": "DiagnosticMessages",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/diagnostic/DiagnosticMessages.java",
"snippet": "public enum DiagnosticMessages {\n COPYBOOK_TYPE_GEN_100(\"COPYBOOK_TYPE_GEN_100\", \"Copybook types generation failed: The input file path argument\" +\n \" is missing. Please provide the path of the Copybook definition file with -i or --input flag.\",\n DiagnosticSeverity.ERROR),\n COPYBOOK_TYPE_GEN_102(\"COPYBOOK_TYPE_GEN_102\", \"Copybook types generation failed: %s\", DiagnosticSeverity.ERROR),\n COPYBOOK_TYPE_GEN_103(\"COPYBOOK_TYPE_GEN_103\", \"Failed to create output directory: %s\", DiagnosticSeverity.ERROR);\n private final String code;\n private final String description;\n private final DiagnosticSeverity severity;\n\n DiagnosticMessages(String code, String description, DiagnosticSeverity severity) {\n this.code = code;\n this.description = description;\n this.severity = severity;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public DiagnosticSeverity getSeverity() {\n return severity;\n }\n}"
},
{
"identifier": "CmdException",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/exception/CmdException.java",
"snippet": "public class CmdException extends Exception {\n private final Diagnostic diagnostic;\n\n public CmdException(DiagnosticMessages diagnosticMessage, Location location) {\n super(diagnosticMessage.getDescription());\n this.diagnostic = createDiagnostic(diagnosticMessage, location);\n }\n\n public CmdException(DiagnosticMessages diagnosticMessage, Location location, String... args) {\n super(generateDescription(diagnosticMessage, args));\n this.diagnostic = createDiagnostic(diagnosticMessage, location, args);\n }\n\n public String getMessage() {\n return this.diagnostic.toString();\n }\n\n private static String generateDescription(DiagnosticMessages message, String... args) {\n return String.format(message.getDescription(), (Object[]) args);\n }\n\n private static Diagnostic createDiagnostic(DiagnosticMessages diagnosticMessage, Location location,\n String... args) {\n DiagnosticInfo diagnosticInfo = new DiagnosticInfo(diagnosticMessage.getCode(),\n generateDescription(diagnosticMessage, args), diagnosticMessage.getSeverity());\n if (location == null) {\n location = NullLocation.getInstance();\n }\n return DiagnosticFactory.createDiagnostic(diagnosticInfo, location);\n }\n}"
},
{
"identifier": "CopybookTypeGenerationException",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/exception/CopybookTypeGenerationException.java",
"snippet": "public class CopybookTypeGenerationException extends Exception {\n private final Diagnostic diagnostic;\n\n public CopybookTypeGenerationException(DiagnosticMessages diagnosticMessage, Location location, String... args) {\n super(generateDescription(diagnosticMessage, args));\n this.diagnostic = createDiagnostic(diagnosticMessage, location, args);\n }\n\n public String getMessage() {\n return this.diagnostic.toString();\n }\n\n private static String generateDescription(DiagnosticMessages message, String... args) {\n return String.format(message.getDescription(), (Object[]) args);\n }\n\n private static Diagnostic createDiagnostic(DiagnosticMessages diagnosticMessage, Location location,\n String... args) {\n DiagnosticInfo diagnosticInfo = new DiagnosticInfo(diagnosticMessage.getCode(),\n generateDescription(diagnosticMessage, args), diagnosticMessage.getSeverity());\n if (location == null) {\n location = NullLocation.getInstance();\n }\n return DiagnosticFactory.createDiagnostic(diagnosticInfo, location);\n }\n}"
},
{
"identifier": "CodeGenerator",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/CodeGenerator.java",
"snippet": "public abstract class CodeGenerator {\n\n protected CodeGenerator() {\n }\n\n public static void generate(Path cbFilePath, Path targetOutputPath, PrintStream outStream)\n throws CopybookTypeGenerationException, FormatterException, IOException {\n Schema schema = Copybook.parse(cbFilePath.toString());\n if (!schema.getErrors().isEmpty()) {\n List<String> errorList = schema.getErrors();\n String errors = errorList.stream().collect(Collectors.joining(System.lineSeparator()));\n throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, errors);\n }\n boolean isCreated = createOutputDirectory(targetOutputPath);\n if (!isCreated) {\n throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_103, null,\n targetOutputPath.toString());\n }\n CopybookTypeGenerator codeGenerator = new CopybookTypeGenerator(schema);\n String src = codeGenerator.generateSourceCode();\n String fileName = getFileName(cbFilePath.toString());\n String resolvedFileName = resolveSchemaFileName(targetOutputPath, fileName);\n writeFile(targetOutputPath.resolve(resolvedFileName), src);\n outStream.println(\"Ballerina record types are generated successfully and copied to :\");\n outStream.println(\"-- \" + resolvedFileName);\n }\n}"
},
{
"identifier": "COBOL_EXTENSION",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java",
"snippet": "public static final String COBOL_EXTENSION = \".cob\";"
},
{
"identifier": "COPYBOOK_EXTENSION",
"path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java",
"snippet": "public static final String COPYBOOK_EXTENSION = \".cpy\";"
}
] | import io.ballerina.cli.BLauncherCmd;
import io.ballerina.tools.copybook.diagnostic.Constants;
import io.ballerina.tools.copybook.diagnostic.DiagnosticMessages;
import io.ballerina.tools.copybook.exception.CmdException;
import io.ballerina.tools.copybook.exception.CopybookTypeGenerationException;
import io.ballerina.tools.copybook.generator.CodeGenerator;
import org.ballerinalang.formatter.core.FormatterException;
import picocli.CommandLine;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static io.ballerina.tools.copybook.generator.GeneratorConstants.COBOL_EXTENSION;
import static io.ballerina.tools.copybook.generator.GeneratorConstants.COPYBOOK_EXTENSION; | 2,581 | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.tools.copybook.cmd;
@CommandLine.Command(
name = "copybook",
description = "Generates Ballerina record types for copybooks definition"
)
public class CopybookCmd implements BLauncherCmd {
private static final String CMD_NAME = "copybook";
private final PrintStream outStream;
private final boolean exitWhenFinish;
private Path executionPath = Paths.get(System.getProperty("user.dir"));
@CommandLine.Option(names = {"-h", "--help"}, hidden = true)
private boolean helpFlag;
@CommandLine.Option(names = {"-i", "--input"},
description = "File path to the Copybook definition file")
private boolean inputPathFlag;
@CommandLine.Option(names = {"-o", "--output"},
description = "Directory to store the generated Ballerina record types")
private String outputPath;
@CommandLine.Parameters
private List<String> argList;
public CopybookCmd() {
this(System.err, Paths.get(System.getProperty("user.dir")), true);
}
public CopybookCmd(PrintStream outStream, Path executionDir, boolean exitWhenFinish) {
this.outStream = outStream;
this.executionPath = executionDir;
this.exitWhenFinish = exitWhenFinish;
}
private static void exitError(boolean exit) {
if (exit) {
Runtime.getRuntime().exit(1);
}
}
@Override
public void execute() {
try {
if (helpFlag) {
printLongDesc(new StringBuilder());
outStream.flush();
exitError(this.exitWhenFinish);
return;
}
validateInputFlags();
executeOperation();
} catch (CmdException | CopybookTypeGenerationException | FormatterException | IOException e) {
outStream.println(e.getMessage());
exitError(this.exitWhenFinish);
}
}
private void validateInputFlags() throws CmdException, IOException {
if (inputPathFlag) {
if (argList == null) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_100, null);
}
} else {
getCommandUsageInfo();
exitError(this.exitWhenFinish);
return;
}
String filePath = argList.get(0);
if (!validInputFileExtension(filePath)) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_FOR_INVALID_FILE_EXTENSION, filePath));
}
}
private void executeOperation() throws CopybookTypeGenerationException, CmdException, FormatterException,
IOException {
String filePath = argList.get(0);
generateType(filePath);
}
private void generateType(String filePath)
throws CmdException, CopybookTypeGenerationException, FormatterException, IOException {
final File copybookFile = new File(filePath);
if (!copybookFile.exists()) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_FOR_INVALID_COPYBOOK_PATH, filePath));
}
if (!copybookFile.canRead()) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_CAN_NOT_READ_COPYBOOK_FILE, filePath));
}
Path copybookFilePath = null;
try {
copybookFilePath = Paths.get(copybookFile.getCanonicalPath());
} catch (IOException e) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.toString());
}
CodeGenerator.generate(copybookFilePath, getTargetOutputPath(), outStream);
}
private Path getTargetOutputPath() {
Path targetOutputPath = executionPath;
if (this.outputPath != null) {
if (Paths.get(outputPath).isAbsolute()) {
targetOutputPath = Paths.get(outputPath);
} else {
targetOutputPath = Paths.get(targetOutputPath.toString(), outputPath);
}
}
return targetOutputPath;
}
private boolean validInputFileExtension(String filePath) { | /*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.tools.copybook.cmd;
@CommandLine.Command(
name = "copybook",
description = "Generates Ballerina record types for copybooks definition"
)
public class CopybookCmd implements BLauncherCmd {
private static final String CMD_NAME = "copybook";
private final PrintStream outStream;
private final boolean exitWhenFinish;
private Path executionPath = Paths.get(System.getProperty("user.dir"));
@CommandLine.Option(names = {"-h", "--help"}, hidden = true)
private boolean helpFlag;
@CommandLine.Option(names = {"-i", "--input"},
description = "File path to the Copybook definition file")
private boolean inputPathFlag;
@CommandLine.Option(names = {"-o", "--output"},
description = "Directory to store the generated Ballerina record types")
private String outputPath;
@CommandLine.Parameters
private List<String> argList;
public CopybookCmd() {
this(System.err, Paths.get(System.getProperty("user.dir")), true);
}
public CopybookCmd(PrintStream outStream, Path executionDir, boolean exitWhenFinish) {
this.outStream = outStream;
this.executionPath = executionDir;
this.exitWhenFinish = exitWhenFinish;
}
private static void exitError(boolean exit) {
if (exit) {
Runtime.getRuntime().exit(1);
}
}
@Override
public void execute() {
try {
if (helpFlag) {
printLongDesc(new StringBuilder());
outStream.flush();
exitError(this.exitWhenFinish);
return;
}
validateInputFlags();
executeOperation();
} catch (CmdException | CopybookTypeGenerationException | FormatterException | IOException e) {
outStream.println(e.getMessage());
exitError(this.exitWhenFinish);
}
}
private void validateInputFlags() throws CmdException, IOException {
if (inputPathFlag) {
if (argList == null) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_100, null);
}
} else {
getCommandUsageInfo();
exitError(this.exitWhenFinish);
return;
}
String filePath = argList.get(0);
if (!validInputFileExtension(filePath)) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_FOR_INVALID_FILE_EXTENSION, filePath));
}
}
private void executeOperation() throws CopybookTypeGenerationException, CmdException, FormatterException,
IOException {
String filePath = argList.get(0);
generateType(filePath);
}
private void generateType(String filePath)
throws CmdException, CopybookTypeGenerationException, FormatterException, IOException {
final File copybookFile = new File(filePath);
if (!copybookFile.exists()) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_FOR_INVALID_COPYBOOK_PATH, filePath));
}
if (!copybookFile.canRead()) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null,
String.format(Constants.MESSAGE_CAN_NOT_READ_COPYBOOK_FILE, filePath));
}
Path copybookFilePath = null;
try {
copybookFilePath = Paths.get(copybookFile.getCanonicalPath());
} catch (IOException e) {
throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.toString());
}
CodeGenerator.generate(copybookFilePath, getTargetOutputPath(), outStream);
}
private Path getTargetOutputPath() {
Path targetOutputPath = executionPath;
if (this.outputPath != null) {
if (Paths.get(outputPath).isAbsolute()) {
targetOutputPath = Paths.get(outputPath);
} else {
targetOutputPath = Paths.get(targetOutputPath.toString(), outputPath);
}
}
return targetOutputPath;
}
private boolean validInputFileExtension(String filePath) { | return filePath.endsWith(COPYBOOK_EXTENSION) || filePath.endsWith(COBOL_EXTENSION); | 6 | 2023-10-24 05:00:08+00:00 | 4k |
zhaoeryu/eu-backend | eu-quartz/src/main/java/cn/eu/quartz/job/AbstractQuartzJob.java | [
{
"identifier": "SpringContextHolder",
"path": "eu-common-core/src/main/java/cn/eu/common/utils/SpringContextHolder.java",
"snippet": "public class SpringContextHolder implements ApplicationContextAware {\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) {\n SpringContextHolder.applicationContext = applicationContext;\n }\n\n public static ApplicationContext getApplicationContext() {\n checkApplicationContext();\n return applicationContext;\n }\n\n public static Object getBean(String name) {\n checkApplicationContext();\n return applicationContext.getBean(name);\n }\n\n public static <T> T getBean(Class<T> clazz) {\n checkApplicationContext();\n return (T) applicationContext.getBean(clazz);\n }\n\n public static void clear() {\n applicationContext = null;\n }\n\n private static void checkApplicationContext() {\n if (applicationContext == null) {\n throw new IllegalStateException(\"applicationContext未注入Spring容器中\");\n }\n }\n} "
},
{
"identifier": "MailSendType",
"path": "eu-message-starter/src/main/java/cn/eu/message/enums/MailSendType.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum MailSendType {\n\n TEXT,\n HTML\n\n}"
},
{
"identifier": "MessageDispatcher",
"path": "eu-message-starter/src/main/java/cn/eu/message/handler/dispatcher/MessageDispatcher.java",
"snippet": "@Component\npublic class MessageDispatcher implements ApplicationContextAware {\n\n private Collection<IMessageExchange> exchanges;\n\n public void dispatch(Message message) {\n for (IMessageExchange exchange : exchanges) {\n if (exchange.support(message)) {\n exchange.exchange(message);\n return;\n }\n }\n throw new NotMatchExchangeException(String.format(\"[%s]未实现exchange\", message.getClass()));\n }\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.exchanges = applicationContext.getBeansOfType(IMessageExchange.class).values();\n }\n}"
},
{
"identifier": "Mail",
"path": "eu-message-starter/src/main/java/cn/eu/message/model/Mail.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class Mail extends Message {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 发送给谁\n */\n private String to;\n\n /**\n * 发送主题\n */\n private String subject;\n\n /**\n * 发送内容\n */\n private String content;\n\n /**\n * 抄送人\n */\n private String[] cc;\n\n /**\n * 密送\n */\n private String[] bcc;\n\n /**\n * 附件\n */\n private List<MailAttachment> attachmentList;\n\n /**\n * 发送方式\n * @see cn.eu.message.enums.MailSendType\n */\n private MailSendType sendType;\n}"
},
{
"identifier": "QuartzConstants",
"path": "eu-quartz/src/main/java/cn/eu/quartz/QuartzConstants.java",
"snippet": "public class QuartzConstants {\n\n public static final String JOB_NAME = \"EU_TASK_\";\n public static final String JOB_DATA_KEY = \"EU_TASK_DATA\";\n\n}"
},
{
"identifier": "QuartzJob",
"path": "eu-quartz/src/main/java/cn/eu/quartz/domain/QuartzJob.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class QuartzJob extends BaseEntity {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 任务ID\n */\n private String id;\n /**\n * 任务名称\n */\n private String jobName;\n /**\n * 任务组\n */\n private String jobGroup;\n /**\n * cron表达式\n */\n private String cron;\n /**\n * 任务状态\n * @see QuartzJobStatus#getValue()\n */\n private Integer status;\n /**\n * 执行策略\n * @see QuartzJobMisfirePolicy#getValue()\n */\n private Integer misfirePolicy;\n /**\n * 是否允许并发\n * @see cn.eu.quartz.enums.QuartzJobConcurrent#getValue()\n */\n private Integer concurrent;\n\n /**\n * 任务执行类\n */\n private String invokeClassName;\n /**\n * 任务执行类的SpringBean名\n */\n private String springBeanName;\n /**\n * 任务执行方法\n */\n private String methodName;\n /**\n * 任务执行方法参数\n */\n private String methodParams;\n /**\n * 失败后是否暂停\n */\n private Boolean pauseAfterFailure;\n /**\n * 任务失败后的告警邮箱\n */\n private String alarmEmail;\n\n}"
},
{
"identifier": "QuartzJobLog",
"path": "eu-quartz/src/main/java/cn/eu/quartz/domain/QuartzJobLog.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class QuartzJobLog extends BaseEntity {\n\n private static final long serialVersionUID = 1L;\n\n @TableId\n @ExcelProperty(\"ID\")\n private String id;\n /**\n * 任务ID\n */\n @ExcelProperty(\"任务ID\")\n private String jobId;\n /**\n * 任务名称\n */\n @ExcelProperty(\"任务名称\")\n private String jobName;\n /**\n * 任务执行类\n */\n @ExcelProperty(\"任务执行类\")\n private String invokeClassName;\n /**\n * 任务执行类的SpringBean名\n */\n @ExcelProperty(\"任务执行类的SpringBean名\")\n private String springBeanName;\n /**\n * 任务执行方法\n */\n @ExcelProperty(\"任务执行方法\")\n private String methodName;\n /**\n * 任务执行方法参数\n */\n @ExcelProperty(\"任务执行方法参数\")\n private String methodParams;\n\n /**\n * 是否执行成功\n */\n @ExcelProperty(\"是否执行成功\")\n private Boolean success;\n\n /**\n * 异常消息\n */\n @ExcelProperty(\"异常消息\")\n private String exceptionMessage;\n /**\n * 异常详情\n */\n @ExcelProperty(\"异常详情\")\n private String exceptionDetail;\n\n /**\n * 开始执行时间\n */\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ExcelProperty(\"开始执行时间\")\n private LocalDateTime startTime;\n\n /**\n * 结束执行时间\n */\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ExcelProperty(\"结束执行时间\")\n private LocalDateTime endTime;\n\n /**\n * 执行时长,单位:毫秒\n */\n @ExcelProperty(\"执行时长(ms)\")\n private Long execTime;\n\n}"
},
{
"identifier": "QuartzJobStatus",
"path": "eu-quartz/src/main/java/cn/eu/quartz/enums/QuartzJobStatus.java",
"snippet": "@AllArgsConstructor\n@Getter\npublic enum QuartzJobStatus {\n\n /**\n * 正常\n */\n NORMAL(0),\n /**\n * 暂停\n */\n PAUSE(1);\n\n private final int value;\n\n}"
},
{
"identifier": "IQuartzJobLogService",
"path": "eu-quartz/src/main/java/cn/eu/quartz/service/IQuartzJobLogService.java",
"snippet": "public interface IQuartzJobLogService extends IEuService<QuartzJobLog> {\n\n PageResult<QuartzJobLog> page(QuartzJobLogQueryCriteria criteria, Pageable pageable);\n\n List<QuartzJobLog> list(QuartzJobLogQueryCriteria criteria);\n\n}"
},
{
"identifier": "IQuartzJobService",
"path": "eu-quartz/src/main/java/cn/eu/quartz/service/IQuartzJobService.java",
"snippet": "public interface IQuartzJobService extends IEuService<QuartzJob> {\n\n PageResult<QuartzJob> page(QuartzJobQueryCriteria criteria, Pageable pageable);\n\n List<QuartzJob> list(QuartzJobQueryCriteria criteria);\n \n /**\n * 暂停或者恢复任务\n */\n void pauseOrResume(QuartzJob quartzJob);\n\n void exec(String jobId);\n\n void deleteJob(String jobId);\n\n void deleteJobs(List<String> jobIds);\n\n void updateJob(QuartzJob entity);\n\n void saveJob(QuartzJob entity);\n}"
}
] | import cn.eu.common.utils.SpringContextHolder;
import cn.eu.message.enums.MailSendType;
import cn.eu.message.handler.dispatcher.MessageDispatcher;
import cn.eu.message.model.Mail;
import cn.eu.quartz.QuartzConstants;
import cn.eu.quartz.domain.QuartzJob;
import cn.eu.quartz.domain.QuartzJobLog;
import cn.eu.quartz.enums.QuartzJobStatus;
import cn.eu.quartz.service.IQuartzJobLogService;
import cn.eu.quartz.service.IQuartzJobService;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.Assert;
import java.time.Duration;
import java.time.LocalDateTime; | 2,943 | package cn.eu.quartz.job;
/**
* @author zhaoeryu
* @since 2023/6/13
*/
@Slf4j
public abstract class AbstractQuartzJob extends QuartzJobBean {
private static final ThreadLocal<LocalDateTime> THREAD_LOCAL = new ThreadLocal<>();
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// public void execute(JobExecutionContext context) throws JobExecutionException {
QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzConstants.JOB_DATA_KEY);
log.info("--------------------------------------");
log.info("[{}]任务开始执行", quartzJob.getJobName());
try {
before(context, quartzJob);
doExecute(context, quartzJob);
after(context, quartzJob, null);
} catch (Exception e) {
log.error("任务执行异常: " + e.getMessage(), e);
after(context, quartzJob, e);
}
log.info("[{}]任务执行结束", quartzJob.getJobName());
}
protected void before(JobExecutionContext context, QuartzJob quartzJob) {
THREAD_LOCAL.set(LocalDateTime.now());
}
protected void after(JobExecutionContext context, QuartzJob quartzJob, Exception e) {
LocalDateTime startTime = THREAD_LOCAL.get();
THREAD_LOCAL.remove();
LocalDateTime endTime = LocalDateTime.now();
long execMs = Duration.between(startTime, endTime).toMillis();
log.info("任务名称 = [{}],任务组名 = [{}],执行耗时 = [{}]毫秒",
quartzJob.getJobName(), quartzJob.getJobGroup(), execMs);
IQuartzJobService quartzJobService = SpringContextHolder.getBean(IQuartzJobService.class);
QuartzJobLog quartzJobLog = new QuartzJobLog();
quartzJobLog.setJobId(quartzJob.getId());
quartzJobLog.setJobName(quartzJob.getJobName());
quartzJobLog.setSpringBeanName(quartzJob.getSpringBeanName());
quartzJobLog.setMethodName(quartzJob.getMethodName());
quartzJobLog.setMethodParams(quartzJob.getMethodParams());
quartzJobLog.setSuccess(e == null);
if (e != null) {
quartzJobLog.setExceptionMessage(e.getMessage());
quartzJobLog.setExceptionDetail(ExceptionUtil.stacktraceToString(e));
// 如果失败了需要暂停
if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) {
quartzJob.setStatus(QuartzJobStatus.PAUSE.getValue());
quartzJobService.pauseOrResume(quartzJob);
}
// 如果配置了邮箱,任务失败发送邮件
if (StrUtil.isNotBlank(quartzJob.getAlarmEmail())) {
try {
// send email
MessageDispatcher dispatcher = SpringContextHolder.getBean(MessageDispatcher.class);
Mail mail = new Mail();
mail.setTo(quartzJob.getAlarmEmail());
mail.setSubject("任务执行失败 - [" + quartzJob.getJobName() + "]");
mail.setContent(quartzJobLog.getExceptionDetail());
mail.setSendType(MailSendType.TEXT);
dispatcher.dispatch(mail);
} catch (Exception emailEx) {
log.error("发送邮件失败:" + emailEx.getMessage(), emailEx);
}
}
}
quartzJobLog.setStartTime(startTime);
quartzJobLog.setEndTime(endTime);
quartzJobLog.setExecTime(execMs);
// save log to database | package cn.eu.quartz.job;
/**
* @author zhaoeryu
* @since 2023/6/13
*/
@Slf4j
public abstract class AbstractQuartzJob extends QuartzJobBean {
private static final ThreadLocal<LocalDateTime> THREAD_LOCAL = new ThreadLocal<>();
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// public void execute(JobExecutionContext context) throws JobExecutionException {
QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzConstants.JOB_DATA_KEY);
log.info("--------------------------------------");
log.info("[{}]任务开始执行", quartzJob.getJobName());
try {
before(context, quartzJob);
doExecute(context, quartzJob);
after(context, quartzJob, null);
} catch (Exception e) {
log.error("任务执行异常: " + e.getMessage(), e);
after(context, quartzJob, e);
}
log.info("[{}]任务执行结束", quartzJob.getJobName());
}
protected void before(JobExecutionContext context, QuartzJob quartzJob) {
THREAD_LOCAL.set(LocalDateTime.now());
}
protected void after(JobExecutionContext context, QuartzJob quartzJob, Exception e) {
LocalDateTime startTime = THREAD_LOCAL.get();
THREAD_LOCAL.remove();
LocalDateTime endTime = LocalDateTime.now();
long execMs = Duration.between(startTime, endTime).toMillis();
log.info("任务名称 = [{}],任务组名 = [{}],执行耗时 = [{}]毫秒",
quartzJob.getJobName(), quartzJob.getJobGroup(), execMs);
IQuartzJobService quartzJobService = SpringContextHolder.getBean(IQuartzJobService.class);
QuartzJobLog quartzJobLog = new QuartzJobLog();
quartzJobLog.setJobId(quartzJob.getId());
quartzJobLog.setJobName(quartzJob.getJobName());
quartzJobLog.setSpringBeanName(quartzJob.getSpringBeanName());
quartzJobLog.setMethodName(quartzJob.getMethodName());
quartzJobLog.setMethodParams(quartzJob.getMethodParams());
quartzJobLog.setSuccess(e == null);
if (e != null) {
quartzJobLog.setExceptionMessage(e.getMessage());
quartzJobLog.setExceptionDetail(ExceptionUtil.stacktraceToString(e));
// 如果失败了需要暂停
if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) {
quartzJob.setStatus(QuartzJobStatus.PAUSE.getValue());
quartzJobService.pauseOrResume(quartzJob);
}
// 如果配置了邮箱,任务失败发送邮件
if (StrUtil.isNotBlank(quartzJob.getAlarmEmail())) {
try {
// send email
MessageDispatcher dispatcher = SpringContextHolder.getBean(MessageDispatcher.class);
Mail mail = new Mail();
mail.setTo(quartzJob.getAlarmEmail());
mail.setSubject("任务执行失败 - [" + quartzJob.getJobName() + "]");
mail.setContent(quartzJobLog.getExceptionDetail());
mail.setSendType(MailSendType.TEXT);
dispatcher.dispatch(mail);
} catch (Exception emailEx) {
log.error("发送邮件失败:" + emailEx.getMessage(), emailEx);
}
}
}
quartzJobLog.setStartTime(startTime);
quartzJobLog.setEndTime(endTime);
quartzJobLog.setExecTime(execMs);
// save log to database | IQuartzJobLogService quartzJobLogService = SpringContextHolder.getBean(IQuartzJobLogService.class); | 8 | 2023-10-20 07:08:37+00:00 | 4k |
Nxer/Twist-Space-Technology-Mod | src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/BlockNuclearReactor.java | [
{
"identifier": "NuclearReactorBlock",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java",
"snippet": "public static Block NuclearReactorBlock = new BlockNuclearReactor(\"nuclear\", \"Mega Nuclear Reactor\");"
},
{
"identifier": "initMetaItemStack",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/MetaItemStackUtils.java",
"snippet": "public static ItemStack initMetaItemStack(String i18nName, int Meta, Item basicItem, Set<Integer> aContainerSet) {\n\n // Handle the Name\n texter(i18nName, basicItem.getUnlocalizedName() + \".\" + Meta + \".name\");\n // Hold the list of Meta-generated Items\n aContainerSet.add(Meta);\n\n return new ItemStack(basicItem, 1, Meta);\n}"
},
{
"identifier": "texter",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextHandler.java",
"snippet": "public static String texter(String aTextLine, String aKey) {\n\n /**\n * If not in Dev mode , return vanilla forge method directly.\n */\n if (TwistSpaceTechnology.isInDevMode) {\n if (LangMap.get(aKey) == null) {\n TwistSpaceTechnology.LOG.info(\"Texter get a new key - TextLine: \" + aKey + \" - \" + aTextLine);\n LangMapNeedToWrite.put(aKey, aTextLine);\n return aTextLine;\n } else {\n return translateToLocalFormatted(aKey);\n }\n } else if (null != translateToLocalFormatted(aKey)) {\n return translateToLocalFormatted(aKey);\n }\n return \"texterError: \" + aTextLine;\n}"
},
{
"identifier": "GTCMCreativeTabs",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/client/GTCMCreativeTabs.java",
"snippet": "public class GTCMCreativeTabs {\n\n /**\n * Creative Tab for MetaItem01\n */\n public static final CreativeTabs tabMetaItem01 = new CreativeTabs(\n texter(\"TST Meta Items 1\", \"itemGroup.TST Meta Items 1\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n public static final CreativeTabs tabGears = new CreativeTabs(texter(\"TSTGears\", \"itemGroup.TSTGears\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n /**\n * Creative Tab for MetaBlock01\n */\n public static final CreativeTabs tabMetaBlock01 = new CreativeTabs(\n texter(\"TST Meta Blocks 1\", \"itemGroup.TST Meta Blocks 1\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n /**\n * Creative Tab for MetaBlock01\n */\n public static final CreativeTabs tabGTCMGeneralTab = new CreativeTabs(texter(\"TST\", \"itemGroup.TST\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n public static final CreativeTabs tabMultiStructures = new CreativeTabs(\n texter(\"MultiStructures\", \"itemGroup.MultiStructures\")) {\n\n @Override\n @SideOnly(Side.CLIENT)\n public Item getTabIconItem() {\n return BasicItems.MetaItem01;\n }\n };\n\n}"
},
{
"identifier": "BlockBase01",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockBase01.java",
"snippet": "public class BlockBase01 extends Block {\n\n // region Constructors\n protected BlockBase01(Material materialIn) {\n super(materialIn);\n }\n\n public BlockBase01() {\n this(Material.iron);\n this.setCreativeTab(GTCMCreativeTabs.tabMetaBlock01);\n }\n\n public BlockBase01(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, \"blockBase01.\" + unlocalizedName + \".name\");\n }\n\n // endregion\n // -----------------------\n // region member variables\n\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region getters\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region setters\n\n public void setUnlocalizedName(String aUnlocalizedName) {\n this.unlocalizedName = aUnlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region Overrides\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < BlockStaticDataClientOnly.iconsBlockMap01.size()\n ? BlockStaticDataClientOnly.iconsBlockMap01.get(meta)\n : BlockStaticDataClientOnly.iconsBlockMap01.get(0);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/0\");\n for (int Meta : MetaBlockSet01) {\n BlockStaticDataClientOnly.iconsBlockMap01\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/\" + Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : MetaBlockSet01) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n public int damageDropped(int meta) {\n return meta;\n }\n\n @Override\n public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n @Override\n public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) {\n return false;\n }\n\n @Override\n public boolean canCreatureSpawn(EnumCreatureType type, IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n // endregion\n}"
},
{
"identifier": "BlockStaticDataClientOnly",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockStaticDataClientOnly.java",
"snippet": "@SideOnly(Side.CLIENT)\npublic class BlockStaticDataClientOnly {\n\n @SideOnly(Side.CLIENT)\n public static Map<Integer, IIcon> iconsBlockMap01 = new HashMap<>();\n @SideOnly(Side.CLIENT)\n public static Map<Integer, IIcon> iconsBlockPhotonControllerUpgradeMap = new HashMap<>();\n @SideOnly(Side.CLIENT)\n public static Map<Integer, IIcon> iconsSpaceStationAntiGravityCasingMap = new HashMap<>();\n @SideOnly(Side.CLIENT)\n public static Map<Integer, IIcon> iconsSpaceStationStructureCasingMap = new HashMap<>();\n @SideOnly(Side.CLIENT)\n public static Map<Integer, IIcon> iconsNuclearReactor = new HashMap<>();\n\n}"
},
{
"identifier": "ItemBlockBase01",
"path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/ItemBlockBase01.java",
"snippet": "public class ItemBlockBase01 extends ItemBlock {\n\n // region statics\n\n public static final Map<Integer, String[]> MetaBlockTooltipsMap01 = new HashMap<>();\n // public static final Map<Integer, ItemStack> MetaBlockMap01 = new HashMap<>();\n public static final Set<Integer> MetaBlockSet01 = new HashSet<>();\n\n // endregion\n // -----------------------\n // region Constructors\n\n public ItemBlockBase01(Block aBlock) {\n super(aBlock);\n setHasSubtypes(true);\n setMaxDamage(0);\n this.setCreativeTab(GTCMCreativeTabs.tabMetaBlock01);\n }\n\n // endregion\n // -----------------------\n // region MetaBlock Generators\n\n public static ItemStack initMetaBlock01(String i18nName, int Meta) {\n return initMetaItemStack(i18nName, Meta, MetaBlock01, MetaBlockSet01);\n }\n\n public static ItemStack initMetaBlock01(String i18nName, int Meta, String[] tooltips) {\n if (tooltips != null) {\n metaItemStackTooltipsAdd(MetaBlockTooltipsMap01, Meta, tooltips);\n }\n return initMetaBlock01(i18nName, Meta);\n }\n\n // endregion\n // -----------------------\n // region Member Variables\n\n public final String mNoMobsToolTip = GT_LanguageManager\n .addStringLocalization(\"gt.nomobspawnsonthisblock\", \"Mobs cannot Spawn on this Block\");\n public final String mNoTileEntityToolTip = GT_LanguageManager\n .addStringLocalization(\"gt.notileentityinthisblock\", \"This is NOT a TileEntity!\");\n\n // endregion\n // -----------------------\n // region Overrides\n\n /**\n * Handle the tooltips.\n *\n * @param aItemStack\n * @param theTooltipsList\n */\n @SideOnly(Side.CLIENT)\n @Override\n @SuppressWarnings({ \"unchecked\" })\n public void addInformation(ItemStack aItemStack, EntityPlayer p_77624_2_, List theTooltipsList,\n boolean p_77624_4_) {\n int meta = aItemStack.getItemDamage();\n if (null != MetaBlockTooltipsMap01.get(meta)) {\n String[] tooltips = MetaBlockTooltipsMap01.get(meta);\n theTooltipsList.addAll(Arrays.asList(tooltips));\n }\n theTooltipsList.add(mNoMobsToolTip);\n theTooltipsList.add(mNoTileEntityToolTip);\n }\n\n @Override\n public String getUnlocalizedName(ItemStack aStack) {\n return this.field_150939_a.getUnlocalizedName() + \".\" + this.getDamage(aStack);\n }\n\n @Override\n public int getMetadata(int aMeta) {\n return aMeta;\n }\n\n // endregion\n}"
}
] | import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.NuclearReactorBlock;
import static com.Nxer.TwistSpaceTechnology.util.MetaItemStackUtils.initMetaItemStack;
import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import com.Nxer.TwistSpaceTechnology.client.GTCMCreativeTabs;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockBase01;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStaticDataClientOnly;
import com.Nxer.TwistSpaceTechnology.common.block.blockClass.ItemBlockBase01;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | 2,974 | package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings;
public class BlockNuclearReactor extends BlockBase01 {
public BlockNuclearReactor(String unlocalizedName, String localName) {
this.setUnlocalizedName(unlocalizedName);
texter(localName, unlocalizedName + ".name");
this.setHardness(9.0F);
this.setResistance(5.0F);
this.setHarvestLevel("wrench", 1);
this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);
NuclearReactorBlockSet.add(0);
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int meta) {
return meta < BlockStaticDataClientOnly.iconsNuclearReactor.size()
? BlockStaticDataClientOnly.iconsNuclearReactor.get(meta)
: BlockStaticDataClientOnly.iconsNuclearReactor.get(0);
}
public static class innerItemBlock extends ItemBlockBase01 {
public innerItemBlock(Block aBlock) {
super(aBlock);
}
}
public static final Set<Integer> NuclearReactorBlockSet = new HashSet<>();
public static ItemStack NuclearReactorBlockMeta(String i18nName, int meta) {
| package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings;
public class BlockNuclearReactor extends BlockBase01 {
public BlockNuclearReactor(String unlocalizedName, String localName) {
this.setUnlocalizedName(unlocalizedName);
texter(localName, unlocalizedName + ".name");
this.setHardness(9.0F);
this.setResistance(5.0F);
this.setHarvestLevel("wrench", 1);
this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);
NuclearReactorBlockSet.add(0);
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int meta) {
return meta < BlockStaticDataClientOnly.iconsNuclearReactor.size()
? BlockStaticDataClientOnly.iconsNuclearReactor.get(meta)
: BlockStaticDataClientOnly.iconsNuclearReactor.get(0);
}
public static class innerItemBlock extends ItemBlockBase01 {
public innerItemBlock(Block aBlock) {
super(aBlock);
}
}
public static final Set<Integer> NuclearReactorBlockSet = new HashSet<>();
public static ItemStack NuclearReactorBlockMeta(String i18nName, int meta) {
| return initMetaItemStack(i18nName, meta, NuclearReactorBlock, NuclearReactorBlockSet); | 1 | 2023-10-16 09:57:15+00:00 | 4k |
wyjsonGo/GoRouter | module_common/src/main/java/com/wyjson/module_common/route/service/PretreatmentServiceImpl.java | [
{
"identifier": "UserSignInActivityGoRouter",
"path": "module_common/src/main/java/com/wyjson/router/helper/module_user/group_user/UserSignInActivityGoRouter.java",
"snippet": "public class UserSignInActivityGoRouter {\n public static String getPath() {\n return \"/user/sign_in/activity\";\n }\n\n public static CardMeta getCardMeta() {\n return GoRouter.getInstance().build(getPath()).getCardMeta();\n }\n\n public static <T> void postEvent(T value) {\n GoRouter.getInstance().postEvent(getPath(), value);\n }\n\n public static Card build() {\n return GoRouter.getInstance().build(getPath());\n }\n\n public static void go() {\n build().go();\n }\n}"
},
{
"identifier": "IPretreatmentService",
"path": "GoRouter-Api/src/main/java/com/wyjson/router/interfaces/IPretreatmentService.java",
"snippet": "public interface IPretreatmentService extends IService {\n\n /**\n * 跳转前预处理\n *\n * @param context\n * @param card\n * @return true继续执行, 如果需要自行处理跳转该方法返回 false 即可\n */\n boolean onPretreatment(Context context, Card card);\n}"
},
{
"identifier": "Card",
"path": "GoRouter-Api/src/main/java/com/wyjson/router/model/Card.java",
"snippet": "public final class Card extends CardMeta {\n\n private Uri uri;\n private Bundle mBundle;\n private int flags = 0;\n private boolean greenChannel;// 绿色通道(跳过所有的拦截器)\n private String action;\n private Context context;\n private IJsonService jsonService;\n\n private int enterAnim = -1;// 转场动画\n private int exitAnim = -1;\n private ActivityOptionsCompat activityOptionsCompat;// 转场动画(API16+)\n\n private Throwable interceptorException;// 拦截执行中断异常信息\n private int timeout = 300;// go() timeout, TimeUnit.Second\n\n public void setUri(Uri uri) {\n if (uri == null || TextUtils.isEmpty(uri.toString()) || TextUtils.isEmpty(uri.getPath())) {\n throw new RouterException(\"uri Parameter is invalid!\");\n }\n this.uri = uri;\n setPath(uri.getPath());\n }\n\n public Uri getUri() {\n return uri;\n }\n\n public ActivityOptionsCompat getActivityOptionsCompat() {\n return activityOptionsCompat;\n }\n\n public int getEnterAnim() {\n return enterAnim;\n }\n\n public int getExitAnim() {\n return exitAnim;\n }\n\n public Card(Uri uri) {\n setUri(uri);\n this.mBundle = new Bundle();\n }\n\n public Card(String path, Bundle bundle) {\n setPath(path);\n this.mBundle = (null == bundle ? new Bundle() : bundle);\n }\n\n @Nullable\n public Object go() {\n return go(null, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context) {\n return go(context, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context, GoCallback callback) {\n return go(context, this, -1, null, callback);\n }\n\n @Nullable\n public Object go(Context context, int requestCode) {\n return go(context, this, requestCode, null, null);\n }\n\n @Nullable\n public Object go(Context context, int requestCode, GoCallback callback) {\n return go(context, this, requestCode, null, callback);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher) {\n return go(context, this, -1, activityResultLauncher, null);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return go(context, this, -1, activityResultLauncher, callback);\n }\n\n @Nullable\n private Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return GoRouter.getInstance().go(context, card, requestCode, activityResultLauncher, callback);\n }\n\n @Nullable\n public CardMeta getCardMeta() {\n try {\n return RouteCenter.getCardMeta(this);\n } catch (NoFoundRouteException e) {\n GoRouter.logger.warning(null, e.getMessage());\n }\n return null;\n }\n\n public void setCardMeta(RouteType type, Class<?> pathClass, int tag, boolean deprecated) {\n setType(type);\n setPathClass(pathClass);\n setTag(tag);\n setDeprecated(deprecated);\n }\n\n public Bundle getExtras() {\n return mBundle;\n }\n\n public Card with(Bundle bundle) {\n if (null != bundle) {\n mBundle = bundle;\n }\n return this;\n }\n\n public Card withFlags(int flag) {\n this.flags = flag;\n return this;\n }\n\n public Card addFlags(int flags) {\n this.flags |= flags;\n return this;\n }\n\n public int getFlags() {\n return flags;\n }\n\n /**\n * 使用 withObject 传递 List 和 Map 的实现了 Serializable 接口的实现类(ArrayList/HashMap)的时候,\n * 接收该对象的地方不能标注具体的实现类类型应仅标注为 List 或 Map,\n * 否则会影响序列化中类型的判断, 其他类似情况需要同样处理\n *\n * @param key\n * @param value\n * @return\n */\n public Card withObject(@Nullable String key, @Nullable Object value) {\n jsonService = GoRouter.getInstance().getService(IJsonService.class);\n if (jsonService == null) {\n throw new RouterException(\"To use withObject() method, you need to implement IJsonService\");\n }\n mBundle.putString(key, jsonService.toJson(value));\n return this;\n }\n\n public Card withString(@Nullable String key, @Nullable String value) {\n mBundle.putString(key, value);\n return this;\n }\n\n public Card withBoolean(@Nullable String key, boolean value) {\n mBundle.putBoolean(key, value);\n return this;\n }\n\n public Card withShort(@Nullable String key, short value) {\n mBundle.putShort(key, value);\n return this;\n }\n\n public Card withInt(@Nullable String key, int value) {\n mBundle.putInt(key, value);\n return this;\n }\n\n public Card withLong(@Nullable String key, long value) {\n mBundle.putLong(key, value);\n return this;\n }\n\n public Card withDouble(@Nullable String key, double value) {\n mBundle.putDouble(key, value);\n return this;\n }\n\n public Card withByte(@Nullable String key, byte value) {\n mBundle.putByte(key, value);\n return this;\n }\n\n public Card withChar(@Nullable String key, char value) {\n mBundle.putChar(key, value);\n return this;\n }\n\n public Card withFloat(@Nullable String key, float value) {\n mBundle.putFloat(key, value);\n return this;\n }\n\n public Card withCharSequence(@Nullable String key, @Nullable CharSequence value) {\n mBundle.putCharSequence(key, value);\n return this;\n }\n\n public Card withParcelable(@Nullable String key, @Nullable Parcelable value) {\n mBundle.putParcelable(key, value);\n return this;\n }\n\n public Card withParcelableArray(@Nullable String key, @Nullable Parcelable[] value) {\n mBundle.putParcelableArray(key, value);\n return this;\n }\n\n public Card withParcelableArrayList(@Nullable String key, @Nullable ArrayList<? extends Parcelable> value) {\n mBundle.putParcelableArrayList(key, value);\n return this;\n }\n\n public Card withSparseParcelableArray(@Nullable String key, @Nullable SparseArray<? extends Parcelable> value) {\n mBundle.putSparseParcelableArray(key, value);\n return this;\n }\n\n public Card withIntegerArrayList(@Nullable String key, @Nullable ArrayList<Integer> value) {\n mBundle.putIntegerArrayList(key, value);\n return this;\n }\n\n public Card withStringArrayList(@Nullable String key, @Nullable ArrayList<String> value) {\n mBundle.putStringArrayList(key, value);\n return this;\n }\n\n public Card withCharSequenceArrayList(@Nullable String key, @Nullable ArrayList<CharSequence> value) {\n mBundle.putCharSequenceArrayList(key, value);\n return this;\n }\n\n public Card withSerializable(@Nullable String key, @Nullable Serializable value) {\n mBundle.putSerializable(key, value);\n return this;\n }\n\n public Card withByteArray(@Nullable String key, @Nullable byte[] value) {\n mBundle.putByteArray(key, value);\n return this;\n }\n\n public Card withShortArray(@Nullable String key, @Nullable short[] value) {\n mBundle.putShortArray(key, value);\n return this;\n }\n\n public Card withCharArray(@Nullable String key, @Nullable char[] value) {\n mBundle.putCharArray(key, value);\n return this;\n }\n\n public Card withLongArray(@Nullable String key, @Nullable long[] value) {\n mBundle.putLongArray(key, value);\n return this;\n }\n\n public Card withIntArray(@Nullable String key, @Nullable int[] value) {\n mBundle.putIntArray(key, value);\n return this;\n }\n\n public Card withDoubleArray(@Nullable String key, @Nullable double[] value) {\n mBundle.putDoubleArray(key, value);\n return this;\n }\n\n public Card withBooleanArray(@Nullable String key, @Nullable boolean[] value) {\n mBundle.putBooleanArray(key, value);\n return this;\n }\n\n public Card withStringArray(@Nullable String key, @Nullable String[] value) {\n mBundle.putStringArray(key, value);\n return this;\n }\n\n public Card withFloatArray(@Nullable String key, @Nullable float[] value) {\n mBundle.putFloatArray(key, value);\n return this;\n }\n\n public Card withCharSequenceArray(@Nullable String key, @Nullable CharSequence[] value) {\n mBundle.putCharSequenceArray(key, value);\n return this;\n }\n\n public Card withBundle(@Nullable String key, @Nullable Bundle value) {\n mBundle.putBundle(key, value);\n return this;\n }\n\n public Card withTransition(int enterAnim, int exitAnim) {\n this.enterAnim = enterAnim;\n this.exitAnim = exitAnim;\n return this;\n }\n\n @RequiresApi(16)\n public Card withActivityOptionsCompat(ActivityOptionsCompat compat) {\n this.activityOptionsCompat = compat;\n return this;\n }\n\n public String getAction() {\n return action;\n }\n\n public Card withAction(String action) {\n this.action = action;\n return this;\n }\n\n public Context getContext() {\n return context;\n }\n\n public void setContext(Context context) {\n if (context == null) {\n throw new RouterException(\"Context cannot be empty, Call 'GoRouter.setApplication(...)' in application.\");\n }\n this.context = context;\n }\n\n public boolean isGreenChannel() {\n return greenChannel;\n }\n\n public Card greenChannel() {\n this.greenChannel = true;\n return this;\n }\n\n public Throwable getInterceptorException() {\n return interceptorException;\n }\n\n public void setInterceptorException(Throwable interceptorException) {\n this.interceptorException = interceptorException;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n /**\n * @param timeout Second\n */\n public Card setTimeout(int timeout) {\n this.timeout = timeout;\n return this;\n }\n\n @NonNull\n @Override\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n return \"Card{\" +\n \"path='\" + getPath() + '\\'' +\n \", uri=\" + uri +\n \", mBundle=\" + mBundle +\n \", flags=\" + flags +\n \", greenChannel=\" + greenChannel +\n \", action='\" + action + '\\'' +\n \", context=\" + (context != null ? context.getClass().getSimpleName() : null) +\n \", optionsCompat=\" + activityOptionsCompat +\n \", enterAnim=\" + enterAnim +\n \", exitAnim=\" + exitAnim +\n \", interceptorException=\" + interceptorException +\n \", timeout=\" + timeout +\n '}';\n }\n}"
}
] | import android.content.Context;
import android.content.Intent;
import com.wyjson.router.annotation.Service;
import com.wyjson.router.helper.module_user.group_user.UserSignInActivityGoRouter;
import com.wyjson.router.interfaces.IPretreatmentService;
import com.wyjson.router.model.Card; | 3,233 | package com.wyjson.module_common.route.service;
@Service(remark = "预处理服务")
public class PretreatmentServiceImpl implements IPretreatmentService {
@Override
public void init() {
}
@Override | package com.wyjson.module_common.route.service;
@Service(remark = "预处理服务")
public class PretreatmentServiceImpl implements IPretreatmentService {
@Override
public void init() {
}
@Override | public boolean onPretreatment(Context context, Card card) { | 2 | 2023-10-18 13:52:07+00:00 | 4k |
trpc-group/trpc-java | trpc-proto/trpc-proto-standard/src/test/java/com/tencent/trpc/proto/standard/clustertest/ClientFilterTest.java | [
{
"identifier": "Filter",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/filter/spi/Filter.java",
"snippet": "@Extensible\npublic interface Filter extends Ordered {\n\n /**\n * <pre> Note: For ClientFilter, the framework has copied the contents of RpcContext into Request#attachments.\n * For ServerFilter,\n * the framework will copy the contents of Request#attachments into ServerContext after the filter ends.\n * 1) In the implementation of Filter,\n * it is necessary to trigger invoker.invoke(RpcContext context, Request request)\n * to ensure that the call is propagated to the real method call.\n * 2) It is recommended to use the following when calling whenComplete:\n * <code>\n * CompletableFuture.whenComplete((r, t) -> {\n * Throwable e = ExceptionHelper.parseResponseException(r, t);\n * if(e != null && r != null) {\n * }\n * }\n * </code>\n * 3) When obtaining context information related to the method, use {@link Request#getInvocation()},\n * such as method name, method parameters, synchronous/asynchronous judgment, etc.\n * 4) When obtaining context information related to the request,\n * use {@link Request#getMeta()}, such as local address, remote address, timeout, whether it is oneway, etc.\n * 5) When obtaining context information of the request with attached parameters,\n * use {@link Request#getAttachments()} | {@link Request#getAttachments()} ()}\n * to obtain business pass-through parameters.\n * 6) When obtaining context information of the response with attached parameters,\n * use {@link Response#getAttachments()} | {@link Response#getAttachments()} ()}\n * to obtain business pass-through parameters.\n * 7) To get the context, use {@link Request#getContext()}}\n * 8) Note: In the oneway scenario, Response is null, so be sure to check for null. </pre>\n *\n * @param filterChain the filter chain\n * @param req the request\n * @return the response\n */\n CompletionStage<Response> filter(Invoker<?> filterChain, Request req);\n\n}"
},
{
"identifier": "CallInfo",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/CallInfo.java",
"snippet": "public class CallInfo implements Cloneable {\n\n private String caller = \"\";\n /**\n * Caller application name.\n */\n private String callerApp = \"\";\n /**\n * Caller server name.\n */\n private String callerServer = \"\";\n /**\n * Caller service.\n */\n private String callerService = \"\";\n /**\n * Caller method name.\n */\n private String callerMethod = \"\";\n /**\n * Caller container name.\n */\n private String callerContainerName = \"\";\n /**\n * Caller set name.\n */\n private String callerSetName = \"\";\n private String callee = \"\";\n /**\n * Callee application name.\n */\n private String calleeApp = \"\";\n /**\n * Callee server name.\n */\n private String calleeServer = \"\";\n /**\n * Callee service.\n */\n private String calleeService = \"\";\n /**\n * Callee method name.\n */\n private String calleeMethod = \"\";\n /**\n * Callee container name.\n */\n private String calleeContainerName = \"\";\n /**\n * Callee set name.\n */\n private String calleeSetName = \"\";\n\n public CallInfo clone() {\n CallInfo clone = null;\n try {\n clone = (CallInfo) super.clone();\n } catch (CloneNotSupportedException e) {\n throw new RuntimeException(\"\", e);\n }\n return clone;\n }\n\n @Override\n public String toString() {\n return \"CallInfo {caller=\" + caller + \", callerApp=\" + callerApp + \", callerServer=\"\n + callerServer + \", callerService=\" + callerService + \", callerMethod=\"\n + callerMethod\n + \", callee=\" + callee + \", calleeApp=\" + calleeApp + \", calleeServer=\"\n + calleeServer\n + \", calleeService=\" + calleeService + \", calleeMethod=\" + calleeMethod + \"}\";\n }\n\n public String getCaller() {\n return caller;\n }\n\n public CallInfo setCaller(String caller) {\n this.caller = caller != null ? caller : \"\";\n return this;\n }\n\n public String getCallee() {\n return callee;\n }\n\n public CallInfo setCallee(String callee) {\n this.callee = callee != null ? callee : \"\";\n return this;\n }\n\n public String getCalleeApp() {\n return calleeApp;\n }\n\n public CallInfo setCalleeApp(String calleeApp) {\n this.calleeApp = calleeApp != null ? calleeApp : \"\";\n return this;\n }\n\n public String getCallerApp() {\n return callerApp;\n }\n\n public CallInfo setCallerApp(String callerApp) {\n this.callerApp = callerApp != null ? callerApp : \"\";\n return this;\n }\n\n public String getCallerServer() {\n return callerServer;\n }\n\n public CallInfo setCallerServer(String callerServer) {\n this.callerServer = callerServer != null ? callerServer : \"\";\n return this;\n }\n\n public String getCallerService() {\n return callerService;\n }\n\n public CallInfo setCallerService(String callerService) {\n this.callerService = callerService != null ? callerService : \"\";\n return this;\n }\n\n public String getCallerMethod() {\n return callerMethod;\n }\n\n public CallInfo setCallerMethod(String callerMethod) {\n this.callerMethod = callerMethod != null ? callerMethod : \"\";\n return this;\n }\n\n public String getCallerContainerName() {\n return callerContainerName;\n }\n\n public void setCallerContainerName(String callerContainerName) {\n this.callerContainerName = callerContainerName;\n }\n\n public String getCallerSetName() {\n return callerSetName;\n }\n\n public void setCallerSetName(String callerSetName) {\n this.callerSetName = callerSetName;\n }\n\n public String getCalleeServer() {\n return calleeServer;\n }\n\n public CallInfo setCalleeServer(String calleeServer) {\n this.calleeServer = calleeServer != null ? calleeServer : \"\";\n return this;\n }\n\n public String getCalleeService() {\n return calleeService;\n }\n\n public CallInfo setCalleeService(String calleeService) {\n this.calleeService = calleeService != null ? calleeService : \"\";\n return this;\n }\n\n public String getCalleeMethod() {\n return calleeMethod;\n }\n\n public CallInfo setCalleeMethod(String calleeMethod) {\n this.calleeMethod = calleeMethod != null ? calleeMethod : \"\";\n return this;\n }\n\n public String getCalleeContainerName() {\n return calleeContainerName;\n }\n\n public void setCalleeContainerName(String calleeContainerName) {\n this.calleeContainerName = calleeContainerName;\n }\n\n public String getCalleeSetName() {\n return calleeSetName;\n }\n\n public void setCalleeSetName(String calleeSetName) {\n this.calleeSetName = calleeSetName;\n }\n\n}"
},
{
"identifier": "Invoker",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/Invoker.java",
"snippet": "public interface Invoker<T> {\n\n /**\n * Get the callee interface.\n */\n Class<T> getInterface();\n\n /***\n * Abstract method invocation, do not return null.\n */\n CompletionStage<Response> invoke(Request request);\n\n}"
},
{
"identifier": "Request",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/Request.java",
"snippet": "public interface Request extends Cloneable {\n\n long getRequestId();\n\n /**\n * Request ID, the framework sends requests using int type, and receives requests for compatibility with other\n * protocols that may be long.\n */\n void setRequestId(long requestId);\n\n RequestMeta getMeta();\n\n /**\n * Request-related metadata information, mainly used by the framework.\n */\n void setMeta(RequestMeta meta);\n\n /**\n * Get data and method-related information. When the server decodes into a Request, it needs to set 1) method\n * routing information rpcServiceName & rpcMethodName for framework routing, 2) Set argument to represent data,\n * method parameters.\n */\n RpcInvocation getInvocation();\n\n void setInvocation(RpcInvocation invocation);\n\n /**\n * Protocol additional information, similar to the trans_info field in TRPC, supports two setting methods:\n * attachments as a map, attachObj as a protocol-defined structure for easy user setting.\n */\n Map<String, Object> getAttachments();\n\n void setAttachments(Map<String, Object> map);\n\n Object putAttachment(String key, Object value);\n\n Object getAttachment(String key);\n\n Object removeAttachment(String key);\n\n /**\n * Attached request header, each protocol is defined by itself, and the server can get it when receiving\n * the package.\n */\n <T> T getAttachReqHead();\n\n void setAttachReqHead(Object attachHead);\n\n /**\n * Carry context, ClientContext for client, and ServerContext for server.\n */\n RpcContext getContext();\n\n void setContext(RpcContext context);\n\n Request clone();\n\n}"
},
{
"identifier": "Response",
"path": "trpc-core/src/main/java/com/tencent/trpc/core/rpc/Response.java",
"snippet": "public interface Response extends Cloneable {\n\n /**\n * Request id, the same as RequestId in Request.\n */\n long getRequestId();\n\n /**\n * Data responded by the server.\n */\n Object getValue();\n\n void setValue(Object object);\n\n ResponseMeta getMeta();\n\n /**\n * Set ResponseMeta.\n */\n void setMeta(ResponseMeta meta);\n\n Throwable getException();\n\n void setException(Throwable exception);\n\n /**\n * Get the request corresponding to the response.\n */\n <T extends Request> T getRequest();\n\n /**\n * Set request, usually set when receiving a package.\n */\n void setRequest(Request request);\n\n /**\n * Protocol attached information, fields that need to be passed through, similar to the trans_info field in tRpc,\n * support two setting methods: attachements as map, attachObj as protocol-defined structure.\n */\n Map<String, Object> getAttachments();\n\n /**\n * Set pass-through map.\n *\n * @param map\n */\n void setAttachments(Map<String, Object> map);\n\n /**\n * Set a value.\n *\n * @param key\n * @param value\n * @return\n */\n Object putAttachment(String key, Object value);\n\n /**\n * Get the value of a key.\n *\n * @param key\n * @return\n */\n Object getAttachment(String key);\n\n /**\n * Remove a key.\n *\n * @param key\n * @return\n */\n Object removeAttachment(String key);\n\n /**\n * Attached response header, each protocol is defined by itself, and the client can get it when receiving\n * the package.\n */\n <T> T getAttachRspHead();\n\n void setAttachRspHead(Object attachRspHead);\n\n Response clone();\n\n /**\n * Get attachments sent by the server.\n */\n byte[] getResponseUncodecDataSegment();\n\n /**\n * Store attachments.\n */\n void setResponseUncodecDataSegment(byte[] dataSegment);\n\n}"
}
] | import static org.junit.Assert.assertEquals;
import com.tencent.trpc.core.filter.spi.Filter;
import com.tencent.trpc.core.rpc.CallInfo;
import com.tencent.trpc.core.rpc.Invoker;
import com.tencent.trpc.core.rpc.Request;
import com.tencent.trpc.core.rpc.Response;
import java.util.concurrent.CompletionStage;
import org.junit.Assert; | 3,061 | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.proto.standard.clustertest;
public class ClientFilterTest implements Filter {
@Override | /*
* Tencent is pleased to support the open source community by making tRPC available.
*
* Copyright (C) 2023 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* If you have downloaded a copy of the tRPC source code from Tencent,
* please note that tRPC source code is licensed under the Apache 2.0 License,
* A copy of the Apache 2.0 License can be found in the LICENSE file.
*/
package com.tencent.trpc.proto.standard.clustertest;
public class ClientFilterTest implements Filter {
@Override | public CompletionStage<Response> filter(Invoker<?> filterChain, Request req) { | 3 | 2023-10-19 10:54:11+00:00 | 4k |
freedom-introvert/YouTubeSendCommentAntiFraud | YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/ToBeCheckedCommentsAdapter.java | [
{
"identifier": "ToBeCheckedComment",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/ToBeCheckedComment.java",
"snippet": "public class ToBeCheckedComment extends Comment{\r\n public static final int COMMENT_SECTION_TYPE_VIDEO = 1;\r\n\r\n public String sourceId;\r\n public int commentSectionType;\r\n public String repliedCommentId;\r\n public String repliedCommentText;\r\n public byte[] context1;\r\n public Date sendTime;\r\n\r\n public ToBeCheckedComment(String commentId, String commentText, String sourceId, int commentSectionType, String repliedCommentId, String repliedCommentText, byte[] context1,Date sendTime) {\r\n this.commentId = commentId;\r\n this.commentText = commentText;\r\n this.sourceId = sourceId;\r\n this.commentSectionType = commentSectionType;\r\n this.repliedCommentId = repliedCommentId;\r\n this.repliedCommentText = repliedCommentText;\r\n this.context1 = context1;\r\n this.sendTime = sendTime;\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendTime);\r\n }\r\n\r\n\r\n\r\n}\r"
},
{
"identifier": "StatisticsDB",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/db/StatisticsDB.java",
"snippet": "public class StatisticsDB extends SQLiteOpenHelper {\r\n public static final String TABLE_NAME_VIDEO_HISTORY_COMMENTS = \"history_comments_from_video\";\r\n private static final String TABLE_NAME_TO_BE_CHECKED_COMMENTS = \"to_be_checked_comments\";\r\n SQLiteDatabase db;\r\n\r\n public static final int DB_VERSION = 1;\r\n\r\n public StatisticsDB(@Nullable Context context) {\r\n super(context, \"statistics\", null, DB_VERSION);\r\n db = getWritableDatabase();\r\n }\r\n\r\n @Override\r\n public void onCreate(SQLiteDatabase db) {\r\n db.execSQL(\"CREATE TABLE history_comments_from_video ( comment_id TEXT PRIMARY KEY UNIQUE NOT NULL, comment_text TEXT NOT NULL,anchor_comment_id TEXT,anchor_comment_text TEXT, video_id TEXT NOT NULL, state TEXT NOT NULL,send_date INTEGER NOT NULL,replied_comment_id TEXT,replied_comment_text TEXT ); \");\r\n db.execSQL(\"CREATE TABLE to_be_checked_comments ( comment_id TEXT PRIMARY KEY NOT NULL UNIQUE, comment_text TEXT NOT NULL, source_id TEXT NOT NULL, comment_section_type INTEGER NOT NULL, replied_comment_id TEXT, replied_comment_text TEXT, context1 BLOB NOT NULL ,send_time INTEGER NOT NULL);\");\r\n }\r\n\r\n @Override\r\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n\r\n }\r\n\r\n public long insertVideoHistoryComment(VideoHistoryComment comment){\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n if (comment.anchorComment != null) {\r\n v.put(\"anchor_comment_id\", comment.anchorComment.commentId);\r\n v.put(\"anchor_comment_text\", comment.anchorComment.commentText);\r\n }\r\n v.put(\"video_id\", comment.videoId);\r\n v.put(\"state\", comment.state);\r\n v.put(\"send_date\", comment.sendDate.getTime());\r\n if (comment.repliedComment != null) {\r\n v.put(\"replied_comment_id\", comment.repliedComment.commentId);\r\n v.put(\"replied_comment_text\", comment.repliedComment.commentText);\r\n }\r\n return db.insert(TABLE_NAME_VIDEO_HISTORY_COMMENTS,null,v);\r\n }\r\n\r\n @SuppressLint(\"Range\")\r\n public List<VideoHistoryComment> queryAllVideoHistoryComments(){\r\n List<VideoHistoryComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"anchor_comment_id\", \"anchor_comment_text\", \"video_id\", \"state\", \"send_date\", \"replied_comment_id\", \"replied_comment_text\"};\r\n Cursor cursor = db.query(\"history_comments_from_video\", columns, null, null, null, null, null);\r\n\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String anchorCommentId = cursor.getString(cursor.getColumnIndex(\"anchor_comment_id\"));\r\n String anchorCommentText = cursor.getString(cursor.getColumnIndex(\"anchor_comment_text\"));\r\n String videoId = cursor.getString(cursor.getColumnIndex(\"video_id\"));\r\n String state = cursor.getString(cursor.getColumnIndex(\"state\"));\r\n long sendDate = cursor.getLong(cursor.getColumnIndex(\"send_date\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n VideoHistoryComment comment = new VideoHistoryComment(commentId, commentText, anchorCommentId, anchorCommentText, videoId, state, sendDate, repliedCommentId, repliedCommentText);\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteVideoHistoryComment(String commentId) {\r\n return db.delete(TABLE_NAME_VIDEO_HISTORY_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n public void insertToBeCheckedComment(ToBeCheckedComment comment) {\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n v.put(\"source_id\", comment.sourceId);\r\n v.put(\"comment_section_type\", comment.commentSectionType);\r\n v.put(\"replied_comment_id\", comment.repliedCommentId);\r\n v.put(\"replied_comment_text\", comment.repliedCommentText);\r\n v.put(\"context1\", comment.context1);\r\n v.put(\"send_time\",comment.sendTime.getTime());\r\n db.insert(TABLE_NAME_TO_BE_CHECKED_COMMENTS, null, v);\r\n }\r\n @SuppressLint(\"Range\")\r\n public List<ToBeCheckedComment> getAllToBeCheckedComments() {\r\n List<ToBeCheckedComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"source_id\", \"comment_section_type\", \"replied_comment_id\", \"replied_comment_text\", \"context1\",\"send_time\"};\r\n Cursor cursor = db.query(\"to_be_checked_comments\", columns, null, null, null, null, null);\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String sourceId = cursor.getString(cursor.getColumnIndex(\"source_id\"));\r\n int commentSectionType = cursor.getInt(cursor.getColumnIndex(\"comment_section_type\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n byte[] context1 = cursor.getBlob(cursor.getColumnIndex(\"context1\"));\r\n long sendTime = cursor.getLong(cursor.getColumnIndex(\"send_time\"));\r\n ToBeCheckedComment comment = new ToBeCheckedComment(commentId, commentText, sourceId, commentSectionType, repliedCommentId, repliedCommentText, context1,new Date(sendTime));\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteToBeCheckedComment(String commentId){\r\n return db.delete(TABLE_NAME_TO_BE_CHECKED_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n}\r"
},
{
"identifier": "VoidDialogInterfaceOnClickListener",
"path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/VoidDialogInterfaceOnClickListener.java",
"snippet": "public class VoidDialogInterfaceOnClickListener implements DialogInterface.OnClickListener{\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n\r\n }\r\n}\r"
}
] | import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.documentfile.provider.DocumentFile;
import androidx.recyclerview.widget.RecyclerView;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import icu.freedomintrovert.YTSendCommAntiFraud.comment.ToBeCheckedComment;
import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB;
import icu.freedomintrovert.YTSendCommAntiFraud.view.VoidDialogInterfaceOnClickListener;
| 2,021 | package icu.freedomintrovert.YTSendCommAntiFraud;
public class ToBeCheckedCommentsAdapter extends RecyclerView.Adapter<ToBeCheckedCommentsAdapter.ViewHolder> {
StatisticsDB statisticsDB;
Activity context;
| package icu.freedomintrovert.YTSendCommAntiFraud;
public class ToBeCheckedCommentsAdapter extends RecyclerView.Adapter<ToBeCheckedCommentsAdapter.ViewHolder> {
StatisticsDB statisticsDB;
Activity context;
| List<ToBeCheckedComment> commentList;
| 0 | 2023-10-15 01:18:28+00:00 | 4k |
New-Barams/This-Year-Ajaja-BE | src/test/java/com/newbarams/ajaja/module/feedback/application/LoadFeedbackInfoServiceTest.java | [
{
"identifier": "MockTestSupport",
"path": "src/test/java/com/newbarams/ajaja/common/support/MockTestSupport.java",
"snippet": "@ExtendWith(MockitoExtension.class)\npublic abstract class MockTestSupport extends MonkeySupport {\n}"
},
{
"identifier": "AjajaException",
"path": "src/main/java/com/newbarams/ajaja/global/exception/AjajaException.java",
"snippet": "@Getter\npublic class AjajaException extends RuntimeException {\n\tprivate final ErrorCode errorCode;\n\n\tpublic AjajaException(ErrorCode errorCode) {\n\t\tsuper(errorCode.getMessage());\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic AjajaException(Throwable cause, ErrorCode errorCode) {\n\t\tsuper(errorCode.getMessage(), cause);\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tprivate AjajaException(String message, ErrorCode errorCode) {\n\t\tsuper(message);\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic static AjajaException withId(Long id, ErrorCode errorCode) {\n\t\tString message = errorCode.getMessage() + \" Wrong with Id :\" + id;\n\t\treturn new AjajaException(message, errorCode);\n\t}\n\n\tpublic int getHttpStatus() {\n\t\treturn errorCode.getHttpStatus().value();\n\t}\n}"
},
{
"identifier": "FeedbackQueryRepository",
"path": "src/main/java/com/newbarams/ajaja/module/feedback/domain/FeedbackQueryRepository.java",
"snippet": "public interface FeedbackQueryRepository {\n\tList<Feedback> findAllFeedbackByPlanId(Long planId);\n\n\tboolean existByPlanIdAndPeriod(Long feedbackId, TimeValue period);\n\n\tList<FeedbackInfo> findFeedbackInfosByPlanId(Long planId);\n\n\tList<AchieveInfo> findAchievesByUserIdAndYear(Long userId, int year);\n}"
},
{
"identifier": "FeedbackResponse",
"path": "src/main/java/com/newbarams/ajaja/module/feedback/dto/FeedbackResponse.java",
"snippet": "public final class FeedbackResponse {\n\t@Data\n\tpublic static class FeedbackInfo {\n\t\tprivate final int createdYear;\n\t\tprivate final int achieveRate;\n\t\tprivate final String title;\n\t\tprivate final int remindTime;\n\t\tprivate final List<RemindFeedback> feedbacks;\n\t}\n\n\t@Data\n\tpublic static class RemindFeedback {\n\t\tprivate final int achieve;\n\t\tprivate final String message;\n\t\tprivate final int remindMonth;\n\t\tprivate final int remindDate;\n\t\tprivate final int endMonth;\n\t\tprivate final int endDate;\n\t\tprivate final boolean reminded;\n\t}\n}"
},
{
"identifier": "FeedbackMapper",
"path": "src/main/java/com/newbarams/ajaja/module/feedback/mapper/FeedbackMapper.java",
"snippet": "@Mapper(componentModel = \"spring\")\npublic interface FeedbackMapper {\n\t@Mapping(source = \"entity.id\", target = \"id\")\n\t@Mapping(target = \"createdAt\", expression = \"java(new TimeValue(entity.getCreatedAt()))\")\n\t@Mapping(target = \"updatedAt\", expression = \"java(new TimeValue(entity.getUpdatedAt()))\")\n\t@Mapping(target = \"achieve\", expression = \"java(Achieve.of(entity.getAchieve()))\")\n\tFeedback toDomain(FeedbackEntity entity);\n\n\tList<Feedback> toDomain(List<FeedbackEntity> entities);\n\n\t@Mapping(target = \"achieveRate\", expression = \"java(findAchieveRate(feedbacks))\")\n\t@Mapping(source = \"info.title\", target = \"title\")\n\tFeedbackResponse.FeedbackInfo toResponse(PlanFeedbackInfo info, List<FeedbackResponse.RemindFeedback> feedbacks);\n\n\t@Mapping(target = \"deleted\", expression = \"java(false)\")\n\t@Mapping(source = \"info.message\", target = \"message\")\n\t@Mapping(target = \"achieve\", expression = \"java(feedback.getInfo().getAchieve().getRate())\")\n\tFeedbackEntity toEntity(Feedback feedback);\n\n\tdefault int findAchieveRate(List<FeedbackResponse.RemindFeedback> feedbacks) {\n\t\treturn (int)feedbacks.stream()\n\t\t\t.mapToInt(FeedbackResponse.RemindFeedback::getAchieve)\n\t\t\t.average()\n\t\t\t.orElse(0);\n\t}\n\n\t@Mapping(target = \"reminded\", expression = \"java(true)\")\n\t@Mapping(target = \"remindMonth\", expression = \"java(sendDate.getMonth())\")\n\t@Mapping(target = \"remindDate\", expression = \"java(sendDate.getDate())\")\n\t@Mapping(target = \"endMonth\", expression = \"java(endDate.getMonthValue())\")\n\t@Mapping(target = \"endDate\", expression = \"java(endDate.getDayOfMonth())\")\n\tFeedbackResponse.RemindFeedback toResponse(TimeValue sendDate, FeedbackInfo feedbackInfo, ZonedDateTime endDate);\n\n\t@Mapping(target = \"message\", expression = \"java(\\\"\\\")\")\n\t@Mapping(target = \"reminded\", expression = \"java(isReminded(sendDate))\")\n\t@Mapping(target = \"remindMonth\", expression = \"java(sendDate.getMonth())\")\n\t@Mapping(target = \"remindDate\", expression = \"java(sendDate.getDate())\")\n\t@Mapping(target = \"endMonth\", expression = \"java(endDate.getMonthValue())\")\n\t@Mapping(target = \"endDate\", expression = \"java(endDate.getDayOfMonth())\")\n\tFeedbackResponse.RemindFeedback toEmptyResponse(TimeValue sendDate, Integer remindTime, ZonedDateTime endDate);\n\n\tdefault boolean isReminded(TimeValue sendDate) {\n\t\tTimeValue current = new TimeValue();\n\t\treturn current.isAfter(sendDate);\n\t}\n}"
},
{
"identifier": "LoadPlanService",
"path": "src/main/java/com/newbarams/ajaja/module/plan/application/LoadPlanService.java",
"snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class LoadPlanService {\n\tprivate final PlanRepository planRepository;\n\tprivate final PlanQueryRepository planQueryRepository;\n\tprivate final PlanMapper planMapper;\n\n\tpublic PlanResponse.Detail loadByIdAndOptionalUser(Long userId, Long id) {\n\t\treturn planQueryRepository.findPlanDetailByIdAndOptionalUser(userId, id)\n\t\t\t.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));\n\t}\n\n\tpublic Plan loadByUserIdAndPlanId(Long userId, Long id) {\n\t\treturn planQueryRepository.findByUserIdAndPlanId(userId, id);\n\t}\n\n\tpublic Plan loadPlanOrElseThrow(Long id) {\n\t\treturn planRepository.findById(id)\n\t\t\t.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));\n\t}\n\n\tpublic PlanFeedbackInfo loadPlanFeedbackInfoByPlanId(Long userId, Long planId) {\n\t\tPlan plan = loadByUserIdAndPlanId(userId, planId);\n\t\treturn planMapper.toModel(plan);\n\t}\n\n\tpublic List<PlanResponse.GetAll> loadAllPlans(PlanRequest.GetAll request) {\n\t\treturn planQueryRepository.findAllByCursorAndSorting(request);\n\t}\n}"
}
] | import static org.mockito.BDDMockito.*;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import com.newbarams.ajaja.common.support.MockTestSupport;
import com.newbarams.ajaja.global.exception.AjajaException;
import com.newbarams.ajaja.module.feedback.application.model.FeedbackPeriod;
import com.newbarams.ajaja.module.feedback.application.model.PlanFeedbackInfo;
import com.newbarams.ajaja.module.feedback.domain.FeedbackQueryRepository;
import com.newbarams.ajaja.module.feedback.dto.FeedbackResponse;
import com.newbarams.ajaja.module.feedback.infra.model.FeedbackInfo;
import com.newbarams.ajaja.module.feedback.mapper.FeedbackMapper;
import com.newbarams.ajaja.module.plan.application.LoadPlanService; | 1,840 | package com.newbarams.ajaja.module.feedback.application;
class LoadFeedbackInfoServiceTest extends MockTestSupport {
@InjectMocks
private LoadFeedbackInfoService loadFeedbackInfoService;
@Mock
private LoadPlanService loadPlanService;
@Mock
private FeedbackQueryRepository feedbackQueryRepository;
@Mock
private FeedbackMapper mapper;
private List<FeedbackInfo> feedbacks;
private PlanFeedbackInfo planFeedbackInfo; | package com.newbarams.ajaja.module.feedback.application;
class LoadFeedbackInfoServiceTest extends MockTestSupport {
@InjectMocks
private LoadFeedbackInfoService loadFeedbackInfoService;
@Mock
private LoadPlanService loadPlanService;
@Mock
private FeedbackQueryRepository feedbackQueryRepository;
@Mock
private FeedbackMapper mapper;
private List<FeedbackInfo> feedbacks;
private PlanFeedbackInfo planFeedbackInfo; | private FeedbackResponse.FeedbackInfo feedbackInfo; | 3 | 2023-10-23 07:24:17+00:00 | 4k |
eclipse-jgit/jgit | org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/time/MonotonicFakeClock.java | [
{
"identifier": "MonotonicClock",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/util/time/MonotonicClock.java",
"snippet": "public interface MonotonicClock {\n\t/**\n\t * Obtain a timestamp close to \"now\".\n\t * <p>\n\t * Proposed times are close to \"now\", but may not yet be certainly in the\n\t * past. This allows the calling thread to interleave other useful work\n\t * while waiting for the clock instance to create an assurance it will never\n\t * in the future propose a time earlier than the returned time.\n\t * <p>\n\t * A hypothetical implementation could read the local system clock (managed\n\t * by NTP) and return that proposal, concurrently sending network messages\n\t * to closely collaborating peers in the same cluster to also ensure their\n\t * system clocks are ahead of this time. In such an implementation the\n\t * {@link org.eclipse.jgit.util.time.ProposedTimestamp#blockUntil(Duration)}\n\t * method would wait for replies from the peers indicating their own system\n\t * clocks have moved past the proposed time.\n\t *\n\t * @return a {@link org.eclipse.jgit.util.time.ProposedTimestamp} object.\n\t */\n\tProposedTimestamp propose();\n}"
},
{
"identifier": "ProposedTimestamp",
"path": "org.eclipse.jgit/src/org/eclipse/jgit/util/time/ProposedTimestamp.java",
"snippet": "public abstract class ProposedTimestamp implements AutoCloseable {\n\t/**\n\t * Wait for several timestamps.\n\t *\n\t * @param times\n\t * timestamps to wait on.\n\t * @param maxWait\n\t * how long to wait for the timestamps.\n\t * @throws java.lang.InterruptedException\n\t * current thread was interrupted before the waiting process\n\t * completed normally.\n\t * @throws java.util.concurrent.TimeoutException\n\t * the timeout was reached without the proposed timestamp become\n\t * certainly in the past.\n\t */\n\tpublic static void blockUntil(Iterable<ProposedTimestamp> times,\n\t\t\tDuration maxWait) throws TimeoutException, InterruptedException {\n\t\tIterator<ProposedTimestamp> itr = times.iterator();\n\t\tif (!itr.hasNext()) {\n\t\t\treturn;\n\t\t}\n\n\t\tlong now = System.currentTimeMillis();\n\t\tlong deadline = now + maxWait.toMillis();\n\t\tfor (;;) {\n\t\t\tlong w = deadline - now;\n\t\t\tif (w < 0) {\n\t\t\t\tthrow new TimeoutException();\n\t\t\t}\n\t\t\titr.next().blockUntil(Duration.ofMillis(w));\n\t\t\tif (itr.hasNext()) {\n\t\t\t\tnow = System.currentTimeMillis();\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Read the timestamp as {@code unit} since the epoch.\n\t * <p>\n\t * The timestamp value for a specific {@code ProposedTimestamp} object never\n\t * changes, and can be read before {@link #blockUntil(Duration)}.\n\t *\n\t * @param unit\n\t * what unit to return the timestamp in. The timestamp will be\n\t * rounded if the unit is bigger than the clock's granularity.\n\t * @return {@code unit} since the epoch.\n\t */\n\tpublic abstract long read(TimeUnit unit);\n\n\t/**\n\t * Wait for this proposed timestamp to be certainly in the recent past.\n\t * <p>\n\t * This method forces the caller to wait up to {@code timeout} for\n\t * {@code this} to pass sufficiently into the past such that the creating\n\t * {@link org.eclipse.jgit.util.time.MonotonicClock} instance will not\n\t * create an earlier timestamp.\n\t *\n\t * @param maxWait\n\t * how long the implementation may block the caller.\n\t * @throws java.lang.InterruptedException\n\t * current thread was interrupted before the waiting process\n\t * completed normally.\n\t * @throws java.util.concurrent.TimeoutException\n\t * the timeout was reached without the proposed timestamp\n\t * becoming certainly in the past.\n\t */\n\tpublic abstract void blockUntil(Duration maxWait)\n\t\t\tthrows InterruptedException, TimeoutException;\n\n\t/**\n\t * Get milliseconds since epoch; {@code read(MILLISECONDS}).\n\t *\n\t * @return milliseconds since epoch; {@code read(MILLISECONDS}).\n\t */\n\tpublic long millis() {\n\t\treturn read(MILLISECONDS);\n\t}\n\n\t/**\n\t * Get microseconds since epoch; {@code read(MICROSECONDS}).\n\t *\n\t * @return microseconds since epoch; {@code read(MICROSECONDS}).\n\t */\n\tpublic long micros() {\n\t\treturn read(MICROSECONDS);\n\t}\n\n\t/**\n\t * Get time since epoch, with up to microsecond resolution.\n\t *\n\t * @return time since epoch, with up to microsecond resolution.\n\t */\n\tpublic Instant instant() {\n\t\tlong usec = micros();\n\t\tlong secs = usec / 1000000L;\n\t\tlong nanos = (usec % 1000000L) * 1000L;\n\t\treturn Instant.ofEpochSecond(secs, nanos);\n\t}\n\n\t/**\n\t * Get time since epoch, with up to microsecond resolution.\n\t *\n\t * @return time since epoch, with up to microsecond resolution.\n\t */\n\tpublic Timestamp timestamp() {\n\t\treturn Timestamp.from(instant());\n\t}\n\n\t/**\n\t * Get time since epoch, with up to millisecond resolution.\n\t *\n\t * @return time since epoch, with up to millisecond resolution.\n\t */\n\tpublic Date date() {\n\t\treturn new Date(millis());\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * <p>\n\t * Release resources allocated by this timestamp.\n\t */\n\t@Override\n\tpublic void close() {\n\t\t// Do nothing by default.\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn instant().toString();\n\t}\n}"
}
] | import org.eclipse.jgit.util.time.ProposedTimestamp;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.util.time.MonotonicClock; | 1,676 | /*
* Copyright (C) 2016, Google Inc. and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.junit.time;
/**
* Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that
* uses Clock.
*
* @since 4.6
*/
public class MonotonicFakeClock implements MonotonicClock {
private long now = TimeUnit.SECONDS.toMicros(42);
/**
* Advance the time returned by future calls to {@link #propose()}.
*
* @param add
* amount of time to add; must be {@code > 0}.
* @param unit
* unit of {@code add}.
*/
public void tick(long add, TimeUnit unit) {
if (add <= 0) {
throw new IllegalArgumentException();
}
now += unit.toMillis(add);
}
@Override | /*
* Copyright (C) 2016, Google Inc. and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.junit.time;
/**
* Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that
* uses Clock.
*
* @since 4.6
*/
public class MonotonicFakeClock implements MonotonicClock {
private long now = TimeUnit.SECONDS.toMicros(42);
/**
* Advance the time returned by future calls to {@link #propose()}.
*
* @param add
* amount of time to add; must be {@code > 0}.
* @param unit
* unit of {@code add}.
*/
public void tick(long add, TimeUnit unit) {
if (add <= 0) {
throw new IllegalArgumentException();
}
now += unit.toMillis(add);
}
@Override | public ProposedTimestamp propose() { | 1 | 2023-10-20 15:09:17+00:00 | 4k |
starfish-studios/Naturalist | common/src/main/java/com/starfish_studios/naturalist/client/model/CatfishModel.java | [
{
"identifier": "Naturalist",
"path": "common/src/main/java/com/starfish_studios/naturalist/Naturalist.java",
"snippet": "public class Naturalist {\n public static final String MOD_ID = \"naturalist\";\n public static final CreativeModeTab TAB = CommonPlatformHelper.registerCreativeModeTab(new ResourceLocation(MOD_ID, \"tab\"), () -> new ItemStack(NaturalistBlocks.TEDDY_BEAR.get()));\n public static final Logger LOGGER = LogManager.getLogger();\n\n public static void init() {\n GeckoLib.initialize();\n NaturalistBlocks.init();\n NaturalistItems.init();\n NaturalistBlockEntities.init();\n NaturalistSoundEvents.init();\n NaturalistEntityTypes.init();\n NaturalistPotions.init();\n }\n \n public static void registerBrewingRecipes() {\n CommonPlatformHelper.registerBrewingRecipe(Potions.AWKWARD, NaturalistItems.ANTLER.get(), NaturalistPotions.FOREST_DASHER.get());\n CommonPlatformHelper.registerBrewingRecipe(NaturalistPotions.FOREST_DASHER.get(), Items.REDSTONE, NaturalistPotions.LONG_FOREST_DASHER.get());\n CommonPlatformHelper.registerBrewingRecipe(NaturalistPotions.FOREST_DASHER.get(), Items.GLOWSTONE_DUST, NaturalistPotions.STRONG_FOREST_DASHER.get());\n }\n\n public static void registerSpawnPlacements() {\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.SNAIL.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BEAR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BUTTERFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.FIREFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Firefly::checkFireflySpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.SNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CORAL_SNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.RATTLESNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DEER.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BLUEJAY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CANARY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CARDINAL.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ROBIN.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.RHINO.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.LION.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ELEPHANT.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ZEBRA.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.GIRAFFE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.HIPPO.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Hippo::checkHippoSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.VULTURE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Vulture::checkVultureSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BOAR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DRAGONFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Dragonfly::checkDragonflySpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CATFISH.get(), SpawnPlacements.Type.IN_WATER, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, WaterAnimal::checkSurfaceWaterAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ALLIGATOR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Alligator::checkAlligatorSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BASS.get(), SpawnPlacements.Type.IN_WATER, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, WaterAnimal::checkSurfaceWaterAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.LIZARD.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.TORTOISE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DUCK.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Duck::checkDuckSpawnRules);\n }\n\n\n public static void registerCompostables() {\n CommonPlatformHelper.registerCompostable(0.65F, NaturalistItems.SNAIL_SHELL.get());\n }\n}"
},
{
"identifier": "Catfish",
"path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Catfish.java",
"snippet": "public class Catfish extends AbstractFish implements IAnimatable {\n private static final EntityDataAccessor<Integer> KILL_COOLDOWN = SynchedEntityData.defineId(Catfish.class, EntityDataSerializers.INT);\n\n private final AnimationFactory factory = GeckoLibUtil.createFactory(this);\n\n public Catfish(EntityType<? extends AbstractFish> entityType, Level level) {\n super(entityType, level);\n }\n\n public static AttributeSupplier.Builder createAttributes() {\n return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 6.0).add(Attributes.ATTACK_DAMAGE, 1.0D);\n }\n\n @Override\n protected void registerGoals() {\n super.registerGoals();\n this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0D, false)\n {\n public boolean canUse() {\n return super.canUse() && !isBaby() && getKillCooldown() == 0;\n }\n\n public void stop() {\n super.stop();\n setKillCooldown(2400);\n }\n });\n this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, WaterAnimal.class, 10, true, false, (entity) -> entity.getType().is(NaturalistTags.EntityTypes.CATFISH_HOSTILES)));\n }\n\n @Override\n protected void defineSynchedData() {\n super.defineSynchedData();\n this.entityData.define(KILL_COOLDOWN, 0);\n }\n\n @Override\n public void addAdditionalSaveData(CompoundTag compound) {\n super.addAdditionalSaveData(compound);\n compound.putInt(\"KillCooldown\", this.getKillCooldown());\n }\n\n @Override\n public void readAdditionalSaveData(CompoundTag compound) {\n super.readAdditionalSaveData(compound);\n this.setKillCooldown(compound.getInt(\"KillCooldown\"));\n }\n\n public void setKillCooldown(int ticks) {\n this.entityData.set(KILL_COOLDOWN, ticks);\n }\n\n public int getKillCooldown() {\n return this.entityData.get(KILL_COOLDOWN);\n }\n\n @Override\n protected SoundEvent getFlopSound() {\n return NaturalistSoundEvents.CATFISH_FLOP.get();\n }\n @Override\n protected SoundEvent getAmbientSound() {\n return SoundEvents.SALMON_AMBIENT;\n }\n\n @Override\n protected SoundEvent getDeathSound() {\n return SoundEvents.SALMON_DEATH;\n }\n\n @Override\n protected SoundEvent getHurtSound(DamageSource damageSource) {\n return SoundEvents.SALMON_HURT;\n }\n\n @Override\n public ItemStack getBucketItemStack() {\n return new ItemStack(NaturalistItems.CATFISH_BUCKET.get());\n }\n\n private <E extends IAnimatable> PlayState predicate(AnimationEvent<E> event) {\n if (!this.isInWater()) {\n event.getController().setAnimation(new AnimationBuilder().loop(\"catfish.flop\"));\n } else {\n event.getController().setAnimation(new AnimationBuilder().loop(\"catfish.swim\"));\n }\n return PlayState.CONTINUE;\n }\n\n @Override\n public void registerControllers(AnimationData data) {\n data.setResetSpeedInTicks(5);\n data.addAnimationController(new AnimationController<>(this, \"controller\", 5, this::predicate));\n }\n\n @Override\n public AnimationFactory getFactory() {\n return factory;\n }\n}"
}
] | import com.starfish_studios.naturalist.Naturalist;
import com.starfish_studios.naturalist.common.entity.Catfish;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.resources.ResourceLocation;
import software.bernie.geckolib3.model.AnimatedGeoModel; | 2,567 | package com.starfish_studios.naturalist.client.model;
@Environment(EnvType.CLIENT)
public class CatfishModel extends AnimatedGeoModel<Catfish> {
@Override
public ResourceLocation getModelResource(Catfish catfish) { | package com.starfish_studios.naturalist.client.model;
@Environment(EnvType.CLIENT)
public class CatfishModel extends AnimatedGeoModel<Catfish> {
@Override
public ResourceLocation getModelResource(Catfish catfish) { | return new ResourceLocation(Naturalist.MOD_ID, "geo/catfish.geo.json"); | 0 | 2023-10-16 21:54:32+00:00 | 4k |
instana/otel-dc | host/src/main/java/com/instana/dc/host/impl/SimpHostUtil.java | [
{
"identifier": "SimpleQueryResult",
"path": "internal/otel-dc/src/main/java/com/instana/dc/SimpleQueryResult.java",
"snippet": "public class SimpleQueryResult {\n private final Number value;\n private String key;\n private final Map<String, Object> attributes = new HashMap<>();\n\n public SimpleQueryResult(Number value) {\n this.value = value;\n }\n\n public Number getValue() {\n return value;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public Map<String, Object> getAttributes() {\n return attributes;\n }\n\n public Object getAttribute(String key) {\n return attributes.get(key);\n }\n\n public SimpleQueryResult setAttribute(String key, Object attribute) {\n attributes.put(key, attribute);\n return this;\n }\n}"
},
{
"identifier": "HostDcUtil",
"path": "host/src/main/java/com/instana/dc/host/HostDcUtil.java",
"snippet": "public class HostDcUtil {\n private static final Logger logger = Logger.getLogger(HostDcUtil.class.getName());\n\n public static class MeterName{\n public static final String CPU = \"cpu\";\n public static final String MEMORY = \"memory\";\n public static final String NETWORK = \"network\";\n public static final String LOAD = \"load\";\n public static final String DISK = \"disk\";\n public static final String FILESYSTEM = \"filesystem\";\n public static final String PROCESSES = \"processes\";\n public static final String PAGING = \"paging\";\n }\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String SYSTEM_CPU_TIME_NAME = \"system.cpu.time\";\n public static final String SYSTEM_CPU_TIME_DESC = \"Seconds each logical CPU spent on each mode\";\n public static final String SYSTEM_CPU_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_MEMORY_USAGE_NAME = \"system.memory.usage\";\n public static final String SYSTEM_MEMORY_USAGE_DESC = \"Bytes of memory in use\";\n public static final String SYSTEM_MEMORY_USAGE_UNIT = UNIT_BY;\n\n public static final String SYSTEM_CPU_LOAD1_NAME = \"system.cpu.load_average.1m\";\n public static final String SYSTEM_CPU_LOAD1_DESC = \"Average CPU Load over 1 minutes\";\n public static final String SYSTEM_CPU_LOAD1_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD5_NAME = \"system.cpu.load_average.5m\";\n public static final String SYSTEM_CPU_LOAD5_DESC = \"Average CPU Load over 5 minutes\";\n public static final String SYSTEM_CPU_LOAD5_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD15_NAME = \"system.cpu.load_average.15m\";\n public static final String SYSTEM_CPU_LOAD15_DESC = \"Average CPU Load over 15 minutes\";\n public static final String SYSTEM_CPU_LOAD15_UNIT = UNIT_1;\n\n public static final String SYSTEM_NETWORK_CONNECTIONS_NAME = \"system.network.connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_DESC = \"The number of connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_UNIT = \"{connections}\";\n\n public static final String SYSTEM_NETWORK_DROPPED_NAME = \"system.network.dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_DESC = \"The number of packets dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_UNIT = \"{packets}\";\n\n public static final String SYSTEM_NETWORK_ERRORS_NAME = \"system.network.errors\";\n public static final String SYSTEM_NETWORK_ERRORS_DESC = \"The number of errors encountered\";\n public static final String SYSTEM_NETWORK_ERRORS_UNIT = \"{errors}\";\n\n public static final String SYSTEM_NETWORK_IO_NAME = \"system.network.io\";\n public static final String SYSTEM_NETWORK_IO_DESC = \"The number of bytes transmitted and received\";\n public static final String SYSTEM_NETWORK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_NETWORK_PACKETS_NAME = \"system.network.packets\";\n public static final String SYSTEM_NETWORK_PACKETS_DESC = \"The number of packets transferred\";\n public static final String SYSTEM_NETWORK_PACKETS_UNIT = \"{packets}\";\n\n\n public static final String SYSTEM_DISK_IO_NAME = \"system.disk.io\";\n public static final String SYSTEM_DISK_IO_DESC = \"Disk bytes transferred\";\n public static final String SYSTEM_DISK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_DISK_IO_TIME_NAME = \"system.disk.io_time\";\n public static final String SYSTEM_DISK_IO_TIME_DESC = \"Time disk spent activated. On Windows, this is calculated as the inverse of disk idle time\";\n public static final String SYSTEM_DISK_IO_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_MERGED_NAME = \"system.disk.merged\";\n public static final String SYSTEM_DISK_MERGED_DESC = \"The number of disk reads/writes merged into single physical disk access operations\";\n public static final String SYSTEM_DISK_MERGED_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_OPERATION_TIME_NAME = \"system.disk.operation_time\";\n public static final String SYSTEM_DISK_OPERATION_TIME_DESC = \"Time spent in disk operations\";\n public static final String SYSTEM_DISK_OPERATION_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_OPERATIONS_NAME = \"system.disk.operations\";\n public static final String SYSTEM_DISK_OPERATIONS_DESC = \"Disk operations count\";\n public static final String SYSTEM_DISK_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_NAME = \"system.disk.pending_operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_DESC = \"The queue size of pending I/O operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_NAME = \"system.disk.weighted_io_time\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_DESC = \"Time disk spent activated multiplied by the queue length\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_UNIT = UNIT_S;\n\n\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_NAME = \"system.filesystem.inodes.usage\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_DESC = \"FileSystem inodes used\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_UNIT = \"{inodes}\";\n\n public static final String SYSTEM_FILESYSTEM_USAGE_NAME = \"system.filesystem.usage\";\n public static final String SYSTEM_FILESYSTEM_USAGE_DESC = \"Filesystem bytes used\";\n public static final String SYSTEM_FILESYSTEM_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PAGING_FAULTS_NAME = \"system.paging.faults\";\n public static final String SYSTEM_PAGING_FAULTS_DESC = \"The number of page faults\";\n public static final String SYSTEM_PAGING_FAULTS_UNIT = \"{faults}\";\n\n public static final String SYSTEM_PAGING_OPERATIONS_NAME = \"system.paging.operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_DESC = \"The number of paging operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_PAGING_USAGE_NAME = \"system.paging.usage\";\n public static final String SYSTEM_PAGING_USAGE_DESC = \"Swap (unix) or pagefile (windows) usage\";\n public static final String SYSTEM_PAGING_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PROCESSES_COUNT_NAME = \"system.processes.count\";\n public static final String SYSTEM_PROCESSES_COUNT_DESC = \"Total number of processes in each state\";\n public static final String SYSTEM_PROCESSES_COUNT_UNIT = \"{processes}\";\n\n public static final String SYSTEM_PROCESSES_CREATED_NAME = \"system.processes.created\";\n public static final String SYSTEM_PROCESSES_CREATED_DESC = \"Total number of created processes\";\n public static final String SYSTEM_PROCESSES_CREATED_UNIT = \"{processes}\";\n\n\n public static String readFileText(String filePath) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n int n = is.available();\n byte[] ba = new byte[n];\n is.read(ba);\n return new String(ba).trim();\n }\n }\n\n public static String readFileText(String filePath, int max) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n byte[] ba = new byte[max];\n int n = is.read(ba);\n return new String(ba, 0, n).trim();\n }\n }\n\n public static String readFileTextLine(String filePath) throws IOException {\n try (Reader rd = new FileReader(filePath)) {\n BufferedReader reader = new BufferedReader(rd);\n String line = reader.readLine();\n reader.close();\n return line;\n }\n }\n}"
}
] | import com.instana.dc.SimpleQueryResult;
import com.instana.dc.host.HostDcUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 2,492 | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostUtil {
private static final Logger logger = Logger.getLogger(SimpHostUtil.class.getName());
public static class CpuTime {
private long user, nice, system, idle, iowait, irq, softirq;
public long getUser() {
return user;
}
public void setUser(long user) {
this.user = user;
}
public long getNice() {
return nice;
}
public void setNice(long nice) {
this.nice = nice;
}
public long getSystem() {
return system;
}
public void setSystem(long system) {
this.system = system;
}
public long getIdle() {
return idle;
}
public void setIdle(long idle) {
this.idle = idle;
}
public long getIowait() {
return iowait;
}
public void setIowait(long iowait) {
this.iowait = iowait;
}
public long getIrq() {
return irq;
}
public void setIrq(long irq) {
this.irq = irq;
}
public long getSoftirq() {
return softirq;
}
public void setSoftirq(long softirq) {
this.softirq = softirq;
}
@Override
public String toString() {
return "CpuTime{" +
"user=" + user +
", nice=" + nice +
", system=" + system +
", idle=" + idle +
", iowait=" + iowait +
", irq=" + irq +
", softirq=" + softirq +
'}';
}
}
public static CpuTime getCpuTime() throws IOException { | /*
* (c) Copyright IBM Corp. 2023
* (c) Copyright Instana Inc.
*/
package com.instana.dc.host.impl;
public class SimpHostUtil {
private static final Logger logger = Logger.getLogger(SimpHostUtil.class.getName());
public static class CpuTime {
private long user, nice, system, idle, iowait, irq, softirq;
public long getUser() {
return user;
}
public void setUser(long user) {
this.user = user;
}
public long getNice() {
return nice;
}
public void setNice(long nice) {
this.nice = nice;
}
public long getSystem() {
return system;
}
public void setSystem(long system) {
this.system = system;
}
public long getIdle() {
return idle;
}
public void setIdle(long idle) {
this.idle = idle;
}
public long getIowait() {
return iowait;
}
public void setIowait(long iowait) {
this.iowait = iowait;
}
public long getIrq() {
return irq;
}
public void setIrq(long irq) {
this.irq = irq;
}
public long getSoftirq() {
return softirq;
}
public void setSoftirq(long softirq) {
this.softirq = softirq;
}
@Override
public String toString() {
return "CpuTime{" +
"user=" + user +
", nice=" + nice +
", system=" + system +
", idle=" + idle +
", iowait=" + iowait +
", irq=" + irq +
", softirq=" + softirq +
'}';
}
}
public static CpuTime getCpuTime() throws IOException { | String line = HostDcUtil.readFileTextLine("/proc/stat"); | 1 | 2023-10-23 01:16:38+00:00 | 4k |
quarkiverse/quarkus-antivirus | deployment/src/main/java/io/quarkiverse/antivirus/deployment/AntivirusProcessor.java | [
{
"identifier": "Antivirus",
"path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/Antivirus.java",
"snippet": "@ApplicationScoped\n@JBossLog\npublic class Antivirus {\n\n @Inject\n private Instance<AntivirusEngine> engineInstances;\n\n /**\n * Perform virus scan and throw exception if a virus has been detected.\n *\n * @param filename the name of the file to scan\n * @param inputStream the inputStream containing the file contents\n * @return the List of all {@link AntivirusScanResult} from all engines\n */\n @SneakyThrows\n public List<AntivirusScanResult> scan(final String filename, final InputStream inputStream) {\n final List<AntivirusScanResult> results = new ArrayList<>();\n for (AntivirusEngine plugin : engineInstances) {\n if (plugin.isEnabled()) {\n final AntivirusScanResult result = plugin.scan(filename, inputStream);\n results.add(result);\n // reset the stream for the next scan\n inputStream.reset();\n }\n }\n\n // let user know nothing happened meaning they had all engines disabled\n if (results.isEmpty()) {\n log.warn(\"Antivirus extension found NO scanning engines to execute!\");\n }\n return results;\n }\n}"
},
{
"identifier": "ClamAVEngine",
"path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/ClamAVEngine.java",
"snippet": "@ApplicationScoped\n@JBossLog\npublic class ClamAVEngine implements AntivirusEngine {\n private ClamAVClient client;\n @Inject\n ClamAVRuntimeConfig config;\n\n @Override\n public boolean isEnabled() {\n return config.enabled();\n }\n\n /**\n * Scans an {@link InputStream} for any viruses. If any virus is detected an exception will be thrown.\n *\n * @param filename the name of the file to be scanned\n * @param inputStream the {@link InputStream} of the file to scan\n * @return the {@link AntivirusScanResult} containing the results\n */\n @Override\n public AntivirusScanResult scan(final String filename, final InputStream inputStream) {\n AntivirusScanResult.AntivirusScanResultBuilder result = AntivirusScanResult.builder().engine(\"ClamAV\")\n .fileName(filename);\n if (!config.enabled()) {\n return result.status(404).message(\"ClamAV scanner is currently disabled!\").build();\n }\n log.infof(\"Starting the virus scan for file: %s\", filename);\n\n try {\n final ClamAVClient client = getClamAVClient();\n final byte[] reply = client.scan(inputStream);\n final String message = new String(reply, StandardCharsets.US_ASCII).trim();\n log.infof(\"Scanner replied with message: %s\", message);\n if (!ClamAVClient.isCleanReply(reply)) {\n final String error = String.format(\"Scan detected viruses in file '%s'! Virus scanner message = %s\",\n filename, message);\n log.errorf(\"ClamAV %s\", error);\n return result.status(400).message(error).payload(message).build();\n }\n return result.status(200).message(message).payload(message).build();\n } catch (final RuntimeException | IOException ex) {\n final String error = String.format(\"Unexpected error scanning file '%s' - %s\",\n filename, ex.getMessage());\n return result.status(400).message(error).payload(ex.getMessage()).build();\n } finally {\n log.infof(\"Finished scanning file %s!\", filename);\n }\n }\n\n /**\n * Ping the clamd service to make sure it is available.\n *\n * @return true if clamd is available false if not.\n */\n public boolean ping() {\n if (!config.enabled()) {\n return false;\n }\n try {\n return getClamAVClient().ping();\n } catch (final RuntimeException | IOException ex) {\n return false;\n }\n }\n\n /**\n * Returns a new ClamAvClient which can be overridden in unit tests.\n *\n * @return the {@link ClamAVClient}\n */\n ClamAVClient getClamAVClient() {\n if (client != null) {\n return client;\n }\n client = new ClamAVClient(this.config);\n return client;\n }\n}"
},
{
"identifier": "ClamAVHealthCheck",
"path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/ClamAVHealthCheck.java",
"snippet": "@Readiness\n@ApplicationScoped\npublic class ClamAVHealthCheck implements HealthCheck {\n\n @Inject\n ClamAVEngine engine;\n @Inject\n ClamAVRuntimeConfig config;\n\n @Override\n public HealthCheckResponse call() {\n final String server = String.format(\"%s:%s\", config.host(), config.port());\n HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named(\"ClamAV Daemon\");\n responseBuilder = engine.ping() ? responseBuilder.up().withData(server, \"UP\")\n : responseBuilder.down().withData(server, \"DOWN\");\n return responseBuilder.build();\n }\n}"
},
{
"identifier": "VirusTotalEngine",
"path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/VirusTotalEngine.java",
"snippet": "@ApplicationScoped\n@JBossLog\npublic class VirusTotalEngine implements AntivirusEngine {\n\n @Inject\n VirusTotalRuntimeConfig config;\n\n @Override\n public boolean isEnabled() {\n return config.enabled() && config.key().isPresent();\n }\n\n @Override\n public AntivirusScanResult scan(String filename, InputStream inputStream) {\n AntivirusScanResult.AntivirusScanResultBuilder result = AntivirusScanResult.builder().engine(\"VirusTotal\")\n .fileName(filename);\n if (!config.enabled()) {\n return result.status(404).message(\"VirusTotal scanner is currently disabled!\").build();\n }\n log.infof(\"Starting the virus scan for file: %s\", filename);\n try {\n String message;\n HttpURLConnection connection = openConnection(filename, inputStream);\n int code = connection.getResponseCode();\n result.status(code);\n switch (code) {\n case 200:\n result.message(\"OK\");\n break;\n case 204:\n message = \"Virus Total Request rate limit exceeded. You are making more requests than allowed. \"\n + \"You have exceeded one of your quotas (minute, daily or monthly). Daily quotas are reset every day at 00:00 UTC.\";\n return result.message(message).build();\n case 400:\n message = \"Bad request. Your request was somehow incorrect. \"\n + \"This can be caused by missing arguments or arguments with wrong values.\";\n return result.message(message).build();\n case 403:\n message = \"Forbidden. You don't have enough privileges to make the request. \"\n + \"You may be doing a request without providing an API key or you may be making a request \"\n + \"to a Private API without having the appropriate privileges.\";\n return result.message(message).build();\n case 404:\n message = \"Not Found. This file has never been scanned by VirusTotal before.\";\n return result.message(message).build();\n default:\n message = \"Unexpected HTTP code \" + code + \" calling Virus Total web service.\";\n return result.message(message).build();\n }\n\n try (InputStream response = connection.getInputStream()) {\n final String payload = convertInputStreamToString(response);\n result.payload(payload);\n final JsonObject json = new JsonObject(payload);\n return handleBodyResponse(filename, json, result);\n }\n } catch (IOException ex) {\n log.warn(\"Cannot perform virus scan\");\n return result.status(400).message(\"Cannot perform virus scan\").payload(ex.getMessage()).build();\n }\n }\n\n private AntivirusScanResult handleBodyResponse(String filename, JsonObject json,\n AntivirusScanResult.AntivirusScanResultBuilder result) {\n JsonObject data = json.getJsonObject(\"data\");\n if (data == null) {\n return result.status(200).build();\n }\n JsonObject attributes = data.getJsonObject(\"attributes\");\n if (attributes == null) {\n return result.status(200).build();\n }\n JsonObject totalVotes = attributes.getJsonObject(\"total_votes\");\n if (totalVotes == null) {\n return result.status(200).build();\n }\n int votes = totalVotes.getInteger(\"malicious\", 0);\n if (votes >= config.minimumVotes()) {\n String name = attributes.getString(\"meaningful_name\");\n log.debugf(String.format(\"Retrieved %s meaningful name.\", name));\n if (name != null && !name.isEmpty()) {\n final String error = String.format(\"Scan detected virus '%s' in file '%s'!\", name, filename);\n return result.status(400).message(error).build();\n }\n }\n return result.status(200).build();\n }\n\n protected HttpURLConnection openConnection(String filename, InputStream inputStream) throws IOException {\n HttpURLConnection connection;\n try {\n String key = config.key().orElseThrow(RuntimeException::new);\n String hash = md5Hex(filename, convertInputStreamToByteArray(inputStream));\n log.debugf(\"File Hash = %s\", hash);\n URL url = new URL(String.format(config.url(), hash));\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestProperty(\"x-apikey\", key);\n connection.setRequestMethod(\"GET\");\n connection.connect();\n } catch (IOException e) {\n throw new AntivirusException(filename, e.getMessage(), e);\n }\n\n return connection;\n }\n\n protected String convertInputStreamToString(InputStream inputStream) throws IOException {\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder stringBuilder = new StringBuilder();\n String line;\n\n while ((line = reader.readLine()) != null) {\n stringBuilder.append(line);\n }\n\n return stringBuilder.toString();\n }\n\n protected byte[] convertInputStreamToByteArray(InputStream inputStream) throws IOException {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int bytesRead;\n\n while ((bytesRead = inputStream.read(buffer)) != -1) {\n byteArrayOutputStream.write(buffer, 0, bytesRead);\n }\n\n return byteArrayOutputStream.toByteArray();\n }\n\n protected String md5Hex(String filename, byte[] bytes) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\n md.update(bytes);\n return DatatypeConverter.printHexBinary(md.digest());\n } catch (NoSuchAlgorithmException e) {\n throw new AntivirusException(filename, e.getMessage());\n }\n }\n}"
}
] | import io.quarkiverse.antivirus.runtime.Antivirus;
import io.quarkiverse.antivirus.runtime.ClamAVEngine;
import io.quarkiverse.antivirus.runtime.ClamAVHealthCheck;
import io.quarkiverse.antivirus.runtime.VirusTotalEngine;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem; | 2,687 | package io.quarkiverse.antivirus.deployment;
/**
* Main processor for the Antivirus extension.
*/
class AntivirusProcessor {
private static final String FEATURE = "antivirus";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep
void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans,
ClamAVBuildConfig buildConfig) {
beans.produce(AdditionalBeanBuildItem.builder().setUnremovable()
.addBeanClasses(ClamAVEngine.class) | package io.quarkiverse.antivirus.deployment;
/**
* Main processor for the Antivirus extension.
*/
class AntivirusProcessor {
private static final String FEATURE = "antivirus";
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(FEATURE);
}
@BuildStep
void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans,
ClamAVBuildConfig buildConfig) {
beans.produce(AdditionalBeanBuildItem.builder().setUnremovable()
.addBeanClasses(ClamAVEngine.class) | .addBeanClasses(VirusTotalEngine.class) | 3 | 2023-10-22 22:33:05+00:00 | 4k |
A1anSong/jd_unidbg | unidbg-ios/src/main/java/com/github/unidbg/ios/FixupChains.java | [
{
"identifier": "Emulator",
"path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java",
"snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}"
},
{
"identifier": "Symbol",
"path": "unidbg-api/src/main/java/com/github/unidbg/Symbol.java",
"snippet": "public abstract class Symbol {\n\n private final String name;\n\n public Symbol(String name) {\n this.name = name;\n }\n\n public abstract Number call(Emulator<?> emulator, Object... args);\n\n public abstract long getAddress();\n\n public abstract long getValue();\n\n public abstract boolean isUndef();\n\n public final UnidbgPointer createNameMemory(SvcMemory svcMemory) {\n return svcMemory.allocateSymbolName(name);\n }\n\n public Pointer createPointer(Emulator<?> emulator) {\n return UnidbgPointer.pointer(emulator, getAddress());\n }\n\n public String getName() {\n return name;\n }\n\n public abstract String getModuleName();\n\n @Override\n public String toString() {\n return name;\n }\n}"
},
{
"identifier": "HookListener",
"path": "unidbg-api/src/main/java/com/github/unidbg/hook/HookListener.java",
"snippet": "public interface HookListener {\n\n int EACH_BIND = -1;\n int WEAK_BIND = -2;\n int FIXUP_BIND = -3;\n\n /**\n * 返回0表示没有hook,否则返回hook以后的调用地址\n */\n long hook(SvcMemory svcMemory, String libraryName, String symbolName, long old);\n\n}"
}
] | import com.github.unidbg.Emulator;
import com.github.unidbg.Symbol;
import com.github.unidbg.hook.HookListener;
import com.sun.jna.Pointer;
import io.kaitai.struct.ByteBufferKaitaiStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.nio.charset.StandardCharsets;
import java.util.List; | 1,747 | package com.github.unidbg.ios;
final class FixupChains {
private static final Log log = LogFactory.getLog(FixupChains.class);
// values for dyld_chained_fixups_header.imports_format
static final int DYLD_CHAINED_IMPORT = 1;
static final int DYLD_CHAINED_IMPORT_ADDEND = 2;
static final int DYLD_CHAINED_IMPORT_ADDEND64 = 3;
static final int DYLD_CHAINED_PTR_START_NONE = 0xffff; // used in page_start[] to denote a page with no fixups
static final int DYLD_CHAINED_PTR_START_MULTI = 0x8000; // used in page_start[] to denote a page which has multiple starts
static final int DYLD_CHAINED_PTR_START_LAST = 0x8000; // used in chain_starts[] to denote last start in list for page
// values for dyld_chained_starts_in_segment.pointer_format
static final int DYLD_CHAINED_PTR_ARM64E = 1; // stride 8, unauth target is vmaddr
static final int DYLD_CHAINED_PTR_64 = 2; // target is vmaddr
static final int DYLD_CHAINED_PTR_32 = 3;
static final int DYLD_CHAINED_PTR_32_CACHE = 4;
static final int DYLD_CHAINED_PTR_32_FIRMWARE = 5;
static final int DYLD_CHAINED_PTR_64_OFFSET = 6; // target is vm offset
static final int DYLD_CHAINED_PTR_ARM64E_OFFSET = 7; // stride 4, unauth target is vm offset
static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8;
static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset
static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr
static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches
static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind
static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) {
return (addLHS > b) || (addRHS > (b-addLHS));
}
private static long signExtendedAddend(long addend) {
long top8Bits = addend & 0x00007f80000L;
long bottom19Bits = addend & 0x0000007ffffL;
return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL);
}
| package com.github.unidbg.ios;
final class FixupChains {
private static final Log log = LogFactory.getLog(FixupChains.class);
// values for dyld_chained_fixups_header.imports_format
static final int DYLD_CHAINED_IMPORT = 1;
static final int DYLD_CHAINED_IMPORT_ADDEND = 2;
static final int DYLD_CHAINED_IMPORT_ADDEND64 = 3;
static final int DYLD_CHAINED_PTR_START_NONE = 0xffff; // used in page_start[] to denote a page with no fixups
static final int DYLD_CHAINED_PTR_START_MULTI = 0x8000; // used in page_start[] to denote a page which has multiple starts
static final int DYLD_CHAINED_PTR_START_LAST = 0x8000; // used in chain_starts[] to denote last start in list for page
// values for dyld_chained_starts_in_segment.pointer_format
static final int DYLD_CHAINED_PTR_ARM64E = 1; // stride 8, unauth target is vmaddr
static final int DYLD_CHAINED_PTR_64 = 2; // target is vmaddr
static final int DYLD_CHAINED_PTR_32 = 3;
static final int DYLD_CHAINED_PTR_32_CACHE = 4;
static final int DYLD_CHAINED_PTR_32_FIRMWARE = 5;
static final int DYLD_CHAINED_PTR_64_OFFSET = 6; // target is vm offset
static final int DYLD_CHAINED_PTR_ARM64E_OFFSET = 7; // stride 4, unauth target is vm offset
static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8;
static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset
static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr
static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches
static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind
static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) {
return (addLHS > b) || (addRHS > (b-addLHS));
}
private static long signExtendedAddend(long addend) {
long top8Bits = addend & 0x00007f80000L;
long bottom19Bits = addend & 0x0000007ffffL;
return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL);
}
| static void handleChain(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, int pointer_format, Pointer chain, long raw64, List<BindTarget> bindTargets, ByteBufferKaitaiStream symbolsPool) { | 0 | 2023-10-17 06:13:28+00:00 | 4k |
robaho/httpserver | src/test/java/robaho/net/httpserver/websockets/WebSocketResponseHandlerTest.java | [
{
"identifier": "Code",
"path": "src/main/java/robaho/net/httpserver/Code.java",
"snippet": "public class Code {\n\n public static final int HTTP_CONTINUE = 100;\n public static final int HTTP_OK = 200;\n public static final int HTTP_CREATED = 201;\n public static final int HTTP_ACCEPTED = 202;\n public static final int HTTP_NOT_AUTHORITATIVE = 203;\n public static final int HTTP_NO_CONTENT = 204;\n public static final int HTTP_RESET = 205;\n public static final int HTTP_PARTIAL = 206;\n public static final int HTTP_MULT_CHOICE = 300;\n public static final int HTTP_MOVED_PERM = 301;\n public static final int HTTP_MOVED_TEMP = 302;\n public static final int HTTP_SEE_OTHER = 303;\n public static final int HTTP_NOT_MODIFIED = 304;\n public static final int HTTP_USE_PROXY = 305;\n public static final int HTTP_BAD_REQUEST = 400;\n public static final int HTTP_UNAUTHORIZED = 401;\n public static final int HTTP_PAYMENT_REQUIRED = 402;\n public static final int HTTP_FORBIDDEN = 403;\n public static final int HTTP_NOT_FOUND = 404;\n public static final int HTTP_BAD_METHOD = 405;\n public static final int HTTP_NOT_ACCEPTABLE = 406;\n public static final int HTTP_PROXY_AUTH = 407;\n public static final int HTTP_CLIENT_TIMEOUT = 408;\n public static final int HTTP_CONFLICT = 409;\n public static final int HTTP_GONE = 410;\n public static final int HTTP_LENGTH_REQUIRED = 411;\n public static final int HTTP_PRECON_FAILED = 412;\n public static final int HTTP_ENTITY_TOO_LARGE = 413;\n public static final int HTTP_REQ_TOO_LONG = 414;\n public static final int HTTP_UNSUPPORTED_TYPE = 415;\n public static final int HTTP_INTERNAL_ERROR = 500;\n public static final int HTTP_NOT_IMPLEMENTED = 501;\n public static final int HTTP_BAD_GATEWAY = 502;\n public static final int HTTP_UNAVAILABLE = 503;\n public static final int HTTP_GATEWAY_TIMEOUT = 504;\n public static final int HTTP_VERSION = 505;\n\n static String msg(int code) {\n\n switch (code) {\n case HTTP_OK:\n return \" OK\";\n case HTTP_CONTINUE:\n return \" Continue\";\n case HTTP_CREATED:\n return \" Created\";\n case HTTP_ACCEPTED:\n return \" Accepted\";\n case HTTP_NOT_AUTHORITATIVE:\n return \" Non-Authoritative Information\";\n case HTTP_NO_CONTENT:\n return \" No Content\";\n case HTTP_RESET:\n return \" Reset Content\";\n case HTTP_PARTIAL:\n return \" Partial Content\";\n case HTTP_MULT_CHOICE:\n return \" Multiple Choices\";\n case HTTP_MOVED_PERM:\n return \" Moved Permanently\";\n case HTTP_MOVED_TEMP:\n return \" Temporary Redirect\";\n case HTTP_SEE_OTHER:\n return \" See Other\";\n case HTTP_NOT_MODIFIED:\n return \" Not Modified\";\n case HTTP_USE_PROXY:\n return \" Use Proxy\";\n case HTTP_BAD_REQUEST:\n return \" Bad Request\";\n case HTTP_UNAUTHORIZED:\n return \" Unauthorized\";\n case HTTP_PAYMENT_REQUIRED:\n return \" Payment Required\";\n case HTTP_FORBIDDEN:\n return \" Forbidden\";\n case HTTP_NOT_FOUND:\n return \" Not Found\";\n case HTTP_BAD_METHOD:\n return \" Method Not Allowed\";\n case HTTP_NOT_ACCEPTABLE:\n return \" Not Acceptable\";\n case HTTP_PROXY_AUTH:\n return \" Proxy Authentication Required\";\n case HTTP_CLIENT_TIMEOUT:\n return \" Request Time-Out\";\n case HTTP_CONFLICT:\n return \" Conflict\";\n case HTTP_GONE:\n return \" Gone\";\n case HTTP_LENGTH_REQUIRED:\n return \" Length Required\";\n case HTTP_PRECON_FAILED:\n return \" Precondition Failed\";\n case HTTP_ENTITY_TOO_LARGE:\n return \" Request Entity Too Large\";\n case HTTP_REQ_TOO_LONG:\n return \" Request-URI Too Large\";\n case HTTP_UNSUPPORTED_TYPE:\n return \" Unsupported Media Type\";\n case HTTP_INTERNAL_ERROR:\n return \" Internal Server Error\";\n case HTTP_NOT_IMPLEMENTED:\n return \" Not Implemented\";\n case HTTP_BAD_GATEWAY:\n return \" Bad Gateway\";\n case HTTP_UNAVAILABLE:\n return \" Service Unavailable\";\n case HTTP_GATEWAY_TIMEOUT:\n return \" Gateway Timeout\";\n case HTTP_VERSION:\n return \" HTTP Version Not Supported\";\n default:\n return \" \";\n }\n }\n}"
},
{
"identifier": "StubHttpExchange",
"path": "src/test/java/robaho/net/httpserver/StubHttpExchange.java",
"snippet": "public class StubHttpExchange extends HttpExchange {\n @Override\n public Headers getRequestHeaders() {\n return null;\n }\n\n @Override\n public Headers getResponseHeaders() {\n return null;\n }\n\n @Override\n public URI getRequestURI() {\n return null;\n }\n\n @Override\n public String getRequestMethod() {\n return null;\n }\n\n @Override\n public HttpContext getHttpContext() {\n return null;\n }\n\n @Override\n public void close() {\n }\n\n @Override\n public InputStream getRequestBody() {\n return null;\n }\n\n @Override\n public OutputStream getResponseBody() {\n return null;\n }\n\n @Override\n public void sendResponseHeaders(int rCode, long responseLength) {\n }\n\n @Override\n public InetSocketAddress getRemoteAddress() {\n return null;\n }\n\n @Override\n public int getResponseCode() {\n return 0;\n }\n\n @Override\n public InetSocketAddress getLocalAddress() {\n return null;\n }\n\n @Override\n public String getProtocol() {\n return null;\n }\n\n @Override\n public Object getAttribute(String name) {\n return null;\n }\n\n @Override\n public void setAttribute(String name, Object value) {\n }\n\n @Override\n public void setStreams(InputStream i, OutputStream o) {\n }\n\n @Override\n public HttpPrincipal getPrincipal() {\n return null;\n }\n}"
}
] | import static org.testng.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import robaho.net.httpserver.Code;
import robaho.net.httpserver.StubHttpExchange; | 2,217 | package robaho.net.httpserver.websockets;
/*
* #%L
* NanoHttpd-Websocket
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
public class WebSocketResponseHandlerTest {
Headers headers;
WebSocketHandler handler;
HttpExchange exchange;
@BeforeMethod
public void setUp() {
this.headers = new Headers();
this.headers.add("upgrade", "websocket");
this.headers.add("connection", "Upgrade");
this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw==");
this.headers.add("sec-websocket-protocol", "chat, superchat");
this.headers.add("sec-websocket-version", "13");
handler = new TestWebsocketHandler();
exchange = new TestHttpExchange(headers, new Headers());
}
private static class TestWebsocketHandler extends WebSocketHandler {
@Override
protected WebSocket openWebSocket(HttpExchange exchange) {
return new TestWebSocket(exchange);
}
private static class TestWebSocket extends WebSocket {
TestWebSocket(HttpExchange exchange) {
super(exchange);
}
protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) {
}
@Override
protected void onMessage(WebSocketFrame message) throws WebSocketException {
}
@Override
protected void onPong(WebSocketFrame pong) throws WebSocketException {
}
}
}
| package robaho.net.httpserver.websockets;
/*
* #%L
* NanoHttpd-Websocket
* %%
* Copyright (C) 2012 - 2015 nanohttpd
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the nanohttpd nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
public class WebSocketResponseHandlerTest {
Headers headers;
WebSocketHandler handler;
HttpExchange exchange;
@BeforeMethod
public void setUp() {
this.headers = new Headers();
this.headers.add("upgrade", "websocket");
this.headers.add("connection", "Upgrade");
this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw==");
this.headers.add("sec-websocket-protocol", "chat, superchat");
this.headers.add("sec-websocket-version", "13");
handler = new TestWebsocketHandler();
exchange = new TestHttpExchange(headers, new Headers());
}
private static class TestWebsocketHandler extends WebSocketHandler {
@Override
protected WebSocket openWebSocket(HttpExchange exchange) {
return new TestWebSocket(exchange);
}
private static class TestWebSocket extends WebSocket {
TestWebSocket(HttpExchange exchange) {
super(exchange);
}
protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) {
}
@Override
protected void onMessage(WebSocketFrame message) throws WebSocketException {
}
@Override
protected void onPong(WebSocketFrame pong) throws WebSocketException {
}
}
}
| private static class TestHttpExchange extends StubHttpExchange { | 1 | 2023-10-15 15:56:58+00:00 | 4k |
ImCodist/funny-bfdi | src/main/java/xyz/imcodist/funnybfdi/features/BFDIHeadFeature.java | [
{
"identifier": "FunnyBFDI",
"path": "src/main/java/xyz/imcodist/funnybfdi/FunnyBFDI.java",
"snippet": "public class FunnyBFDI implements ModInitializer {\n public static final String MOD_ID = \"funnybfdi\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n @Override\n public void onInitialize() {\n MidnightConfig.init(MOD_ID, Config.class);\n }\n}"
},
{
"identifier": "Config",
"path": "src/main/java/xyz/imcodist/funnybfdi/other/Config.java",
"snippet": "public class Config extends MidnightConfig {\n @Entry public static boolean enabled = true;\n\n @Comment(centered = true) public static Comment mouthCategory;\n @Entry(isSlider = true, min = 0.2f, max = 1.8f) public static float mouthSpeed = 1.0f;\n @Entry public static boolean mouthTransitions = true;\n\n @Comment(centered = true) public static Comment mouthTransformCategory;\n @Entry(isSlider = true, min = 0.0f, max = 2.0f) public static float mouthSize = 1.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetX = 0.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetY = 0.0f;\n @Entry(min = -150.0f, max = 150.0f) public static float mouthOffsetZ = 0.0f;\n}"
},
{
"identifier": "MouthManager",
"path": "src/main/java/xyz/imcodist/funnybfdi/other/MouthManager.java",
"snippet": "public class MouthManager {\n private static final ArrayList<MouthState> playerMouths = new ArrayList<>();\n\n public static void tick() {\n if (!Config.enabled) {\n if (playerMouths.size() > 0) {\n playerMouths.clear();\n }\n\n return;\n }\n\n playerMouths.forEach(MouthState::tick);\n playerMouths.removeIf(mouthState -> mouthState.queueForDeletion);\n }\n\n public static void onPlayerChatted(Text message, UUID senderUUID) {\n if (!Config.enabled) return;\n\n MouthState mouthState = getOrCreatePlayerMouthState(senderUUID);\n\n mouthState.talkCharacter = 0;\n mouthState.talkText = message.getString();\n mouthState.updateMouthShape();\n\n mouthState.talking = true;\n }\n\n public static MouthState getOrCreatePlayerMouthState(UUID playerUUID) {\n MouthState getState = getPlayerMouthState(playerUUID);\n if (getState != null) return getState;\n\n\n MouthState newPlayerState = new MouthState();\n newPlayerState.playerUUID = playerUUID;\n playerMouths.add(newPlayerState);\n\n return newPlayerState;\n }\n\n public static MouthState getPlayerMouthState(UUID playerUUID) {\n for (MouthState mouthState : playerMouths) {\n if (mouthState.playerUUID.equals(playerUUID)) {\n return mouthState;\n }\n }\n\n return null;\n }\n\n public static class MouthState {\n public UUID playerUUID;\n\n public boolean queueForDeletion = false;\n\n public boolean talking = false;\n\n public String talkText = \"\";\n public int talkCharacter = 0;\n\n public String currentMouthShape = \"0\";\n public String transitionMouthShape = currentMouthShape;\n\n private double talkTimer = 0.0;\n\n public void tick() {\n if (talking) {\n talkTimer += 0.75 * Config.mouthSpeed;\n\n if (talkTimer >= 1.0) {\n if (talkCharacter >= talkText.length() - 1) {\n talking = false;\n queueForDeletion = true;\n }\n\n if (talkCharacter < talkText.length()) {\n talkCharacter += 1;\n if (talkCharacter >= talkText.length()) talkCharacter = talkText.length() - 1;\n\n updateMouthShape();\n }\n\n talkTimer -= 1.0;\n }\n\n if (Config.mouthTransitions) {\n if (currentMouthShape.equals(\"8\")) {\n transitionMouthShape = switch (transitionMouthShape) {\n case \"9\" -> \"7\";\n case \"7\", \"8\" -> \"8\";\n default -> \"9\";\n };\n } else {\n if (transitionMouthShape.equals(\"8\") || transitionMouthShape.equals(\"7\")) {\n transitionMouthShape = \"9\";\n } else if (transitionMouthShape.equals(\"3\") && !currentMouthShape.equals(\"3\")) {\n transitionMouthShape = \"2\";\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n }\n\n public void updateMouthShape() {\n String character = String.valueOf(talkText.charAt(talkCharacter));\n\n transitionMouthShape = currentMouthShape;\n currentMouthShape = switch (character.toLowerCase()) {\n case \"a\", \"e\", \"u\" -> \"2\";\n case \"i\" -> \"3\";\n case \"o\", \"r\" -> \"8\";\n case \"m\", \"p\", \"b\" -> \"6\";\n case \"f\", \"v\" -> \"5\";\n case \"l\" -> \"4\";\n case \"t\", \"d\", \"k\", \"g\", \"n\", \"s\", \" \" -> \"0\";\n default -> \"1\";\n };\n }\n }\n}"
}
] | import net.minecraft.client.model.*;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.ModelWithHead;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.RotationAxis;
import xyz.imcodist.funnybfdi.FunnyBFDI;
import xyz.imcodist.funnybfdi.other.Config;
import xyz.imcodist.funnybfdi.other.MouthManager; | 2,304 | package xyz.imcodist.funnybfdi.features;
public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> {
private final ModelPart base;
public BFDIHeadFeature(FeatureRendererContext<T, M> context) {
super(context);
ModelData modelData = new ModelData();
ModelPartData modelPartData = modelData.getRoot();
modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F));
TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16);
this.base = texturedModelData.createModel().getChild("mouth");
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (!Config.enabled) return;
if (Config.mouthSize <= 0.0f) return;
ModelPart head = getContextModel().getHead();
if (entity.isInvisible()) return;
if (!head.visible) return;
MouthManager.MouthState mouthState = MouthManager.getPlayerMouthState(entity.getUuid());
String mouthExpression = "normal";
if (entity.getHealth() <= 10) {
// when less then half health
mouthExpression = "sad";
}
String mouth = "idle";
// status effects
boolean hasAbsorb = false;
boolean hasPoison = false;
for (StatusEffectInstance effectInstance : entity.getStatusEffects()) {
if (effectInstance.getEffectType().equals(StatusEffects.ABSORPTION)) {
hasAbsorb = true;
continue;
}
if (effectInstance.getEffectType().equals(StatusEffects.POISON)) {
hasPoison = true;
}
}
// absorption
if (mouthExpression.equals("normal") && hasAbsorb) {
mouthExpression = "normal";
mouth = "absorption";
}
// is at critical hearts (shaky health bar oooo)
if (entity.getHealth() <= 4) {
mouthExpression = "sad";
mouth = "critical";
}
if (entity.isSubmergedInWater()) {
mouth = "water";
}
// is talking
if (mouthState != null && mouthState.talking) {
String shape = mouthState.transitionMouthShape;
if (!shape.equals("0")) {
if (!mouth.equals("absorption") && !mouth.equals("critical") && !mouth.equals("water")) {
mouth = "talk" + shape;
} else {
mouth = mouth + "talk";
}
} else {
if (mouth.equals("water")) mouth = mouth + "talkclosed";
}
} else {
if (hasPoison) {
mouthExpression = "special";
mouth = "poison";
}
}
// is hurt
if (entity.hurtTime > 0) {
mouthExpression = "special";
mouth = "hurt";
}
| package xyz.imcodist.funnybfdi.features;
public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> {
private final ModelPart base;
public BFDIHeadFeature(FeatureRendererContext<T, M> context) {
super(context);
ModelData modelData = new ModelData();
ModelPartData modelPartData = modelData.getRoot();
modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F));
TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16);
this.base = texturedModelData.createModel().getChild("mouth");
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (!Config.enabled) return;
if (Config.mouthSize <= 0.0f) return;
ModelPart head = getContextModel().getHead();
if (entity.isInvisible()) return;
if (!head.visible) return;
MouthManager.MouthState mouthState = MouthManager.getPlayerMouthState(entity.getUuid());
String mouthExpression = "normal";
if (entity.getHealth() <= 10) {
// when less then half health
mouthExpression = "sad";
}
String mouth = "idle";
// status effects
boolean hasAbsorb = false;
boolean hasPoison = false;
for (StatusEffectInstance effectInstance : entity.getStatusEffects()) {
if (effectInstance.getEffectType().equals(StatusEffects.ABSORPTION)) {
hasAbsorb = true;
continue;
}
if (effectInstance.getEffectType().equals(StatusEffects.POISON)) {
hasPoison = true;
}
}
// absorption
if (mouthExpression.equals("normal") && hasAbsorb) {
mouthExpression = "normal";
mouth = "absorption";
}
// is at critical hearts (shaky health bar oooo)
if (entity.getHealth() <= 4) {
mouthExpression = "sad";
mouth = "critical";
}
if (entity.isSubmergedInWater()) {
mouth = "water";
}
// is talking
if (mouthState != null && mouthState.talking) {
String shape = mouthState.transitionMouthShape;
if (!shape.equals("0")) {
if (!mouth.equals("absorption") && !mouth.equals("critical") && !mouth.equals("water")) {
mouth = "talk" + shape;
} else {
mouth = mouth + "talk";
}
} else {
if (mouth.equals("water")) mouth = mouth + "talkclosed";
}
} else {
if (hasPoison) {
mouthExpression = "special";
mouth = "poison";
}
}
// is hurt
if (entity.hurtTime > 0) {
mouthExpression = "special";
mouth = "hurt";
}
| RenderLayer renderLayer = RenderLayer.getEntityTranslucent(new Identifier(FunnyBFDI.MOD_ID, "textures/mouths/" + mouthExpression + "/" + mouth + ".png")); | 0 | 2023-10-18 00:31:52+00:00 | 4k |
ItzGreenCat/SkyImprover | src/main/java/me/greencat/skyimprover/feature/damageSplash/DamageSplash.java | [
{
"identifier": "Config",
"path": "src/main/java/me/greencat/skyimprover/config/Config.java",
"snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashEnable = true;\n @Entry(category = \"render\")\n public static boolean damageSplashCompact = true;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 5.0F)\n public static float damageSplashOffset = 2.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 10.0F)\n public static float damageSplashDuration = 3.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 2.0F)\n public static float damageSplashAnimationSpeed = 0.3F;\n\n @Comment(category = \"misc\")\n public static Comment rainTimer;\n @Entry(category = \"misc\")\n public static boolean rainTimerEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetY = 0.3F;\n @Comment(category = \"misc\")\n public static Comment ferocityCount;\n @Entry(category = \"misc\")\n public static boolean ferocityCountEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetY = 0.4F;\n\n @Comment(category = \"dungeon\")\n public static Comment m3FreezeHelper;\n @Entry(category = \"dungeon\")\n public static boolean m3FreezeHelperEnable = true;\n\n @Comment(category = \"dungeon\")\n public static Comment dungeonDeathMessage;\n @Entry(category = \"dungeon\")\n public static boolean dungeonDeathMessageEnable = true;\n @Entry(category = \"dungeon\")\n public static String dungeonDeathMessageContent = \"BOOM!\";\n @Comment(category = \"dungeon\")\n public static Comment kuudraHelper;\n @Entry(category = \"dungeon\")\n public static boolean kuudraHelperEnable = true;\n}"
},
{
"identifier": "RenderLivingEntityPreEvent",
"path": "src/main/java/me/greencat/skyimprover/event/RenderLivingEntityPreEvent.java",
"snippet": "public interface RenderLivingEntityPreEvent {\n Event<RenderLivingEntityPreEvent> EVENT = EventFactory.createArrayBacked(RenderLivingEntityPreEvent.class,(listeners) -> (entity) -> {\n for(RenderLivingEntityPreEvent event : listeners){\n boolean result = event.render(entity);\n if(!result){\n return false;\n }\n }\n return true;\n });\n boolean render(LivingEntity entity);\n}"
},
{
"identifier": "Module",
"path": "src/main/java/me/greencat/skyimprover/feature/Module.java",
"snippet": "public interface Module {\n void registerEvent();\n}"
},
{
"identifier": "TextRenderUtils",
"path": "src/main/java/me/greencat/skyimprover/utils/TextRenderUtils.java",
"snippet": "public class TextRenderUtils {\n public static final int backgroundColor = new Color(0,0,0,100).getRGB();\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, boolean seeThrough) {\n renderText(context, text, pos, 1, seeThrough);\n }\n\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, float scale, boolean seeThrough) {\n renderText(context, text, pos, scale, 0, seeThrough);\n }\n\n public static void renderText(WorldRenderContext context, Text text, Vec3d pos, float scale, float yOffset, boolean seeThrough) {\n renderText(context, text.asOrderedText(), pos, scale, yOffset, seeThrough);\n }\n public static void renderText(WorldRenderContext context, OrderedText text, Vec3d pos, float scale, float yOffset, boolean seeThrough) {\n MatrixStack matrices = context.matrixStack();\n Vec3d camera = context.camera().getPos();\n TextRenderer textRenderer = MinecraftClient.getInstance().textRenderer;\n\n scale *= 0.025f;\n\n matrices.push();\n matrices.translate(pos.getX() - camera.getX(), pos.getY() - camera.getY(), pos.getZ() - camera.getZ());\n matrices.peek().getPositionMatrix().mul(RenderSystem.getModelViewMatrix());\n matrices.multiply(context.camera().getRotation());\n matrices.scale(-scale, -scale, scale);\n\n Matrix4f positionMatrix = matrices.peek().getPositionMatrix();\n float xOffset = -textRenderer.getWidth(text) / 2f;\n\n Tessellator tessellator = RenderSystem.renderThreadTesselator();\n BufferBuilder buffer = tessellator.getBuffer();\n VertexConsumerProvider.Immediate consumers = VertexConsumerProvider.immediate(buffer);\n\n RenderSystem.depthFunc(seeThrough ? GL11.GL_ALWAYS : GL11.GL_LEQUAL);\n\n textRenderer.draw(text, xOffset, yOffset, 0xFFFFFFFF, false, positionMatrix, consumers, TextRenderer.TextLayerType.SEE_THROUGH, 0, LightmapTextureManager.MAX_LIGHT_COORDINATE);\n consumers.draw();\n\n RenderSystem.depthFunc(GL11.GL_LEQUAL);\n matrices.pop();\n }\n public static void renderHUDText(DrawContext context,int x,int y,Text... text){\n int height = text.length * 10;\n int width = 0;\n for(Text t : text){\n int length = MinecraftClient.getInstance().textRenderer.getWidth(t.asOrderedText());\n if(length > width){\n width = length;\n }\n }\n context.fill(x - 3,y - 3,x + width + 3,y + height + 3,backgroundColor);\n for(int i = 0;i < text.length;i++){\n context.drawText(MinecraftClient.getInstance().textRenderer,text[i],x,y + i * 10,Color.WHITE.getRGB(),false);\n }\n }\n}"
}
] | import me.greencat.skyimprover.config.Config;
import me.greencat.skyimprover.event.RenderLivingEntityPreEvent;
import me.greencat.skyimprover.feature.Module;
import me.greencat.skyimprover.utils.TextRenderUtils;
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext;
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.decoration.ArmorStandEntity;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.math.Vec3d;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 1,815 | package me.greencat.skyimprover.feature.damageSplash;
public class DamageSplash implements Module {
private static final Pattern pattern = Pattern.compile("[✧✯]?(\\d{1,3}(?:,\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)");
private static final Deque<RenderInformation> damages = new LinkedList<>();
private static final DecimalFormat decimalFormat = new DecimalFormat("0.00");
private static final Random random = new Random();
@Override
public void registerEvent() { | package me.greencat.skyimprover.feature.damageSplash;
public class DamageSplash implements Module {
private static final Pattern pattern = Pattern.compile("[✧✯]?(\\d{1,3}(?:,\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)");
private static final Deque<RenderInformation> damages = new LinkedList<>();
private static final DecimalFormat decimalFormat = new DecimalFormat("0.00");
private static final Random random = new Random();
@Override
public void registerEvent() { | RenderLivingEntityPreEvent.EVENT.register(DamageSplash::onRenderEntity); | 1 | 2023-10-19 09:19:09+00:00 | 4k |
zilliztech/kafka-connect-milvus | src/main/java/com/milvus/io/kafka/MilvusSinkTask.java | [
{
"identifier": "MilvusClientHelper",
"path": "src/main/java/com/milvus/io/kafka/helper/MilvusClientHelper.java",
"snippet": "public class MilvusClientHelper {\n public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) {\n ConnectParam connectParam = ConnectParam.newBuilder()\n .withUri(config.getUrl())\n .withToken(Utils.decryptToken(config.getToken().value()))\n .build();\n return new MilvusServiceClient(connectParam);\n }\n}"
},
{
"identifier": "DataConverter",
"path": "src/main/java/com/milvus/io/kafka/utils/DataConverter.java",
"snippet": "public class DataConverter {\n\n private final MilvusSinkConnectorConfig config;\n\n private static final Logger log = LoggerFactory.getLogger(DataConverter.class);\n\n public DataConverter(MilvusSinkConnectorConfig config) {\n this.config = config;\n }\n /*\n * Convert SinkRecord to List<InsertParam.Field>\n */\n public List<InsertParam.Field> convertRecord(SinkRecord sr, CollectionSchema collectionSchema) {\n // parse sinkRecord to get filed name and value\n if(sr.value() instanceof Struct) {\n return parseValue((Struct)sr.value(), collectionSchema);\n }else if (sr.value() instanceof HashMap) {\n return parseValue((HashMap<?, ?>)sr.value(), collectionSchema);\n }else {\n throw new RuntimeException(\"Unsupported SinkRecord data type\" + sr.value());\n }\n }\n\n private List<InsertParam.Field> parseValue(HashMap<?, ?> mapValue, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = new ArrayList<>();\n // convert collectionSchema.getFieldsList: Filed's Name and DataType to a Map\n Map<String, DataType> fieldType = collectionSchema.getFieldsList().stream().collect(Collectors.toMap(FieldSchema::getName, FieldSchema::getDataType));\n mapValue.forEach((key1, value) -> {\n // for each field, create a InsertParam.Field\n if(fieldType.containsKey(key1.toString())){\n // if the key exists in the collection, store the value by collectionSchema DataType\n fields.add(new InsertParam.Field(key1.toString(), Collections.singletonList(castValueToType(value, fieldType.get(key1.toString())))));\n }else if(collectionSchema.getEnableDynamicField()){\n // if the key not exists in the collection and the collection is dynamic, store the value directly\n fields.add(new InsertParam.Field(key1.toString(), Collections.singletonList(value)));\n }\n });\n return fields;\n }\n\n private List<InsertParam.Field> parseValue(Struct structValue, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = new ArrayList<>();\n // convert collectionSchema.getFieldsList: Filed's Name and DataType to a Map\n Map<String, DataType> fieldType = collectionSchema.getFieldsList().stream().collect(Collectors.toMap(FieldSchema::getName, FieldSchema::getDataType));\n structValue.schema().fields().forEach(field -> {\n // for each field, create a InsertParam.Field\n if(fieldType.containsKey(field.name())){\n // if the key exists in the collection, store the value by collectionSchema DataType\n fields.add(new InsertParam.Field(field.name(), Collections.singletonList(castValueToType(structValue.get(field.name()), fieldType.get(field.name())))));\n }else if(collectionSchema.getEnableDynamicField()){\n // if the key not exists in the collection and the collection is dynamic, store the value directly\n fields.add(new InsertParam.Field(field.name(), Collections.singletonList(structValue.get(field.name()))));\n }\n });\n\n return fields;\n }\n\n private Object castValueToType(Object value, DataType dataType) {\n switch (dataType){\n case Bool:\n return Boolean.parseBoolean(value.toString());\n case Int8:\n case Int16:\n return Short.parseShort(value.toString());\n case Int32:\n return Integer.parseInt(value.toString());\n case Int64:\n return Long.parseLong(value.toString());\n case Float:\n return Float.parseFloat(value.toString());\n case Double:\n return Double.parseDouble(value.toString());\n case VarChar:\n case String:\n return value.toString();\n case JSON:\n Gson gson = new Gson();\n return gson.toJson(value);\n case BinaryVector:\n return parseBinaryVectorField(value.toString());\n case FloatVector:\n return parseFloatVectorField(value.toString());\n default:\n throw new RuntimeException(\"Unsupported data type\" + dataType);\n }\n }\n\n protected List<Float> parseFloatVectorField(String vectors){\n try {\n log.debug(\"parse float vectors: {}\", vectors);\n\n String[] vectorArrays = vectors.replaceAll(\"\\\\[\", \"\").replaceAll(\"\\\\]\", \"\")\n .replaceAll(\" \",\"\").split(\",\");\n\n List<Float> floatList = Lists.newLinkedList();\n for (String vector : vectorArrays) {\n floatList.add(Float.valueOf(vector));\n }\n\n return floatList;\n }catch (Exception e){\n throw new RuntimeException(\"parse float vector field error: \" + e.getMessage() + vectors);\n }\n\n }\n protected ByteBuffer parseBinaryVectorField(String vectors){\n try {\n log.debug(\"parse binary vectors: {}\", vectors);\n\n String[] vectorArrays = vectors.replaceAll(\"\\\\[\", \"\").replaceAll(\"\\\\]\", \"\")\n .replaceAll(\" \", \"\").split(\",\");\n\n ByteBuffer buffer = ByteBuffer.allocate(vectorArrays.length);\n for (String vectorArray : vectorArrays) {\n int vector = Integer.parseInt(vectorArray);\n buffer.put((byte) vector);\n }\n\n return buffer;\n }catch (Exception e){\n throw new RuntimeException(\"parse binary vector field error: \" + e.getMessage() + vectors);\n }\n }\n\n public List<JSONObject> convertRecordWithDynamicSchema(SinkRecord sr, CollectionSchema collectionSchema) {\n List<InsertParam.Field> fields = convertRecord(sr, collectionSchema);\n List<JSONObject> jsonObjects = new ArrayList<>();\n int rows = fields.get(0).getValues().size();\n for (int i = 0; i < rows; i++) {\n JSONObject jsonObject = new JSONObject();\n for (InsertParam.Field field : fields) {\n jsonObject.put(field.getName(), field.getValues().get(i));\n }\n jsonObjects.add(jsonObject);\n }\n return jsonObjects;\n }\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/com/milvus/io/kafka/utils/Utils.java",
"snippet": "public class Utils {\n private static final Logger log = LoggerFactory.getLogger(Utils.class);\n private static final SecretKey SECRET_KEY = generateSecretKey();\n\n public static String encryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8));\n return Base64.getEncoder().encodeToString(encryptedBytes);\n } catch (Exception e) {\n // Handle encryption errors\n log.error(\"encryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static String decryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = Base64.getDecoder().decode(token);\n byte[] decryptedBytes = cipher.doFinal(encryptedBytes);\n\n return new String(decryptedBytes, StandardCharsets.UTF_8);\n } catch (Exception e) {\n // Handle decryption errors\n log.error(\"decryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static SecretKey generateSecretKey() {\n try {\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"AES\");\n SecureRandom secureRandom = new SecureRandom();\n keyGenerator.init(128, secureRandom);\n return keyGenerator.generateKey();\n } catch (NoSuchAlgorithmException e) {\n log.error(e.getMessage());\n return null;\n }\n }\n\n}"
},
{
"identifier": "VersionUtil",
"path": "src/main/java/com/milvus/io/kafka/utils/VersionUtil.java",
"snippet": "public final class VersionUtil {\n private static final String VERSION;\n\n static {\n Properties prop = new Properties();\n try (InputStream in = VersionUtil.class.getResourceAsStream(\"/kafka-connect-milvus.properties\")) {\n prop.load(in);\n VERSION = prop.getProperty(\"version\", \"0.0.0.0\");\n } catch (IOException e) {\n throw new ExceptionInInitializerError(e);\n }\n }\n\n public static String getVersion() {\n return VERSION;\n }\n}"
},
{
"identifier": "TOKEN",
"path": "src/main/java/com/milvus/io/kafka/MilvusSinkConnectorConfig.java",
"snippet": "protected static final String TOKEN = \"token\";"
}
] | import com.milvus.io.kafka.helper.MilvusClientHelper;
import com.milvus.io.kafka.utils.DataConverter;
import com.milvus.io.kafka.utils.Utils;
import com.milvus.io.kafka.utils.VersionUtil;
import io.milvus.client.MilvusServiceClient;
import io.milvus.grpc.CollectionSchema;
import io.milvus.grpc.DescribeCollectionResponse;
import io.milvus.grpc.GetLoadStateResponse;
import io.milvus.grpc.LoadState;
import io.milvus.param.R;
import io.milvus.param.collection.DescribeCollectionParam;
import io.milvus.param.collection.GetLoadStateParam;
import io.milvus.param.dml.InsertParam;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static com.milvus.io.kafka.MilvusSinkConnectorConfig.TOKEN; | 2,341 | package com.milvus.io.kafka;
public class MilvusSinkTask extends SinkTask {
private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class);
private MilvusSinkConnectorConfig config;
private MilvusServiceClient myMilvusClient;
private DataConverter converter;
private CollectionSchema collectionSchema;
@Override
public String version() { | package com.milvus.io.kafka;
public class MilvusSinkTask extends SinkTask {
private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class);
private MilvusSinkConnectorConfig config;
private MilvusServiceClient myMilvusClient;
private DataConverter converter;
private CollectionSchema collectionSchema;
@Override
public String version() { | return VersionUtil.getVersion(); | 3 | 2023-10-18 02:11:08+00:00 | 4k |
histevehu/12306 | generator/src/main/java/com/steve/train/generator/gen/EnumGenerator.java | [
{
"identifier": "ConfirmOrderStatusEnum",
"path": "business/src/main/java/com/steve/train/business/enums/ConfirmOrderStatusEnum.java",
"snippet": "public enum ConfirmOrderStatusEnum {\n // 订单刚进系统\n INIT(\"I\", \"初始\"),\n // 订单选票中\n PENDING(\"P\", \"处理中\"),\n SUCCESS(\"S\", \"成功\"),\n FAILURE(\"F\", \"失败\"),\n // 库存不足\n EMPTY(\"E\", \"无票\"),\n // 排队选票中取消\n CANCEL(\"C\", \"取消\");\n\n private String code;\n\n private String desc;\n\n ConfirmOrderStatusEnum(String code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n @Override\n public String toString() {\n return \"ConfirmOrderStatusEnum{\" +\n \"code='\" + code + '\\'' +\n \", desc='\" + desc + '\\'' +\n \"} \" + super.toString();\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public String getDesc() {\n return desc;\n }\n\n}"
},
{
"identifier": "SeatColEnum",
"path": "common/src/main/java/com/steve/train/common/enums/SeatColEnum.java",
"snippet": "public enum SeatColEnum {\n\n YDZ_A(\"A\", \"A\", \"1\"),\n YDZ_C(\"C\", \"C\", \"1\"),\n YDZ_D(\"D\", \"D\", \"1\"),\n YDZ_F(\"F\", \"F\", \"1\"),\n EDZ_A(\"A\", \"A\", \"2\"),\n EDZ_B(\"B\", \"B\", \"2\"),\n EDZ_C(\"C\", \"C\", \"2\"),\n EDZ_D(\"D\", \"D\", \"2\"),\n EDZ_F(\"F\", \"F\", \"2\");\n\n private String code;\n\n private String desc;\n\n /**\n * 对应SeatTypeEnum.code\n */\n private String type;\n\n SeatColEnum(String code, String desc, String type) {\n this.code = code;\n this.desc = desc;\n this.type = type;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n /**\n * 根据车箱的座位类型,筛选出所有的列,比如车箱类型是一等座,则筛选出columnList={ACDF}\n */\n public static List<SeatColEnum> getColsByType(String seatType) {\n List<SeatColEnum> colList = new ArrayList<>();\n EnumSet<SeatColEnum> seatColEnums = EnumSet.allOf(SeatColEnum.class);\n for (SeatColEnum anEnum : seatColEnums) {\n if (seatType.equals(anEnum.getType())) {\n colList.add(anEnum);\n }\n }\n return colList;\n }\n\n}"
},
{
"identifier": "SeatTypeEnum",
"path": "common/src/main/java/com/steve/train/common/enums/SeatTypeEnum.java",
"snippet": "public enum SeatTypeEnum {\n\n YDZ(\"1\", \"一等座\", new BigDecimal(\"0.4\")),\n EDZ(\"2\", \"二等座\", new BigDecimal(\"0.3\")),\n RW(\"3\", \"软卧\", new BigDecimal(\"0.6\")),\n YW(\"4\", \"硬卧\", new BigDecimal(\"0.5\"));\n\n private String code;\n\n private String desc;\n\n /**\n * 基础票价 N元/公里,0.4即为0.4元/公里\n */\n private BigDecimal price;\n\n SeatTypeEnum(String code, String desc, BigDecimal price) {\n this.code = code;\n this.desc = desc;\n this.price = price;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public BigDecimal getPrice() {\n return price;\n }\n\n public void setPrice(BigDecimal price) {\n this.price = price;\n }\n\n public static List<HashMap<String,String>> getEnumList() {\n List<HashMap<String, String>> list = new ArrayList<>();\n for (SeatTypeEnum anEnum : EnumSet.allOf(SeatTypeEnum.class)) {\n HashMap<String, String> map = new HashMap<>();\n map.put(\"code\",anEnum.code);\n map.put(\"desc\",anEnum.desc);\n list.add(map);\n }\n return list;\n }\n\n public static SeatTypeEnum getEnumByCode(String code) {\n for (SeatTypeEnum enums : SeatTypeEnum.values()) {\n if (enums.getCode().equalsIgnoreCase(code)) {\n return enums;\n }\n }\n return null;\n }\n}"
},
{
"identifier": "TrainTypeEnum",
"path": "common/src/main/java/com/steve/train/common/enums/TrainTypeEnum.java",
"snippet": "public enum TrainTypeEnum {\n\n G(\"G\", \"高铁\", new BigDecimal(\"1.2\")),\n D(\"D\", \"动车\", new BigDecimal(\"1\")),\n K(\"K\", \"快速\", new BigDecimal(\"0.8\"));\n\n private String code;\n\n private String desc;\n\n /**\n * 票价比例,例:1.1,则票价 = 1.1 * 每公里单价(SeatTypeEnum.price) * 公里(station.km)\n */\n private BigDecimal priceRate;\n\n TrainTypeEnum(String code, String desc, BigDecimal priceRate) {\n this.code = code;\n this.desc = desc;\n this.priceRate = priceRate;\n }\n\n @Override\n public String toString() {\n return \"TrainTypeEnum{\" +\n \"code='\" + code + '\\'' +\n \", desc='\" + desc + '\\'' +\n \", priceRate=\" + priceRate +\n \"} \" + super.toString();\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public BigDecimal getPriceRate() {\n return priceRate;\n }\n\n public void setPriceRate(BigDecimal priceRate) {\n this.priceRate = priceRate;\n }\n\n public static List<HashMap<String,String>> getEnumList() {\n List<HashMap<String, String>> list = new ArrayList<>();\n for (TrainTypeEnum anEnum : EnumSet.allOf(TrainTypeEnum.class)) {\n HashMap<String, String> map = new HashMap<>();\n map.put(\"code\",anEnum.code);\n map.put(\"desc\",anEnum.desc);\n list.add(map);\n }\n return list;\n }\n}"
},
{
"identifier": "PassengerTypeEnum",
"path": "member/src/main/java/com/steve/train/member/enums/PassengerTypeEnum.java",
"snippet": "public enum PassengerTypeEnum {\n\n ADULT(\"1\", \"成人\"),\n CHILD(\"2\", \"儿童\"),\n STUDENT(\"3\", \"学生\");\n\n private String code;\n\n private String desc;\n\n PassengerTypeEnum(String code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public void setDesc(String desc) {\n this.desc = desc;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public static List<HashMap<String,String>> getEnumList() {\n List<HashMap<String, String>> list = new ArrayList<>();\n for (PassengerTypeEnum anEnum : EnumSet.allOf(PassengerTypeEnum.class)) {\n HashMap<String, String> map = new HashMap<>();\n map.put(\"code\",anEnum.code);\n map.put(\"desc\",anEnum.desc);\n list.add(map);\n }\n return list;\n }\n}"
}
] | import cn.hutool.core.util.StrUtil;
import com.steve.train.business.enums.ConfirmOrderStatusEnum;
import com.steve.train.common.enums.SeatColEnum;
import com.steve.train.common.enums.SeatTypeEnum;
import com.steve.train.common.enums.TrainTypeEnum;
import com.steve.train.member.enums.PassengerTypeEnum;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List; | 2,328 | package com.steve.train.generator.gen;
public class EnumGenerator {
static String path = "admin/src/assets/js/enums.js";
public static void main(String[] args) {
// 生成的JSON枚举对象
StringBuffer bufferObject = new StringBuffer();
// 生成的JSON枚举数组
StringBuffer bufferArray = new StringBuffer();
long begin = System.currentTimeMillis();
try {
toJson(PassengerTypeEnum.class, bufferObject, bufferArray);
toJson(TrainTypeEnum.class, bufferObject, bufferArray);
toJson(SeatTypeEnum.class, bufferObject, bufferArray);
toJson(SeatColEnum.class, bufferObject, bufferArray); | package com.steve.train.generator.gen;
public class EnumGenerator {
static String path = "admin/src/assets/js/enums.js";
public static void main(String[] args) {
// 生成的JSON枚举对象
StringBuffer bufferObject = new StringBuffer();
// 生成的JSON枚举数组
StringBuffer bufferArray = new StringBuffer();
long begin = System.currentTimeMillis();
try {
toJson(PassengerTypeEnum.class, bufferObject, bufferArray);
toJson(TrainTypeEnum.class, bufferObject, bufferArray);
toJson(SeatTypeEnum.class, bufferObject, bufferArray);
toJson(SeatColEnum.class, bufferObject, bufferArray); | toJson(ConfirmOrderStatusEnum.class, bufferObject, bufferArray); | 0 | 2023-10-23 01:20:56+00:00 | 4k |
aws-samples/trading-latency-benchmark | src/main/java/com/aws/trading/ExchangeClientLatencyTestHandler.java | [
{
"identifier": "COIN_PAIRS",
"path": "src/main/java/com/aws/trading/Config.java",
"snippet": "public static final List<String> COIN_PAIRS;"
},
{
"identifier": "printResults",
"path": "src/main/java/com/aws/trading/RoundTripLatencyTester.java",
"snippet": "public static synchronized void printResults(SingleWriterRecorder hdr, long orderResponseCount) {\n long currentTime = System.nanoTime();\n var executionTime = currentTime - testStartTime;\n MESSAGE_COUNTER.add(orderResponseCount);\n\n var messageCount = MESSAGE_COUNTER.longValue();\n if (messageCount < WARMUP_COUNT * TEST_SIZE) {\n LOGGER.info(\"warming up... - message count: {}\", messageCount);\n return;\n }\n\n HISTOGRAM.add(hdr.getIntervalHistogram());\n if (messageCount % REPORT_SIZE == 0) {\n var executionTimeStr = LatencyTools.formatNanos(executionTime);\n var messagePerSecond = messageCount / TimeUnit.SECONDS.convert(executionTime, TimeUnit.NANOSECONDS);\n var logMsg = \"\\nTest Execution Time: {}s \\n Number of messages: {} \\n Message Per Second: {} \\n Percentiles: {} \\n\";\n\n try (PrintStream histogramLogFile = getLogFile()) {\n saveHistogramToFile(currentTime, histogramLogFile);\n histogramStartTime = currentTime;\n } catch (IOException e) {\n LOGGER.error(e);\n }\n\n LinkedHashMap<String, String> latencyReport = LatencyTools.createLatencyReport(HISTOGRAM);\n LOGGER.info(logMsg,\n executionTimeStr, messageCount, messagePerSecond, LatencyTools.toJSON(latencyReport)\n );\n\n hdr.reset();\n HISTOGRAM.reset();\n }\n}"
}
] | import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import org.HdrHistogram.SingleWriterRecorder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import static com.aws.trading.Config.COIN_PAIRS;
import static com.aws.trading.RoundTripLatencyTester.printResults; | 2,330 | throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
+ response.content().toString(CharsetUtil.UTF_8) + ')');
}
final WebSocketFrame frame = (WebSocketFrame) msg;
if (frame instanceof TextWebSocketFrame) {
this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame);
} else if (frame instanceof PongWebSocketFrame) {
} else if (frame instanceof CloseWebSocketFrame) {
LOGGER.info("received CloseWebSocketFrame, closing the channel");
ch.close();
} else if (frame instanceof BinaryWebSocketFrame) {
LOGGER.info(frame.content().toString());
}
}
private TextWebSocketFrame subscribeMessage() {
return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG));
}
private TextWebSocketFrame authMessage() {
return new TextWebSocketFrame(Unpooled.wrappedBuffer(
ExchangeProtocolImpl.AUTH_MSG_HEADER,
Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8),
ExchangeProtocolImpl.MSG_END)
);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
LOGGER.error(cause);
if (!handshakeFuture.isDone()) {
handshakeFuture.setFailure(cause);
}
ctx.close();
}
public ChannelPromise getHandshakeFuture() {
return handshakeFuture;
}
private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException {
long eventReceiveTime = System.nanoTime();
ByteBuf buf = textFrame.content();
final byte[] bytes;
int offset = 0;
final int length = buf.readableBytes();
if (buf.hasArray()) {
bytes = buf.array();
offset = buf.arrayOffset();
} else {
bytes = new byte[length];
buf.getBytes(buf.readerIndex(), bytes);
}
buf.clear();
buf.release();
JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8);
Object type = parsedObject.getString("type");
if ("BOOKED".equals(type) || type.equals("DONE")) {
//LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject);
String clientId = parsedObject.getString("client_id");
if (type.equals("BOOKED")) {
if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return;
var pair = parsedObject.getString("instrument_code");
sendCancelOrder(ctx, clientId, pair);
} else {
if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return;
sendOrder(ctx);
}
if (orderResponseCount % test_size == 0) {
printResults(hdrRecorderForAggregation, test_size);
}
} else if ("AUTHENTICATED".equals(type)) {
LOGGER.info("{}", parsedObject);
ctx.channel().writeAndFlush(subscribeMessage());
} else if ("SUBSCRIPTIONS".equals(type)) {
LOGGER.info("{}", parsedObject);
this.testStartTime = System.nanoTime();
sendOrder(ctx);
} else {
LOGGER.error("Unhandled object {}", parsedObject);
}
}
private void sendCancelOrder(ChannelHandlerContext ctx, String clientId, String pair) {
TextWebSocketFrame cancelOrder = protocol.createCancelOrder(pair, clientId);
//LOGGER.info("Sending cancel order seq: {}, order: {}", sequence, cancelOrder.toString(StandardCharsets.UTF_8));
try {
ctx.channel().write(cancelOrder, ctx.channel().voidPromise()).await();
} catch (InterruptedException e) {
LOGGER.error(e);
}
var cancelSentTime = System.nanoTime();
//LOGGER.info("cancel sent time for clientId: {} - {}",clientId, cancelSentTime);
this.cancelSentTimeMap.put(clientId, cancelSentTime);
ctx.channel().flush();
orderResponseCount += 1;
}
private boolean calculateRoundTrip(long eventReceiveTime, String clientId, ConcurrentHashMap<String, Long> cancelSentTimeMap) {
long roundTripTime;
Long cancelSentTime = cancelSentTimeMap.remove(clientId);
if (null == cancelSentTime || eventReceiveTime < cancelSentTime) {
LOGGER.error("no order sent time found for order {}", clientId);
return true;
}
roundTripTime = eventReceiveTime - cancelSentTime;
//LOGGER.info("round trip time for client id {}: {} = {} - {}", clientId, roundTripTime, eventReceiveTime, cancelSentTime);
if (roundTripTime > 0) {
//LOGGER.info("recording round trip time");
hdrRecorderForAggregation.recordValue(roundTripTime);
}
return false;
}
void sendOrder(ChannelHandlerContext ch) throws InterruptedException {
| /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: MIT-0
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.aws.trading;
public class ExchangeClientLatencyTestHandler extends ChannelInboundHandlerAdapter {
private static final Logger LOGGER = LogManager.getLogger(ExchangeClientLatencyTestHandler.class);
private final WebSocketClientHandshaker handshaker;
private final int apiToken;
private final int test_size;
public final URI uri;
private final ExchangeProtocol protocol;
private ChannelPromise handshakeFuture;
private final ConcurrentHashMap<String, Long> orderSentTimeMap;
private final ConcurrentHashMap<String, Long> cancelSentTimeMap;
private long orderResponseCount = 0;
private final SingleWriterRecorder hdrRecorderForAggregation;
private long testStartTime = 0;
private final Random random = new Random();
public ExchangeClientLatencyTestHandler(ExchangeProtocol protocol, URI uri, int apiToken, int test_size) {
this.uri = uri;
this.protocol = protocol;
var header = HttpHeaders.EMPTY_HEADERS;
this.handshaker = WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, false, header, 1280000);
this.apiToken = apiToken;
this.orderSentTimeMap = new ConcurrentHashMap<>(test_size);
this.cancelSentTimeMap = new ConcurrentHashMap<>(test_size);
this.test_size = test_size;
this.hdrRecorderForAggregation = new SingleWriterRecorder(Long.MAX_VALUE, 2);
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
this.handshakeFuture = ctx.newPromise();
}
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
LOGGER.info("channel is active, starting websocket handshaking...");
handshaker.handshake(ctx.channel());
}
@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
LOGGER.info("Websocket client disconnected");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
final Channel ch = ctx.channel();
if (!handshaker.isHandshakeComplete()) {
LOGGER.info("Websocket client is connected");
var m = (FullHttpResponse) msg;
handshaker.finishHandshake(ch, m);
LOGGER.info("Websocket client is authenticating for {}", this.apiToken);
//success, authenticate
var channel = ctx.channel();
channel.write(authMessage());
channel.flush();
handshakeFuture.setSuccess();
return;
}
if (msg instanceof FullHttpResponse) {
final FullHttpResponse response = (FullHttpResponse) msg;
throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content="
+ response.content().toString(CharsetUtil.UTF_8) + ')');
}
final WebSocketFrame frame = (WebSocketFrame) msg;
if (frame instanceof TextWebSocketFrame) {
this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame);
} else if (frame instanceof PongWebSocketFrame) {
} else if (frame instanceof CloseWebSocketFrame) {
LOGGER.info("received CloseWebSocketFrame, closing the channel");
ch.close();
} else if (frame instanceof BinaryWebSocketFrame) {
LOGGER.info(frame.content().toString());
}
}
private TextWebSocketFrame subscribeMessage() {
return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG));
}
private TextWebSocketFrame authMessage() {
return new TextWebSocketFrame(Unpooled.wrappedBuffer(
ExchangeProtocolImpl.AUTH_MSG_HEADER,
Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8),
ExchangeProtocolImpl.MSG_END)
);
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
LOGGER.error(cause);
if (!handshakeFuture.isDone()) {
handshakeFuture.setFailure(cause);
}
ctx.close();
}
public ChannelPromise getHandshakeFuture() {
return handshakeFuture;
}
private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException {
long eventReceiveTime = System.nanoTime();
ByteBuf buf = textFrame.content();
final byte[] bytes;
int offset = 0;
final int length = buf.readableBytes();
if (buf.hasArray()) {
bytes = buf.array();
offset = buf.arrayOffset();
} else {
bytes = new byte[length];
buf.getBytes(buf.readerIndex(), bytes);
}
buf.clear();
buf.release();
JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8);
Object type = parsedObject.getString("type");
if ("BOOKED".equals(type) || type.equals("DONE")) {
//LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject);
String clientId = parsedObject.getString("client_id");
if (type.equals("BOOKED")) {
if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return;
var pair = parsedObject.getString("instrument_code");
sendCancelOrder(ctx, clientId, pair);
} else {
if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return;
sendOrder(ctx);
}
if (orderResponseCount % test_size == 0) {
printResults(hdrRecorderForAggregation, test_size);
}
} else if ("AUTHENTICATED".equals(type)) {
LOGGER.info("{}", parsedObject);
ctx.channel().writeAndFlush(subscribeMessage());
} else if ("SUBSCRIPTIONS".equals(type)) {
LOGGER.info("{}", parsedObject);
this.testStartTime = System.nanoTime();
sendOrder(ctx);
} else {
LOGGER.error("Unhandled object {}", parsedObject);
}
}
private void sendCancelOrder(ChannelHandlerContext ctx, String clientId, String pair) {
TextWebSocketFrame cancelOrder = protocol.createCancelOrder(pair, clientId);
//LOGGER.info("Sending cancel order seq: {}, order: {}", sequence, cancelOrder.toString(StandardCharsets.UTF_8));
try {
ctx.channel().write(cancelOrder, ctx.channel().voidPromise()).await();
} catch (InterruptedException e) {
LOGGER.error(e);
}
var cancelSentTime = System.nanoTime();
//LOGGER.info("cancel sent time for clientId: {} - {}",clientId, cancelSentTime);
this.cancelSentTimeMap.put(clientId, cancelSentTime);
ctx.channel().flush();
orderResponseCount += 1;
}
private boolean calculateRoundTrip(long eventReceiveTime, String clientId, ConcurrentHashMap<String, Long> cancelSentTimeMap) {
long roundTripTime;
Long cancelSentTime = cancelSentTimeMap.remove(clientId);
if (null == cancelSentTime || eventReceiveTime < cancelSentTime) {
LOGGER.error("no order sent time found for order {}", clientId);
return true;
}
roundTripTime = eventReceiveTime - cancelSentTime;
//LOGGER.info("round trip time for client id {}: {} = {} - {}", clientId, roundTripTime, eventReceiveTime, cancelSentTime);
if (roundTripTime > 0) {
//LOGGER.info("recording round trip time");
hdrRecorderForAggregation.recordValue(roundTripTime);
}
return false;
}
void sendOrder(ChannelHandlerContext ch) throws InterruptedException {
| var pair = COIN_PAIRS.get(random.nextInt(COIN_PAIRS.size())); | 0 | 2023-10-22 19:04:39+00:00 | 4k |
team-moabam/moabam-BE | src/main/java/com/moabam/api/application/bug/BugMapper.java | [
{
"identifier": "PaymentMapper",
"path": "src/main/java/com/moabam/api/application/payment/PaymentMapper.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class PaymentMapper {\n\n\tpublic static Payment toPayment(Long memberId, Product product) {\n\t\tOrder order = Order.builder()\n\t\t\t.name(product.getName())\n\t\t\t.build();\n\n\t\treturn Payment.builder()\n\t\t\t.memberId(memberId)\n\t\t\t.product(product)\n\t\t\t.order(order)\n\t\t\t.totalAmount(product.getPrice())\n\t\t\t.build();\n\t}\n\n\tpublic static PaymentResponse toPaymentResponse(Payment payment) {\n\t\treturn Optional.ofNullable(payment)\n\t\t\t.map(p -> PaymentResponse.builder()\n\t\t\t\t.id(p.getId())\n\t\t\t\t.orderName(p.getOrder().getName())\n\t\t\t\t.discountAmount(p.getDiscountAmount())\n\t\t\t\t.totalAmount(p.getTotalAmount())\n\t\t\t\t.build())\n\t\t\t.orElse(null);\n\t}\n\n\tpublic static RequestConfirmPaymentResponse toRequestConfirmPaymentResponse(Payment payment,\n\t\tConfirmTossPaymentResponse response) {\n\t\treturn RequestConfirmPaymentResponse.builder()\n\t\t\t.payment(payment)\n\t\t\t.paymentKey(response.paymentKey())\n\t\t\t.build();\n\t}\n}"
},
{
"identifier": "Bug",
"path": "src/main/java/com/moabam/api/domain/bug/Bug.java",
"snippet": "@Embeddable\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Bug {\n\n\t@Column(name = \"morning_bug\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int morningBug;\n\n\t@Column(name = \"night_bug\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int nightBug;\n\n\t@Column(name = \"golden_bug\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int goldenBug;\n\n\t@Builder\n\tprivate Bug(int morningBug, int nightBug, int goldenBug) {\n\t\tthis.morningBug = validateBugCount(morningBug);\n\t\tthis.nightBug = validateBugCount(nightBug);\n\t\tthis.goldenBug = validateBugCount(goldenBug);\n\t}\n\n\tprivate int validateBugCount(int bug) {\n\t\tif (bug < 0) {\n\t\t\tthrow new BadRequestException(INVALID_BUG_COUNT);\n\t\t}\n\n\t\treturn bug;\n\t}\n\n\tpublic void use(BugType bugType, int count) {\n\t\tint currentBug = getBug(bugType);\n\n\t\tvalidateEnoughBug(currentBug, count);\n\t\tdecrease(bugType, count);\n\t}\n\n\tprivate int getBug(BugType bugType) {\n\t\treturn switch (bugType) {\n\t\t\tcase MORNING -> this.morningBug;\n\t\t\tcase NIGHT -> this.nightBug;\n\t\t\tcase GOLDEN -> this.goldenBug;\n\t\t};\n\t}\n\n\tprivate void validateEnoughBug(int currentBug, int count) {\n\t\tif (currentBug < count) {\n\t\t\tthrow new BadRequestException(BUG_NOT_ENOUGH);\n\t\t}\n\t}\n\n\tprivate void decrease(BugType bugType, int count) {\n\t\tswitch (bugType) {\n\t\t\tcase MORNING -> this.morningBug -= count;\n\t\t\tcase NIGHT -> this.nightBug -= count;\n\t\t\tcase GOLDEN -> this.goldenBug -= count;\n\t\t}\n\t}\n\n\tpublic void increase(BugType bugType, int count) {\n\t\tswitch (bugType) {\n\t\t\tcase MORNING -> this.morningBug += count;\n\t\t\tcase NIGHT -> this.nightBug += count;\n\t\t\tcase GOLDEN -> this.goldenBug += count;\n\t\t}\n\t}\n\n\tpublic void charge(int count) {\n\t\tthis.goldenBug += count;\n\t}\n}"
},
{
"identifier": "BugActionType",
"path": "src/main/java/com/moabam/api/domain/bug/BugActionType.java",
"snippet": "public enum BugActionType {\n\n\tREWARD,\n\tCHARGE,\n\tUSE,\n\tREFUND,\n\tCOUPON;\n}"
},
{
"identifier": "BugHistory",
"path": "src/main/java/com/moabam/api/domain/bug/BugHistory.java",
"snippet": "@Entity\n@Getter\n@Table(name = \"bug_history\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class BugHistory extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"member_id\", updatable = false, nullable = false)\n\tprivate Long memberId;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"payment_id\")\n\tprivate Payment payment;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"bug_type\", nullable = false)\n\tprivate BugType bugType;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"action_type\", nullable = false)\n\tprivate BugActionType actionType;\n\n\t@Column(name = \"quantity\", nullable = false)\n\tprivate int quantity;\n\n\t@Builder\n\tprivate BugHistory(Long memberId, Payment payment, BugType bugType, BugActionType actionType, int quantity) {\n\t\tthis.memberId = requireNonNull(memberId);\n\t\tthis.payment = payment;\n\t\tthis.bugType = requireNonNull(bugType);\n\t\tthis.actionType = requireNonNull(actionType);\n\t\tthis.quantity = validateQuantity(quantity);\n\t}\n\n\tprivate int validateQuantity(int quantity) {\n\t\tif (quantity < 0) {\n\t\t\tthrow new BadRequestException(INVALID_QUANTITY);\n\t\t}\n\n\t\treturn quantity;\n\t}\n}"
},
{
"identifier": "BugType",
"path": "src/main/java/com/moabam/api/domain/bug/BugType.java",
"snippet": "public enum BugType {\n\n\tMORNING,\n\tNIGHT,\n\tGOLDEN;\n\n\tpublic boolean isGoldenBug() {\n\t\treturn this == GOLDEN;\n\t}\n}"
},
{
"identifier": "DateUtils",
"path": "src/main/java/com/moabam/global/common/util/DateUtils.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class DateUtils {\n\n\tprivate static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\");\n\n\tpublic static String format(LocalDateTime dateTime) {\n\t\treturn dateTime.format(formatter);\n\t}\n}"
},
{
"identifier": "StreamUtils",
"path": "src/main/java/com/moabam/global/common/util/StreamUtils.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class StreamUtils {\n\n\tpublic static <T, R> List<R> map(List<T> list, Function<T, R> mapper) {\n\t\treturn list.stream()\n\t\t\t.map(mapper)\n\t\t\t.toList();\n\t}\n}"
}
] | import java.util.List;
import com.moabam.api.application.payment.PaymentMapper;
import com.moabam.api.domain.bug.Bug;
import com.moabam.api.domain.bug.BugActionType;
import com.moabam.api.domain.bug.BugHistory;
import com.moabam.api.domain.bug.BugType;
import com.moabam.api.dto.bug.BugHistoryItemResponse;
import com.moabam.api.dto.bug.BugHistoryResponse;
import com.moabam.api.dto.bug.BugHistoryWithPayment;
import com.moabam.api.dto.bug.BugResponse;
import com.moabam.global.common.util.DateUtils;
import com.moabam.global.common.util.StreamUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor; | 1,937 | package com.moabam.api.application.bug;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class BugMapper {
public static BugResponse toBugResponse(Bug bug) {
return BugResponse.builder()
.morningBug(bug.getMorningBug())
.nightBug(bug.getNightBug())
.goldenBug(bug.getGoldenBug())
.build();
}
public static BugHistoryItemResponse toBugHistoryItemResponse(BugHistoryWithPayment dto) {
return BugHistoryItemResponse.builder()
.id(dto.id())
.bugType(dto.bugType())
.actionType(dto.actionType())
.quantity(dto.quantity())
.date(DateUtils.format(dto.createdAt()))
.payment(PaymentMapper.toPaymentResponse(dto.payment()))
.build();
}
public static BugHistoryResponse toBugHistoryResponse(List<BugHistoryWithPayment> dtoList) {
return BugHistoryResponse.builder()
.history(StreamUtils.map(dtoList, BugMapper::toBugHistoryItemResponse))
.build();
}
| package com.moabam.api.application.bug;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class BugMapper {
public static BugResponse toBugResponse(Bug bug) {
return BugResponse.builder()
.morningBug(bug.getMorningBug())
.nightBug(bug.getNightBug())
.goldenBug(bug.getGoldenBug())
.build();
}
public static BugHistoryItemResponse toBugHistoryItemResponse(BugHistoryWithPayment dto) {
return BugHistoryItemResponse.builder()
.id(dto.id())
.bugType(dto.bugType())
.actionType(dto.actionType())
.quantity(dto.quantity())
.date(DateUtils.format(dto.createdAt()))
.payment(PaymentMapper.toPaymentResponse(dto.payment()))
.build();
}
public static BugHistoryResponse toBugHistoryResponse(List<BugHistoryWithPayment> dtoList) {
return BugHistoryResponse.builder()
.history(StreamUtils.map(dtoList, BugMapper::toBugHistoryItemResponse))
.build();
}
| public static BugHistory toUseBugHistory(Long memberId, BugType bugType, int quantity) { | 4 | 2023-10-20 06:15:43+00:00 | 4k |
Chocochip101/aws-kendra-demo | src/main/java/com/chocochip/awskendrademo/application/DemoController.java | [
{
"identifier": "IndexRequestDTO",
"path": "src/main/java/com/chocochip/awskendrademo/dto/IndexRequestDTO.java",
"snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class IndexRequestDTO {\n private String name;\n private String clientToken;\n private String roleArn;\n private String description = \"\";\n\n @Builder\n public IndexRequestDTO(String name, String clientToken, String roleArn, String description) {\n this.name = name;\n this.clientToken = clientToken;\n this.roleArn = roleArn;\n this.description = description;\n }\n}"
},
{
"identifier": "S3DataSourceRequestDTO",
"path": "src/main/java/com/chocochip/awskendrademo/dto/S3DataSourceRequestDTO.java",
"snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class S3DataSourceRequestDTO {\n private String clientToken;\n private String dataSourceName;\n private String description;\n private String languageCode;\n private String roleArn;\n private String bucketName;\n private String s3PrefixMetaData;\n\n @Builder\n public S3DataSourceRequestDTO(String clientToken, String dataSourceName, String description, String languageCode,\n String roleArn, String bucketName, String s3PrefixMetaData) {\n this.clientToken = clientToken;\n this.dataSourceName = dataSourceName;\n this.description = description;\n this.languageCode = languageCode;\n this.roleArn = roleArn;\n this.bucketName = bucketName;\n this.s3PrefixMetaData = s3PrefixMetaData;\n }\n}"
},
{
"identifier": "SearchResultDTO",
"path": "src/main/java/com/chocochip/awskendrademo/dto/SearchResultDTO.java",
"snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class SearchResultDTO {\n private String type;\n private String title;\n private String excerpt;\n private String uri;\n\n @Builder\n public SearchResultDTO(String type, String title, String excerpt, String uri) {\n this.type = type;\n this.title = title;\n this.excerpt = excerpt;\n this.uri = uri;\n }\n}"
},
{
"identifier": "KendraService",
"path": "src/main/java/com/chocochip/awskendrademo/service/KendraService.java",
"snippet": "@Service\n@RequiredArgsConstructor\npublic class KendraService {\n private final KendraClient kendraClient;\n\n public String createIndex(IndexRequestDTO indexRequestDTO) {\n CreateIndexRequest createIndexRequest = CreateIndexRequest\n .builder()\n .name(indexRequestDTO.getName())\n .clientToken(indexRequestDTO.getClientToken())\n .roleArn(indexRequestDTO.getRoleArn())\n .description(indexRequestDTO.getDescription())\n .build();\n CreateIndexResponse index = kendraClient.createIndex(createIndexRequest);\n return index.id();\n }\n\n public void deleteIndex(String indexId) {\n DeleteIndexRequest deleteIndexRequest = DeleteIndexRequest\n .builder()\n .id(indexId)\n .build();\n kendraClient.deleteIndex(deleteIndexRequest);\n }\n}"
},
{
"identifier": "IndexService",
"path": "src/main/java/com/chocochip/awskendrademo/service/IndexService.java",
"snippet": "@Service\n@RequiredArgsConstructor\npublic class IndexService {\n private final KendraClient kendraClient;\n\n public List<SearchResultDTO> searchForDocuments(String query, String indexId) {\n QueryRequest queryRequest = QueryRequest\n .builder()\n .queryText(query)\n .indexId(indexId)\n .build();\n\n QueryResponse queryResponse = kendraClient.query(queryRequest);\n\n return queryResponse.resultItems().stream()\n .filter(item -> isValidResultType(item.type()))\n .map(item -> SearchResultDTO.builder()\n .type(item.type().toString())\n .title(item.documentTitle().text())\n .excerpt(item.documentExcerpt().text())\n .uri(item.documentURI())\n .build())\n .collect(Collectors.toList());\n }\n\n private boolean isValidResultType(QueryResultType type) {\n return type == QueryResultType.ANSWER || type == QueryResultType.QUESTION_ANSWER\n || type == QueryResultType.DOCUMENT;\n }\n\n public String addS3DataSource(S3DataSourceRequestDTO s3DataSourceRequestDTO, String indexId) {\n DataSourceConfiguration dataSourceConfiguration\n = getDataSourceConfiguration(s3DataSourceRequestDTO);\n\n CreateDataSourceRequest createDataSourceRequest = CreateDataSourceRequest\n .builder()\n .indexId(indexId)\n .name(s3DataSourceRequestDTO.getDataSourceName())\n .roleArn(s3DataSourceRequestDTO.getRoleArn())\n .description(s3DataSourceRequestDTO.getDescription())\n .clientToken(s3DataSourceRequestDTO.getClientToken())\n .configuration(dataSourceConfiguration)\n .type(DataSourceType.S3).build();\n CreateDataSourceResponse dataSource = kendraClient.createDataSource(createDataSourceRequest);\n return dataSource.id();\n }\n\n private DataSourceConfiguration getDataSourceConfiguration(S3DataSourceRequestDTO s3DataSourceRequestDTO) {\n DocumentsMetadataConfiguration documentsMetadataConfiguration = DocumentsMetadataConfiguration\n .builder()\n .s3Prefix(s3DataSourceRequestDTO.getS3PrefixMetaData())\n .build();\n\n S3DataSourceConfiguration s3DataSourceConfiguration = S3DataSourceConfiguration\n .builder()\n .documentsMetadataConfiguration(documentsMetadataConfiguration)\n .bucketName(s3DataSourceRequestDTO.getBucketName())\n .build();\n\n return DataSourceConfiguration\n .builder()\n .s3Configuration(s3DataSourceConfiguration)\n .build();\n }\n\n public void syncDataSource(String indexId, String dataSourceId) {\n StartDataSourceSyncJobRequest startDataSourceSyncJobRequest = StartDataSourceSyncJobRequest\n .builder()\n .indexId(indexId)\n .id(dataSourceId)\n .build();\n kendraClient.startDataSourceSyncJob(startDataSourceSyncJobRequest);\n }\n}"
}
] | import com.chocochip.awskendrademo.dto.IndexRequestDTO;
import com.chocochip.awskendrademo.dto.S3DataSourceRequestDTO;
import com.chocochip.awskendrademo.dto.SearchResultDTO;
import com.chocochip.awskendrademo.service.KendraService;
import com.chocochip.awskendrademo.service.IndexService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; | 1,732 | package com.chocochip.awskendrademo.application;
@RestController
@RequiredArgsConstructor
public class DemoController {
private final IndexService indexService;
private final KendraService kendraService;
@GetMapping("/search")
public ResponseEntity<List<SearchResultDTO>> search(
@RequestParam("keyword") String keyword, @RequestParam("index-id") String indexId) {
return ResponseEntity.ok(indexService.searchForDocuments(keyword, indexId));
}
@PostMapping("/datasource/s3")
public ResponseEntity<String> addDataSource(
@RequestBody S3DataSourceRequestDTO s3DataSourceRequestDTO, @RequestParam("index-id") String indexId) {
return ResponseEntity.ok(indexService.addS3DataSource(s3DataSourceRequestDTO, indexId));
}
@GetMapping("/sync")
public ResponseEntity<Boolean> sync(
@RequestParam("index-id") String indexId, @RequestParam("datasource-id") String dataSourceId) {
indexService.syncDataSource(indexId, dataSourceId);
return ResponseEntity.ok(true);
}
@PostMapping("/kendra/index") | package com.chocochip.awskendrademo.application;
@RestController
@RequiredArgsConstructor
public class DemoController {
private final IndexService indexService;
private final KendraService kendraService;
@GetMapping("/search")
public ResponseEntity<List<SearchResultDTO>> search(
@RequestParam("keyword") String keyword, @RequestParam("index-id") String indexId) {
return ResponseEntity.ok(indexService.searchForDocuments(keyword, indexId));
}
@PostMapping("/datasource/s3")
public ResponseEntity<String> addDataSource(
@RequestBody S3DataSourceRequestDTO s3DataSourceRequestDTO, @RequestParam("index-id") String indexId) {
return ResponseEntity.ok(indexService.addS3DataSource(s3DataSourceRequestDTO, indexId));
}
@GetMapping("/sync")
public ResponseEntity<Boolean> sync(
@RequestParam("index-id") String indexId, @RequestParam("datasource-id") String dataSourceId) {
indexService.syncDataSource(indexId, dataSourceId);
return ResponseEntity.ok(true);
}
@PostMapping("/kendra/index") | public ResponseEntity<String> createIndex(@RequestBody IndexRequestDTO indexRequestDTO) { | 0 | 2023-10-23 15:47:15+00:00 | 4k |
FlinkFood/FlinkFood | flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/flinkjobs/CustomerViewJob.java | [
{
"identifier": "Address",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/Address.java",
"snippet": "public class Address {\n\n public int id;\n public int customer_id;\n public String street;\n public int street_number;\n public String zipcode;\n public String city;\n public String province;\n public String country;\n public boolean isdelivery;\n public boolean ispayment;\n\n public Address() {\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getCustomer_id() {\n return customer_id;\n }\n\n public void setCustomer_id(int user_id) {\n this.customer_id = user_id;\n }\n\n public String getStreet() {\n return street;\n }\n\n public void setStreet(String street) {\n this.street = street;\n }\n\n public int getStreet_number() {\n return street_number;\n }\n\n public void setStreet_number(int street_number) {\n this.street_number = street_number;\n }\n\n public String getZipCode() {\n return zipcode;\n }\n\n public void setZipCode(String zipCode) {\n this.zipcode = zipCode;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getProvince() {\n return province;\n }\n\n public void setProvince(String province) {\n this.province = province;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public boolean isDelivery() {\n return isdelivery;\n }\n\n public void setDelivery(boolean isDelivery) {\n this.isdelivery = isDelivery;\n }\n\n public boolean isPayment() {\n return ispayment;\n }\n\n public void setPayment(boolean isPayment) {\n this.ispayment = isPayment;\n }\n\n @Override\n public String toString() {\n return \"Address [id=\" + id + \", customer_id=\" + customer_id + \", street=\" + street + \", street_number=\"\n + street_number + \", zipcode=\" + zipcode + \", city=\" + city + \", province=\" + province + \", country=\"\n + country + \", isdelivery=\" + isdelivery + \", ispayment=\" + ispayment + \"]\";\n }\n\n}"
},
{
"identifier": "Customer",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/Customer.java",
"snippet": "public class Customer {\n\n public int id;\n public String name;\n public Character gender;\n public int age;\n\n public Customer() {\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Character getGender() {\n return gender;\n }\n\n public void setGender(Character gender) {\n this.gender = gender;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n\n @Override\n public String toString() {\n return \"Customer [id=\" + id + \", name=\" + name + \", gender=\" + gender + \", age=\" + age + \"]\";\n }\n\n}"
},
{
"identifier": "KafkaAddressSchema",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/KafkaAddressSchema.java",
"snippet": "public class KafkaAddressSchema extends AbstractDeserializationSchema<Address> {\n\n private static final long serialVersionUID = 1L;\n private transient ObjectMapper objectMapper;\n\n @Override\n public void open(InitializationContext context) {\n objectMapper = new ObjectMapper();\n }\n\n @Override\n public Address deserialize(byte[] message) throws IOException {\n return objectMapper.readValue(message, Address.class);\n }\n\n}"
},
{
"identifier": "KafkaCustomerSchema",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/KafkaCustomerSchema.java",
"snippet": "public class KafkaCustomerSchema extends AbstractDeserializationSchema<Customer> {\n\n private static final long serialVersionUID = 1L;\n private transient ObjectMapper objectMapper;\n\n @Override\n public void open(InitializationContext context) {\n objectMapper = new ObjectMapper();\n }\n\n @Override\n public Customer deserialize(byte[] message) throws IOException {\n return objectMapper.readValue(message, Customer.class);\n }\n\n}"
},
{
"identifier": "KafkaOrderSchema",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/KafkaOrderSchema.java",
"snippet": "public class KafkaOrderSchema extends AbstractDeserializationSchema<Order> {\n\n private static final long serialVersionUID = 1L;\n private transient ObjectMapper objectMapper;\n\n @Override\n public void open(InitializationContext context) {\n objectMapper = new ObjectMapper();\n }\n\n @Override\n public Order deserialize(byte[] message) throws IOException {\n return objectMapper.readValue(message, Order.class);\n }\n}"
},
{
"identifier": "Order",
"path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/Order.java",
"snippet": "public class Order {\n\n public int id;\n public int customer_id;\n public int total_amount;\n public String order_id;\n public String title;\n public String restaurant;\n public boolean paid;\n\n public Order() {\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getCustomer_id() {\n return customer_id;\n }\n\n public void setCustomer_id(int customer_id) {\n this.customer_id = customer_id;\n }\n\n public int getTotal_amount() {\n return total_amount;\n }\n\n public void setTotal_amount(int total_amount) {\n this.total_amount = total_amount;\n }\n\n public String getOrder_id() {\n return order_id;\n }\n\n public void setOrder_id(String order_id) {\n this.order_id = order_id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getRestaurant() {\n return restaurant;\n }\n\n public void setRestaurant(String restaurant) {\n this.restaurant = restaurant;\n }\n\n public boolean isPaid() {\n return paid;\n }\n\n public void setPaid(boolean paid) {\n this.paid = paid;\n }\n\n}"
}
] | import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import static org.apache.flink.table.api.Expressions.jsonArray;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.connector.mongodb.sink.MongoSink;
import org.apache.flink.mongodb.shaded.org.bson.Document;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode;
import com.mongodb.client.model.InsertOneModel;
import org.bson.BsonDocument;
import org.flinkfood.schemas.Address;
import org.flinkfood.schemas.Customer;
import org.flinkfood.schemas.KafkaAddressSchema;
import org.flinkfood.schemas.KafkaCustomerSchema;
import org.flinkfood.schemas.KafkaOrderSchema;
import org.flinkfood.schemas.Order;
import org.apache.flink.util.Collector;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode; | 2,163 | // Package declaration for the Flink job
package org.flinkfood.flinkjobs;
// Importing necessary Flink libraries and external dependencies
// Class declaration for the Flink job
public class CustomerViewJob {
// Kafka and MongoDB connection details obtained from environment variables
private static final String KAFKA_URI = "localhost:9092";
private static final String SOURCE_CUSTOMER_TABLE = "postgres.public.customer";
private static final String SOURCE_ADDRESS_TABLE = "postgres.public.address";
private static final String SOURCE_ORDER_TABLE = "postgres.public.orders";
private static final String MONGODB_URI = "mongodb://localhost:27017";
private static final String SINK_DB = "flinkfood";
private static final String SINK_DB_TABLE = "users_sink";
// Main method where the Flink job is defined
public static void main(String[] args) throws Exception {
// Setting up Kafka source with relevant configurations | // Package declaration for the Flink job
package org.flinkfood.flinkjobs;
// Importing necessary Flink libraries and external dependencies
// Class declaration for the Flink job
public class CustomerViewJob {
// Kafka and MongoDB connection details obtained from environment variables
private static final String KAFKA_URI = "localhost:9092";
private static final String SOURCE_CUSTOMER_TABLE = "postgres.public.customer";
private static final String SOURCE_ADDRESS_TABLE = "postgres.public.address";
private static final String SOURCE_ORDER_TABLE = "postgres.public.orders";
private static final String MONGODB_URI = "mongodb://localhost:27017";
private static final String SINK_DB = "flinkfood";
private static final String SINK_DB_TABLE = "users_sink";
// Main method where the Flink job is defined
public static void main(String[] args) throws Exception {
// Setting up Kafka source with relevant configurations | KafkaSource<Customer> sourceCustomer = KafkaSource.<Customer>builder() | 1 | 2023-10-17 08:37:30+00:00 | 4k |
liukanshan1/PrivateTrace-Core | src/main/java/Priloc/protocol/CCircleTree.java | [
{
"identifier": "EncTmLocData",
"path": "src/main/java/Priloc/data/EncTmLocData.java",
"snippet": "public class EncTmLocData implements Serializable {\n private EncryptedCircle eCircle;\n private Date date;\n private EncTmLocData nETLD = null;\n private EncTmLocData pETLD = null;\n private ConcentricCircles cCircles = null;\n\n public EncTmLocData(TimeLocationData tld) {\n this.date = tld.getDate();\n EncryptedPoint ep = tld.getLoc().encrypt();\n this.eCircle = new EncryptedCircle(ep, tld.getAccuracy());\n }\n\n public EncTmLocData(EncryptedCircle eCircle, Date date) {\n this.eCircle = eCircle;\n this.date = date;\n }\n\n public EncryptedCircle getCircle() {\n return eCircle;\n }\n\n public Date getDate() {\n return date;\n }\n\n\n public void setcCircles(ConcentricCircles cCircles) {\n this.cCircles = cCircles;\n }\n\n public void prune() {\n this.cCircles.prune(this);\n }\n\n public void setNext(EncTmLocData nETLD) {\n this.nETLD = nETLD;\n }\n\n public void setPrevious(EncTmLocData pETLD) {\n this.pETLD = pETLD;\n }\n\n public boolean hasNext() {\n return nETLD != null;\n }\n\n public EncTmLocData next() {\n return nETLD;\n }\n\n public boolean hasPrevious() {\n return pETLD != null;\n }\n\n public EncTmLocData previous() {\n return pETLD;\n }\n}"
},
{
"identifier": "EncTrajectory",
"path": "src/main/java/Priloc/data/EncTrajectory.java",
"snippet": "public class EncTrajectory implements Serializable {\n private List<EncTmLocData> eTLDs;\n private String name;\n\n public EncTrajectory(Trajectory trajectory) {\n this.name = trajectory.getName();\n List<TimeLocationData> tlds = trajectory.getTLDs();\n this.eTLDs = new ArrayList<>();\n EncTmLocData pETLD = null;\n for (int i = 0; i < tlds.size(); i++) {\n TimeLocationData tld = tlds.get(i);\n EncTmLocData cETLD = tld.encrypt();\n if (pETLD != null) {\n pETLD.setNext(cETLD);\n }\n cETLD.setPrevious(pETLD);\n eTLDs.add(cETLD);\n pETLD = cETLD;\n }\n }\n\n public EncTrajectory(EncryptedCircle encryptedCircle) {\n this.name = \"范围轨迹\";\n eTLDs = new ArrayList<>();\n EncTmLocData pETLD = null;\n for (int i = 0; i < 24; i++) {\n for (int j = 0; j < 60; j += Constant.INTERVAL) {\n Date date = new Date(2008, Calendar.JUNE, 24, i, j);\n EncTmLocData cETLD = new EncTmLocData(encryptedCircle, date);\n if (pETLD != null) {\n pETLD.setNext(cETLD);\n }\n cETLD.setPrevious(pETLD);\n eTLDs.add(cETLD);\n pETLD = cETLD;\n }\n }\n }\n\n @Override\n public String toString() {\n return \"EncTrajectory{\" +\n \"name=\" + name +\n '}';\n }\n\n public List<EncTmLocData> geteTLDs() {\n return eTLDs;\n }\n\n public Date getStartDate() {\n return this.eTLDs.get(0).getDate();\n }\n\n public Date getEndDate() {\n return this.eTLDs.get(eTLDs.size() - 1).getDate();\n }\n\n// private void writeObject(ObjectOutputStream out) throws IOException {\n// //只序列化以下3个成员变量\n// out.writeObject(this.eTLDs);\n// out.writeObject(this.name);\n// }\n//\n// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n// //注意:read()的顺序要和write()的顺序一致。\n// this.eTLDs = (List<EncTmLocData>) in.readObject();\n// this.name = (String) in.readObject();\n// EncTmLocData prev = null;\n// for (EncTmLocData curr : eTLDs) {\n// curr.setPrevious(prev);\n// if (prev != null) {\n// prev.setNext(curr);\n// }\n// prev = curr;\n// }\n// }\n}"
},
{
"identifier": "Constant",
"path": "src/main/java/Priloc/utils/Constant.java",
"snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{2160000, 1820000, -5690000};\n\n public static final boolean IGNORE_DATE = true;\n public static final boolean REJECT_R_LESS_P5 = true;\n\n // 时间段大小\n public final static int INTERVAL = 10;\n // 每个时间段的移动最大距离\n public static final double RADIUS = 200.0;\n // TODO 优化 不同时间段的活跃距离\n public static final double[] COMPARE_DISTANCE = new double[]{1200 * 1200.0};\n public static final int[] PRUNE_NUM = new int[]{0, 2};\n // 控制形状拟合效果\n public static final int TRIANGLE_NUM = 100;\n public static final Circle.circleFilter FILTER = new Circle.distantFilter(); //new Circle.areaFilter();\n\n public static String toStr() {\n return \"Constant{\" +\n \"INTERVAL=\" + INTERVAL +\n \", RADIUS=\" + RADIUS +\n \", IGNORE_DATE=\" + IGNORE_DATE +\n \", REJECT_R_LESS_P5=\" + REJECT_R_LESS_P5 +\n \", COMPARE_DISTANCE=\" + Arrays.toString(COMPARE_DISTANCE) +\n \", PRUNE_NUM=\" + Arrays.toString(PRUNE_NUM) +\n \", TRIANGLE_NUM=\" + TRIANGLE_NUM +\n \", FILTER=\" + FILTER +\n '}';\n }\n}"
},
{
"identifier": "Utils",
"path": "src/main/java/Priloc/utils/Utils.java",
"snippet": "public class Utils {\n\n public static BigInteger encryptDouble(double d) {\n return User.pai.encrypt(BigInteger.valueOf(Math.round(d * Math.pow(10, Constant.FIXED_POINT))));\n }\n\n public static BigInteger encryptDouble(double d, int scale) {\n return User.pai.encrypt(BigInteger.valueOf(Math.round(d * Math.pow(10, scale))));\n }\n\n public static BigInteger encryptDouble(double d, int scale, Boolean floorOrCeil) {\n if(floorOrCeil) {\n return User.pai.encrypt(BigInteger.valueOf((long) Math.floor(d * Math.pow(10, scale))));\n } else {\n return User.pai.encrypt(BigInteger.valueOf((long) Math.ceil(d * Math.pow(10, scale))));\n }\n }\n\n public static Date getStart(Date d) {\n d.setSeconds(0);\n d.setMinutes(d.getMinutes() - d.getMinutes() % Constant.INTERVAL);\n return d;\n }\n\n public static void writeObject(Object o, String path) throws IOException {\n ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path));\n //调用我们自定义的writeObject()方法\n out.writeObject(o);\n out.close();\n }\n\n public static Object readObject(String path) throws IOException, ClassNotFoundException {\n ObjectInputStream in=new ObjectInputStream(new FileInputStream(path));\n Object o = in.readObject();\n in.close();\n return o;\n }\n}"
}
] | import Priloc.data.EncTmLocData;
import Priloc.data.EncTrajectory;
import Priloc.utils.Constant;
import Priloc.utils.Utils;
import sg.smu.securecom.protocol.Paillier;
import sg.smu.securecom.protocol.PaillierThdDec;
import java.io.Serializable;
import java.util.*;
import java.util.concurrent.*; | 2,292 | package Priloc.protocol;
public class CCircleTree implements Serializable {
private HashMap<Date, ConcentricCircles> ccTree;
private transient ThreadLocal<Map<ConcentricCircles, boolean[]>> localPrune = new ThreadLocal<>();
private static final List<EncTrajectory> workLoad = new LinkedList<>();
public CCircleTree() {
this.ccTree = new HashMap<>();
}
public void add(EncTrajectory eTrajectory) {
List<EncTmLocData> eTLDs = eTrajectory.geteTLDs();
for (int i = 0; i < eTLDs.size(); i++) {
EncTmLocData eTLD = eTLDs.get(i);
Date startDate = eTLD.getDate();
ConcentricCircles ccs = ccTree.get(startDate);
if (ccs == null) {
ccs = new ConcentricCircles(eTLD, this);
//ccs.setDates(startDate, new Date(startDate.getTime() + INTERVAL * 60 * 1000));
ccTree.put(startDate, ccs);
} else {
ccs.add(eTLD);
}
}
}
public void init() throws InterruptedException { | package Priloc.protocol;
public class CCircleTree implements Serializable {
private HashMap<Date, ConcentricCircles> ccTree;
private transient ThreadLocal<Map<ConcentricCircles, boolean[]>> localPrune = new ThreadLocal<>();
private static final List<EncTrajectory> workLoad = new LinkedList<>();
public CCircleTree() {
this.ccTree = new HashMap<>();
}
public void add(EncTrajectory eTrajectory) {
List<EncTmLocData> eTLDs = eTrajectory.geteTLDs();
for (int i = 0; i < eTLDs.size(); i++) {
EncTmLocData eTLD = eTLDs.get(i);
Date startDate = eTLD.getDate();
ConcentricCircles ccs = ccTree.get(startDate);
if (ccs == null) {
ccs = new ConcentricCircles(eTLD, this);
//ccs.setDates(startDate, new Date(startDate.getTime() + INTERVAL * 60 * 1000));
ccTree.put(startDate, ccs);
} else {
ccs.add(eTLD);
}
}
}
public void init() throws InterruptedException { | ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD); | 2 | 2023-10-22 06:28:51+00:00 | 4k |
tuxming/xmfx | BaseUI/src/main/java/com/xm2013/jfx/ui/FxWindow.java | [
{
"identifier": "BorderlessPane",
"path": "BaseUI/src/main/java/com/xm2013/jfx/borderless/BorderlessPane.java",
"snippet": "public class BorderlessPane extends AnchorPane {\n\tpublic BorderlessPane (BorderlessController controller) throws IOException {\n\n\t\t// ------------------------------------FXMLLOADER ----------------------------------------\n\n\t\tFXMLLoader loader = new FXMLLoader(getClass().getResource(\"/borderless/fxml/Borderless.fxml\"));\n\t\tloader.setController(controller);\n\t\tloader.setRoot(this);\n loader.load();\n\t}\n}"
},
{
"identifier": "BorderlessScene",
"path": "BaseUI/src/main/java/com/xm2013/jfx/borderless/BorderlessScene.java",
"snippet": "public class BorderlessScene extends Scene {\n\n\t/** The controller. */\n\tprivate BorderlessController controller;\n\n\t/** The root. */\n\tprivate BorderlessPane root;\n\n\t/** The Stage. */\n\tprivate Stage stage;\n\n\t/**\n\t * The constructor.\n\t *\n\t * @param stage your stage.\n\t * @param stageStyle <b>Undecorated</b> and <b>Transparent</b> StageStyles are accepted or else the Transparent StageStyle will be set.\n\t * @param sceneRoot The root of the Scene\n\t */\n\tpublic BorderlessScene(Stage stage, StageStyle stageStyle, Parent sceneRoot) {\n\t\tsuper(new Pane());\n\t\ttry {\n\t\t\tthis.controller = new BorderlessController();\n\t\t\t// Load the FXML\n\t\t\tthis.root = new BorderlessPane(this.controller);\n\n\t\t\t// Set Scene root\n\t\t\tsetRoot(this.root);\n\t\t\tsetContent(sceneRoot);\n\n\t\t\t// Initialize the Controller\n\t\t\tthis.controller.setStage(stage);\n\t\t\tthis.controller.createTransparentWindow(stage);\n\n\t\t\t// StageStyle\n\t\t\tstage.initStyle(stageStyle);\n\t\t\tif (stageStyle == StageStyle.UTILITY) {\n\t\t\t\tsetSnapEnabled(false);\n\t\t\t\tsetResizable(false);\n\t\t\t}\n\n\t\t\t// Stage\n\t\t\tthis.stage = stage;\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * The constructor.\n\t *\n\t * @param stage your stage.\n\t * @param stageStyle <b>Undecorated</b> and <b>Transparent</b> StageStyles are accepted or else the Transparent StageStyle will be set.\n\t * @param sceneRoot The root of the Scene\n\t * @param minWidth The minimum width that the Stage can have\n\t * @param minHeight The minimum height that the Stage can have\n\t */\n\tpublic BorderlessScene(Stage stage, StageStyle stageStyle, Parent sceneRoot, double minWidth, double minHeight) {\n\t\tthis(stage, stageStyle, sceneRoot);\n\n\t\t// minSize\n\t\tstage.setMinWidth(minWidth);\n\t\tstage.setMinHeight(minHeight);\n\t}\n\n\t/**\n\t * Change the content of the scene.\n\t *\n\t * @param content the root Parent of your new content.\n\t */\n\tpublic void setContent(Parent content) {\n\t\tthis.root.getChildren().remove(0);\n\t\tthis.root.getChildren().add(0, content);\n\t\tAnchorPane.setLeftAnchor(content, 0.0D);\n\t\tAnchorPane.setTopAnchor(content, 0.0D);\n\t\tAnchorPane.setRightAnchor(content, 0.0D);\n\t\tAnchorPane.setBottomAnchor(content, 0.0D);\n\t}\n\n\t/**\n\t * Set a node that can be pressed and dragged to move the application around.\n\t *\n\t * @param node the node.\n\t */\n\tpublic void setMoveControl(Node node) {\n\t\tthis.controller.setMoveControl(node);\n\t}\n\n\t/**\n\t * Toggle to maximize the application.\n\t */\n\tpublic void maximizeStage() {\n\t\tcontroller.maximize();\n\t}\n\n\t/**\n\t * Minimize the stage to the taskbar.\n\t */\n\tpublic void minimizeStage() {\n\t\tcontroller.minimize();\n\t}\n\n\t/**\n\t * Disable/enable the resizing of your stage. Enabled by default.\n\t *\n\t * @param bool false to disable, true to enable.\n\t */\n\tpublic void setResizable(boolean bool) {\n\t\tcontroller.setResizable(bool);\n\t}\n\n\t/**\n\t * Disable/enable the Aero Snap of your stage. Enabled by default.\n\t *\n\t * @param bool false to disable, true to enable.\n\t */\n\tpublic void setSnapEnabled(boolean bool) {\n\t\tcontroller.setSnapEnabled(bool);\n\t}\n\n\t/**\n\t * Maximized property.\n\t *\n\t * @return Maximized property\n\t */\n\tpublic BooleanProperty maximizedProperty() {\n\t\treturn controller.maximizedProperty();\n\t}\n\n\t/**\n\t * Resizable property.\n\t *\n\t * @return Resizable property\n\t */\n\tpublic BooleanProperty resizableProperty() {\n\t\treturn controller.resizableProperty();\n\t}\n\n\t/**\n\t * Aero Snap property.\n\t *\n\t * @return Aero Snap property\n\t */\n\tpublic BooleanProperty snapProperty() {\n\t\treturn controller.snapProperty();\n\t}\n\n\t/**\n\t * True if the stage is maximized or false if not\n\t *\n\t * @return True if the stage is maximized or false if not\n\t */\n\tpublic boolean isMaximized() {\n\t\treturn controller.maximizedProperty().get();\n\t}\n\n\t/**\n\t * True if the stage is resizable or false if not\n\t *\n\t * @return True if the stage is resizable or false if not\n\t */\n\tpublic boolean isResizable() {\n\t\treturn controller.resizableProperty().get();\n\t}\n\n\t/**\n\t * True if Aero Snap is enabled or false if not\n\t *\n\t * @return True if Aero Snap is enabled or false if not\n\t */\n\tpublic boolean isSnapEnabled() {\n\t\treturn controller.snapProperty().get();\n\t}\n\n\t/**\n\t * Returns the width and height of the application when windowed.\n\t *\n\t * @return instance of Delta class. Delta.x = width, Delta.y = height.\n\t */\n\tpublic Delta getWindowedSize() {\n\t\tif (controller.prevSize.x == null)\n\t\t\tcontroller.prevSize.x = stage.getWidth();\n\t\tif (controller.prevSize.y == null)\n\t\t\tcontroller.prevSize.y = stage.getHeight();\n\t\treturn controller.prevSize;\n\t}\n\n\t/**\n\t * Returns the x and y position of the application when windowed.\n\t *\n\t * @return instance of Delta class. Use Delta.x and Delta.y.\n\t */\n\tpublic Delta getWindowedPositon() {\n\t\tif (controller.prevPos.x == null)\n\t\t\tcontroller.prevPos.x = stage.getX();\n\t\tif (controller.prevPos.y == null)\n\t\t\tcontroller.prevPos.y = stage.getY();\n\t\treturn controller.prevPos;\n\t}\n\n\t/**\n\t * Removes the default css style of the corners\n\t */\n\tpublic void removeDefaultCSS() {\n\t\tthis.root.getStylesheets().remove(0);\n\t}\n\n\t/**\n\t * The transparent window which allows the library to have aerosnap controls can be styled using this method .\n\t * It is nothing more than a StackPane in a transparent window , so for example you can change it's background color , borders , everything through this method :)\n\t *\n\t * @param style The style of the transparent window of the application\n\t */\n\tpublic void setTransparentWindowStyle(String style) {\n\t\tcontroller.getTransparentWindow().setStyle(\"\");\n\t\tcontroller.getTransparentWindow().setStyle(style);\n\t}\n\n}"
},
{
"identifier": "CustomStage",
"path": "BaseUI/src/main/java/com/xm2013/jfx/borderless/CustomStage.java",
"snippet": "public class CustomStage extends Stage {\n\tpublic CustomStage() {}\n\t\n\tpublic CustomStage(StageStyle style) {\n\t\tsuper(style);\n\t}\n\t\n\tpublic BorderlessScene craftBorderlessScene(Parent sceneRoot) {\n\t\treturn new BorderlessScene(this, getStyle(), sceneRoot);\n\t}\n\t\n\tpublic void showAndAdjust() {\n\t\tif(isShowing())\n\t\t\treturn;\n\t\tshow();\n\t}\n\n}"
},
{
"identifier": "FXEventBus",
"path": "BaseUI/src/main/java/com/xm2013/jfx/component/eventbus/FXEventBus.java",
"snippet": "public final class FXEventBus implements EventBus {\n\t\n\tprivate static FXEventBus instance = new FXEventBus();\n\t\n\tpublic static FXEventBus getDefault() {\n\t\treturn instance;\n\t}\n\t\n private Group eventHandlers = new Group();\n\n @Override\n public <T extends Event> Subscriber addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {\n eventHandlers.addEventHandler(eventType, eventHandler);\n return new Subscriber(this, eventType, (EventHandler<? super Event>) eventHandler);\n }\n\n @Override\n public <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {\n eventHandlers.removeEventHandler(eventType, eventHandler);\n }\n\n @Override\n public void fireEvent(Event event) {\n eventHandlers.fireEvent(event);\n }\n}"
},
{
"identifier": "XmEvent",
"path": "BaseUI/src/main/java/com/xm2013/jfx/component/eventbus/XmEvent.java",
"snippet": "public class XmEvent<T> extends Event{\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 4011774587169578132L;\n\n\tpublic static final EventType<XmEvent<Object>> ANY = new EventType<>(Event.ANY, \"XM-EVENT\");\n\tpublic static final EventType<XmEvent<Object>> CLOSE_WINDOW = new EventType<>(Event.ANY, \"XM-CLOSE-WINDOW\");\n\tpublic static final EventType<XmEvent<Object>> MAX_WINDOW = new EventType<>(Event.ANY, \"XM-MAX-WINDOW\");\n\tpublic static final EventType<XmEvent<Object>> MIN_WINDOW = new EventType<>(Event.ANY, \"XM-MIN-WINDOW\");\n\n private T data;\n\n public XmEvent(EventType<? extends XmEvent<T>> eventType) {\n\t\tsuper(eventType);\n\t}\n\n \n public XmEvent(@NamedArg(\"eventType\") EventType<? extends XmEvent<T>> eventType, T data) {\n super(eventType);\n this.data = data;\n }\n\n public T getData() {\n return data;\n }\n}"
}
] | import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.StageStyle;
import java.io.IOException;
import com.xm2013.jfx.borderless.BorderlessPane;
import com.xm2013.jfx.borderless.BorderlessScene;
import com.xm2013.jfx.borderless.CustomStage;
import com.xm2013.jfx.component.eventbus.FXEventBus;
import com.xm2013.jfx.component.eventbus.XmEvent;
import javafx.beans.property.DoubleProperty; | 3,285 | /*
* MIT License
*
* Copyright (c) 2023 [email protected] / wechat: t5x5m5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.xm2013.jfx.ui;
public class FxWindow {
private CustomStage stage;
private BorderlessScene scene = null;
private DoubleProperty heightProperty = new SimpleDoubleProperty();
private DoubleProperty widthProperty = new SimpleDoubleProperty();
public FxWindow(double width, double height, Pane rootPane) throws IOException {
heightProperty.set(height);
widthProperty.set(width);
stage = new CustomStage(StageStyle.TRANSPARENT);
stage.setWidth(width+40);
stage.setHeight(height+40);
scene = stage.craftBorderlessScene(rootPane);
scene.setFill(Color.TRANSPARENT);
scene.maximizedProperty().addListener((ob, ov, nv)->{
if(nv){
heightProperty.set(stage.getHeight());
widthProperty.set(stage.getWidth());
}else{
heightProperty.set(stage.getHeight()-40);
widthProperty.set(stage.getWidth()-40);
}
});
stage.heightProperty().addListener((ob, ov, nv)->{
if(scene.isMaximized()){
heightProperty.set(stage.getHeight());
}else{
heightProperty.set(stage.getHeight()-40);
}
});
stage.widthProperty().addListener((ob, ov, nv)->{
if(scene.isMaximized()){
widthProperty.set(stage.getWidth());
}else{
widthProperty.set(stage.getWidth()-40);
}
});
stage.setScene(scene);
scene.removeDefaultCSS();
rootPane.setStyle("-fx-background-color: white;");
final BorderlessPane root = (BorderlessPane) scene.getRoot();
root.setStyle("-fx-background-color: transparent; "
+ "-fx-padding:20px; "
+ "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);");
scene.maximizedProperty().addListener((ob, ov, nv)->{
if(nv) {
root.setStyle("");
}else {
root.setStyle("-fx-background-color: transparent; "
+ "-fx-padding:20px; "
+ "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);");
}
});
| /*
* MIT License
*
* Copyright (c) 2023 [email protected] / wechat: t5x5m5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.xm2013.jfx.ui;
public class FxWindow {
private CustomStage stage;
private BorderlessScene scene = null;
private DoubleProperty heightProperty = new SimpleDoubleProperty();
private DoubleProperty widthProperty = new SimpleDoubleProperty();
public FxWindow(double width, double height, Pane rootPane) throws IOException {
heightProperty.set(height);
widthProperty.set(width);
stage = new CustomStage(StageStyle.TRANSPARENT);
stage.setWidth(width+40);
stage.setHeight(height+40);
scene = stage.craftBorderlessScene(rootPane);
scene.setFill(Color.TRANSPARENT);
scene.maximizedProperty().addListener((ob, ov, nv)->{
if(nv){
heightProperty.set(stage.getHeight());
widthProperty.set(stage.getWidth());
}else{
heightProperty.set(stage.getHeight()-40);
widthProperty.set(stage.getWidth()-40);
}
});
stage.heightProperty().addListener((ob, ov, nv)->{
if(scene.isMaximized()){
heightProperty.set(stage.getHeight());
}else{
heightProperty.set(stage.getHeight()-40);
}
});
stage.widthProperty().addListener((ob, ov, nv)->{
if(scene.isMaximized()){
widthProperty.set(stage.getWidth());
}else{
widthProperty.set(stage.getWidth()-40);
}
});
stage.setScene(scene);
scene.removeDefaultCSS();
rootPane.setStyle("-fx-background-color: white;");
final BorderlessPane root = (BorderlessPane) scene.getRoot();
root.setStyle("-fx-background-color: transparent; "
+ "-fx-padding:20px; "
+ "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);");
scene.maximizedProperty().addListener((ob, ov, nv)->{
if(nv) {
root.setStyle("");
}else {
root.setStyle("-fx-background-color: transparent; "
+ "-fx-padding:20px; "
+ "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);");
}
});
| FXEventBus.getDefault().addEventHandler(XmEvent.MAX_WINDOW, e -> { | 3 | 2023-10-17 08:57:08+00:00 | 4k |
ErickMonteiroMDK/Advocacia_Beckhauser | src/main/java/com/advocacia/Advocacia_Beckhauser/resources/AgendaController.java | [
{
"identifier": "ValidationException",
"path": "src/main/java/com/advocacia/Advocacia_Beckhauser/enterprise/ValidationException.java",
"snippet": "public class ValidationException extends RuntimeException {\n public ValidationException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "Agenda",
"path": "src/main/java/com/advocacia/Advocacia_Beckhauser/models/Agenda.java",
"snippet": "@Entity\npublic class Agenda extends EntityID \n{\n @Column(name = \"dataOcorrencia\", nullable = false)\n private LocalDate dataOcorrencia;\n\n\n @ManyToOne\n @JoinColumn(name = \"advogado_responsavel_id\", referencedColumnName = \"id\")\n private Advogado responsavel;\n\n @ManyToOne\n @JoinColumn(name = \"processo_id\", referencedColumnName = \"id\")\n private Processo numeroProcesso;\n\n\n @Column(nullable = false)\n private String situacao;\n\n @Column(nullable = false)\n private String fase;\n\n @Column(nullable = false)\n private String local;\n\n @Column(nullable = false)\n private String tipoPrazo;\n\n @Column(nullable = false)\n private LocalDate dataInicial;\n \n @Column(nullable = false)\n private Integer prazo;\n\n @Column(nullable = false)\n private LocalDate dataFatal;\n \n\n\n public LocalDate getDataOcorrencia() {\n return this.dataOcorrencia;\n }\n\n public void setDataOcorrencia(LocalDate dataOcorrencia) {\n this.dataOcorrencia = dataOcorrencia;\n }\n\n\n public Advogado getResponsavel() {\n return responsavel;\n }\n\n public void setResponsavel(Advogado responsavel) {\n this.responsavel = responsavel;\n }\n\n public Processo getNumeroProcesso() {\n return numeroProcesso;\n }\n\n public void setNumeroProcesso(Processo numeroProcesso) {\n this.numeroProcesso = numeroProcesso;\n }\n\n\n public String getSituacao() {\n return this.situacao;\n }\n\n public void setSituacao(String situacao) {\n this.situacao = situacao;\n }\n\n public String getFase() {\n return this.fase;\n }\n\n public void setFase(String fase) {\n this.fase = fase;\n }\n\n public String getLocal() {\n return this.local;\n }\n\n public void setLocal(String local) {\n this.local = local;\n }\n\n public String getTipoPrazo() {\n return this.tipoPrazo;\n }\n\n public void setTipoPrazo(String tipoPrazo) {\n this.tipoPrazo = tipoPrazo;\n }\n\n public LocalDate getDataInicial() {\n return this.dataInicial;\n }\n\n public void setDataInicial(LocalDate dataInicial) {\n this.dataInicial = dataInicial;\n }\n\n public Integer getPrazo() {\n return this.prazo;\n }\n\n public void setPrazo(Integer prazo) {\n this.prazo = prazo;\n }\n\n public LocalDate getDataFatal() {\n return this.dataFatal;\n }\n\n public void setDataFatal(LocalDate dataFatal) {\n this.dataFatal = dataFatal;\n }\n\n\n @Override\n public String toString() {\n return \"Agenda{\" +\n \"dataOcorrencia=\" + dataOcorrencia +\n \", responsavel=\" + responsavel +\n \", numeroProcesso=\" + numeroProcesso +\n \", situacao='\" + situacao + '\\'' +\n \", fase='\" + fase + '\\'' +\n \", local='\" + local + '\\'' +\n \", tipoPrazo='\" + tipoPrazo + '\\'' +\n \", dataInicial=\" + dataInicial +\n \", prazo=\" + prazo +\n \", dataFatal=\" + dataFatal +\n '}';\n }\n}"
},
{
"identifier": "AgendaService",
"path": "src/main/java/com/advocacia/Advocacia_Beckhauser/services/AgendaService.java",
"snippet": "@Service\npublic class AgendaService \n{ \n @Autowired\n private AgendaRepository repository;\n\n\n\n public Agenda salvarAgenda(Agenda agenda) \n {\n return repository.save(agenda);\n }\n\n\n public List<Agenda> trazerTodasAgendas() \n {\n return repository.findAll();\n }\n\n public Agenda trazerAgendaPorId(Long id) \n {\n return repository.findById(id).orElse(null);\n }\n\n\n public void removerAgenda(Long id)\n {\n repository.deleteById(id);\n }\n\n\n public Agenda alterarAgenda(Long id, Agenda novaAgenda) \n {\n java.util.Optional<Agenda> porId = repository.findById(id);\n\n if (porId.isPresent()) \n {\n Agenda agenda = porId.get();\n\n agenda.setDataOcorrencia(novaAgenda.getDataOcorrencia());\n agenda.setResponsavel(novaAgenda.getResponsavel());\n agenda.setNumeroProcesso(novaAgenda.getNumeroProcesso());\n agenda.setSituacao(novaAgenda.getSituacao());\n agenda.setFase(novaAgenda.getFase());\n agenda.setLocal(novaAgenda.getLocal());\n agenda.setTipoPrazo(novaAgenda.getTipoPrazo());\n agenda.setDataInicial(novaAgenda.getDataInicial());\n agenda.setPrazo(novaAgenda.getPrazo());\n agenda.setDataFatal(novaAgenda.getDataFatal());\n\n return repository.save(agenda);\n }\n return null;\n }\n}"
}
] | import java.net.URI;
import java.time.temporal.ChronoUnit;
import java.util.List;
import com.advocacia.Advocacia_Beckhauser.enterprise.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.advocacia.Advocacia_Beckhauser.models.Agenda;
import com.advocacia.Advocacia_Beckhauser.services.AgendaService; | 1,700 | package com.advocacia.Advocacia_Beckhauser.resources;
@RestController
@RequestMapping("/api/agenda")
public class AgendaController extends AbstractController
{
@Autowired
AgendaService service;
// ResponseEntity recebe <?> para obter qualquer tipo de retorno(String ou Agenda). Deus nos proteja de qualquer erro com 500 linhas
/*
* Autor: Lucas Ronchi
*
* Mensagem à Raphael:
* Então tá jóia...
* */
@PostMapping
public ResponseEntity salvarAgenda(@RequestBody Agenda agenda)
{
if (agenda.getDataInicial().isAfter(agenda.getDataFatal()))
{ | package com.advocacia.Advocacia_Beckhauser.resources;
@RestController
@RequestMapping("/api/agenda")
public class AgendaController extends AbstractController
{
@Autowired
AgendaService service;
// ResponseEntity recebe <?> para obter qualquer tipo de retorno(String ou Agenda). Deus nos proteja de qualquer erro com 500 linhas
/*
* Autor: Lucas Ronchi
*
* Mensagem à Raphael:
* Então tá jóia...
* */
@PostMapping
public ResponseEntity salvarAgenda(@RequestBody Agenda agenda)
{
if (agenda.getDataInicial().isAfter(agenda.getDataFatal()))
{ | throw new ValidationException("data inicial deve ser anterior ou igual a data fatal"); | 0 | 2023-10-24 21:35:12+00:00 | 4k |
Space125/tasklist | src/main/java/org/kurilov/tasklist/web/controller/UserController.java | [
{
"identifier": "Task",
"path": "src/main/java/org/kurilov/tasklist/domain/task/Task.java",
"snippet": "@Data\npublic class Task {\n\n private Long id;\n private String title;\n private String description;\n private Status status;\n private LocalDateTime expirationDate;\n}"
},
{
"identifier": "User",
"path": "src/main/java/org/kurilov/tasklist/domain/user/User.java",
"snippet": "@Data\npublic class User {\n\n private Long id;\n private String name;\n private String username;\n private String password;\n private String passwordConfirmation;\n private Set<Role> roles;\n private List<Task> tasks;\n}"
},
{
"identifier": "TaskService",
"path": "src/main/java/org/kurilov/tasklist/service/TaskService.java",
"snippet": "public interface TaskService {\n\n Task getById(Long id);\n\n List<Task> getAllByUserId(Long userId);\n\n Task update(Task task);\n\n Task create(Task task, Long userId);\n\n void delete(Long id);\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/org/kurilov/tasklist/service/UserService.java",
"snippet": "public interface UserService {\n\n User getById(Long id);\n\n User getByUsername(String username);\n\n User update(User user);\n\n User create(User user);\n\n boolean isTaskOwner(Long userId, Long taskId);\n\n void delete(Long id);\n\n}"
},
{
"identifier": "TaskDto",
"path": "src/main/java/org/kurilov/tasklist/web/dto/task/TaskDto.java",
"snippet": "@Data\npublic class TaskDto {\n\n @NotNull(message = \"Id must be not null.\", groups = OnUpdate.class)\n private Long id;\n\n @NotNull(message = \"Title must be not null.\", groups = {OnUpdate.class, OnCreate.class})\n @Length(max = 255, message = \"Title length must be smaller than 255 symbols\", groups = {OnUpdate.class, OnCreate.class})\n private String title;\n\n @Length(max = 255, message = \"Description length must be smaller than 255 symbols\", groups = {OnUpdate.class, OnCreate.class})\n private String description;\n\n private Status status;\n\n @DateTimeFormat(iso = DateTimeFormat.ISO.TIME)\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm\")\n private LocalDateTime expirationDate;\n\n}"
},
{
"identifier": "UserDto",
"path": "src/main/java/org/kurilov/tasklist/web/dto/user/UserDto.java",
"snippet": "@Data\n@Schema(description = \"User DTO\")\npublic class UserDto {\n\n @Schema(description = \"User Id\", example = \"1\")\n @NotNull(message = \"Id must be not null.\", groups = OnUpdate.class)\n private Long id;\n\n @Schema(description = \"User name\", example = \"John Doe\")\n @NotNull(message = \"Name must be not null.\", groups = {OnCreate.class, OnUpdate.class})\n @Length(max = 255, message = \"Name length must be smaller than 255 symbols.\", groups = {OnCreate.class, OnUpdate.class})\n private String name;\n\n @Schema(description = \"User email\", example = \"[email protected]\")\n @NotNull(message = \"Username must be not null\", groups = {OnCreate.class, OnUpdate.class})\n @Length(max = 255, message = \"Username length must be smaller than 255 symbols.\", groups = {OnCreate.class, OnUpdate.class})\n private String username;\n\n @Schema(description = \"User password\", example = \"Test54123\")\n @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)\n @NotNull(message = \"Password must be not null.\", groups = {OnCreate.class, OnUpdate.class})\n private String password;\n\n @Schema(description = \"User password confirmation\", example = \"Test54123\")\n @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)\n @NotNull(message = \"Password confirmation must be not null.\", groups = {OnCreate.class})\n private String passwordConfirmation;\n\n}"
},
{
"identifier": "OnCreate",
"path": "src/main/java/org/kurilov/tasklist/web/dto/validation/OnCreate.java",
"snippet": "public interface OnCreate {\n}"
},
{
"identifier": "OnUpdate",
"path": "src/main/java/org/kurilov/tasklist/web/dto/validation/OnUpdate.java",
"snippet": "public interface OnUpdate {\n}"
},
{
"identifier": "TaskMapper",
"path": "src/main/java/org/kurilov/tasklist/web/mappers/TaskMapper.java",
"snippet": "@Mapper(componentModel = \"spring\")\npublic interface TaskMapper extends Mappable<Task, TaskDto> {\n}"
},
{
"identifier": "UserMapper",
"path": "src/main/java/org/kurilov/tasklist/web/mappers/UserMapper.java",
"snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserMapper extends Mappable<User, UserDto> {\n @Override\n @Mapping(target = \"roles\", ignore = true)\n @Mapping(target = \"tasks\", ignore = true)\n User toEntity(UserDto dto);\n}"
}
] | import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.kurilov.tasklist.domain.task.Task;
import org.kurilov.tasklist.domain.user.User;
import org.kurilov.tasklist.service.TaskService;
import org.kurilov.tasklist.service.UserService;
import org.kurilov.tasklist.web.dto.task.TaskDto;
import org.kurilov.tasklist.web.dto.user.UserDto;
import org.kurilov.tasklist.web.dto.validation.OnCreate;
import org.kurilov.tasklist.web.dto.validation.OnUpdate;
import org.kurilov.tasklist.web.mappers.TaskMapper;
import org.kurilov.tasklist.web.mappers.UserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,678 | package org.kurilov.tasklist.web.controller;
/**
* @author Ivan Kurilov on 20.10.2023
*/
@RestController
@RequestMapping("/api/v1/users")
@Validated
@RequiredArgsConstructor
@Tag(name = "User Controller", description = "User API")
public class UserController {
private final UserService userService;
private final TaskService taskService;
private final UserMapper userMapper;
private final TaskMapper taskMapper;
@PutMapping
@Operation(summary = "Update User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#dto.id)")
public UserDto update(@Validated(OnUpdate.class) @RequestBody final UserDto dto) {
User user = userMapper.toEntity(dto);
User updatedUser = userService.update(user);
return userMapper.toDto(updatedUser);
}
@GetMapping("/{id}")
@Operation(summary = "Get UserDto by Id")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public UserDto getById(@PathVariable final Long id) {
User user = userService.getById(id);
return userMapper.toDto(user);
}
@DeleteMapping("/{id}")
@Operation(summary = "Delete User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public void delete(@PathVariable final Long id) {
userService.delete(id);
}
@GetMapping("/{id}/tasks")
@Operation(summary = "Get all User Tasks")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public List<TaskDto> getTaskByUserId(@PathVariable final Long id) {
List<Task> tasks = taskService.getAllByUserId(id);
return taskMapper.toDto(tasks);
}
@PostMapping("/{id}/tasks")
@Operation(summary = "Add task to User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)") | package org.kurilov.tasklist.web.controller;
/**
* @author Ivan Kurilov on 20.10.2023
*/
@RestController
@RequestMapping("/api/v1/users")
@Validated
@RequiredArgsConstructor
@Tag(name = "User Controller", description = "User API")
public class UserController {
private final UserService userService;
private final TaskService taskService;
private final UserMapper userMapper;
private final TaskMapper taskMapper;
@PutMapping
@Operation(summary = "Update User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#dto.id)")
public UserDto update(@Validated(OnUpdate.class) @RequestBody final UserDto dto) {
User user = userMapper.toEntity(dto);
User updatedUser = userService.update(user);
return userMapper.toDto(updatedUser);
}
@GetMapping("/{id}")
@Operation(summary = "Get UserDto by Id")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public UserDto getById(@PathVariable final Long id) {
User user = userService.getById(id);
return userMapper.toDto(user);
}
@DeleteMapping("/{id}")
@Operation(summary = "Delete User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public void delete(@PathVariable final Long id) {
userService.delete(id);
}
@GetMapping("/{id}/tasks")
@Operation(summary = "Get all User Tasks")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public List<TaskDto> getTaskByUserId(@PathVariable final Long id) {
List<Task> tasks = taskService.getAllByUserId(id);
return taskMapper.toDto(tasks);
}
@PostMapping("/{id}/tasks")
@Operation(summary = "Add task to User")
@PreAuthorize("@userSecurityExpression.canAccessUser(#id)") | public TaskDto createTask(@Validated(OnCreate.class) | 6 | 2023-10-19 05:50:28+00:00 | 4k |
rfresh2/2b2t.vc-rusherhack | src/main/java/vc/VcPlugin.java | [
{
"identifier": "VcApi",
"path": "src/main/java/vc/api/VcApi.java",
"snippet": "public class VcApi {\n private final HttpClient httpClient;\n private final ILogger logger;\n private final Gson gson;\n\n public VcApi(final ILogger logger) {\n this.logger = logger;\n this.httpClient = HttpClient.newBuilder()\n .build();\n this.gson = new GsonBuilder()\n .registerTypeAdapter(OffsetDateTime.class, (JsonDeserializer<OffsetDateTime>) (json, typeOfT, context) -> OffsetDateTime.parse(json.getAsString()))\n .create();\n }\n\n public Optional<SeenResponse> getSeen(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/seen?playerName=\" + player.name(), SeenResponse.class);\n }\n\n public Optional<PlaytimeResponse> getPlaytime(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/playtime?playerName=\" + player.name(), PlaytimeResponse.class);\n }\n\n public Optional<QueueStatus> getQueueStatus() {\n return get(\"https://api.2b2t.vc/queue\", QueueStatus.class);\n }\n\n public Optional<StatsResponse> getStats(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/stats/player?playerName=\" + player.name(), StatsResponse.class);\n }\n\n private <T> Optional<T> get(final String uri, final Class<T> responseType) {\n try {\n HttpRequest request = HttpRequest.newBuilder()\n .GET()\n .uri(URI.create(uri))\n .setHeader(\"User-Agent\", \"rusherhack/1.0\")\n .build();\n HttpResponse<InputStream> response = this.httpClient.send(request, ofInputStream());\n try (JsonReader reader = new JsonReader(new InputStreamReader(response.body()))) {\n return Optional.ofNullable(this.gson.fromJson(reader, responseType));\n }\n } catch (final Exception e) {\n logger.error(\"Failed querying \" + uri);\n e.printStackTrace();\n return Optional.empty();\n }\n }\n}"
},
{
"identifier": "PlaytimeCommand",
"path": "src/main/java/vc/command/PlaytimeCommand.java",
"snippet": "public class PlaytimeCommand extends Command {\n private final VcApi api;\n\n public PlaytimeCommand(final VcApi api) {\n super(\"vcplaytime\", \"Gets a player's 2b2t playtime\");\n this.api = api;\n addAliases(\"vcpt\");\n }\n\n @CommandExecutor\n @CommandExecutor.Argument({\"player\"})\n public String playtime(final PlayerReference player) {\n ForkJoinPool.commonPool().execute(() -> {\n var playtime = this.api.getPlaytime(player);\n var out = player.name() + \" Playtime\\n\" +\n playtime.map(\n pt -> formatDuration(Duration.ofSeconds(pt.playtimeSeconds())))\n .orElse(\"Error: \" + player.name() + \" not found!\");\n ChatUtils.print(out);\n });\n return null;\n }\n}"
},
{
"identifier": "QueueCommand",
"path": "src/main/java/vc/command/QueueCommand.java",
"snippet": "public class QueueCommand extends Command {\n\n private final VcApi api;\n public QueueCommand(final VcApi api) {\n super(\"queue\", \"2b2t queue status\");\n this.api = api;\n addAliases(\"q\");\n }\n\n @CommandExecutor\n private String getQueueStatus() {\n ForkJoinPool.commonPool().execute(() -> {\n var queueStatus = this.api.getQueueStatus();\n var out = queueStatus.map(qs ->\n \"Regular: \" + qs.regular() + \" [ETA: \" + getQueueEta(qs.regular()) + \"]\"\n + \"\\nPrio: \" + qs.prio())\n .orElse(\"Error: Failed to get queue status!\");\n ChatUtils.print(out);\n });\n return null;\n }\n\n public static long getQueueWait(final int queuePos) {\n return (long) (12.7 * (Math.pow(queuePos, 1.28)));\n }\n\n public static String getEtaStringFromSeconds(final long totalSeconds) {\n final int hour = (int) (totalSeconds / 3600);\n final int minutes = (int) ((totalSeconds / 60) % 60);\n final int seconds = (int) (totalSeconds % 60);\n final String hourStr = hour >= 10 ? \"\" + hour : \"0\" + hour;\n final String minutesStr = minutes >= 10 ? \"\" + minutes : \"0\" + minutes;\n final String secondsStr = seconds >= 10 ? \"\" + seconds : \"0\" + seconds;\n return hourStr + \":\" + minutesStr + \":\" + secondsStr;\n }\n\n public static String getQueueEta(final int queuePos) {\n return getEtaStringFromSeconds(getQueueWait(queuePos));\n }\n}"
},
{
"identifier": "SeenCommand",
"path": "src/main/java/vc/command/SeenCommand.java",
"snippet": "public class SeenCommand extends Command {\n private final VcApi api;\n public SeenCommand(final VcApi api) {\n super(\"vcseen\", \"Gets when a player was first and last seen on 2b2t\");\n this.api = api;\n }\n\n @CommandExecutor\n @CommandExecutor.Argument({\"player\"})\n private String seenPlayerName(final PlayerReference player) {\n ForkJoinPool.commonPool().execute(() -> {\n var apiResponse = this.api.getSeen(player);\n if (apiResponse.isEmpty()) {\n ChatUtils.print(\"Error: \" + player.name() + \" not found!\");\n }\n String out = player.name() + \" Seen\";\n out += apiResponse.map(seenResponse -> \"\\nFirst seen: \" + getSeenString(seenResponse.firstSeen())).orElse(\"\");\n out += apiResponse.map(seenResponse -> \"\\nLast seen: \" + getSeenString(seenResponse.lastSeen())).orElse(\"\");\n ChatUtils.print(out);\n });\n return null;\n }\n}"
},
{
"identifier": "StatsCommand",
"path": "src/main/java/vc/command/StatsCommand.java",
"snippet": "public class StatsCommand extends Command {\n private final VcApi api;\n public StatsCommand(final VcApi api) {\n super(\"stats\", \"Gets the 2b2t stats of a player\");\n this.api = api;\n }\n\n @CommandExecutor\n @CommandExecutor.Argument({\"player\"})\n private String statsPlayerName(final PlayerReference player) {\n ForkJoinPool.commonPool().execute(() -> {\n var statsResponse = api.getStats(player);\n var out = statsResponse.map(s ->\n player.name() + \" Stats\" +\n \"\\nJoins: \" + s.joinCount() +\n \"\\nLeaves: \" + s.leaveCount() +\n \"\\nFirst Seen: \" + getSeenString(s.firstSeen()) +\n \"\\nLast Seen: \" + getSeenString(s.lastSeen()) +\n \"\\nPlaytime: \" + formatDuration(Duration.ofSeconds(s.playtimeSeconds())) +\n \"\\nPlaytime (Last 30 Days): \" + formatDuration(Duration.ofSeconds(s.playtimeSecondsMonth())) +\n \"\\nDeaths: \" + s.deathCount() +\n \"\\nKills: \" + s.killCount() +\n \"\\nChats: \" + s.chatsCount())\n .orElse(\"Error: \" + player.name() + \" not found!\");\n ChatUtils.print(out);\n });\n return null;\n }\n}"
},
{
"identifier": "Queue2b2tHudElement",
"path": "src/main/java/vc/hud/Queue2b2tHudElement.java",
"snippet": "public class Queue2b2tHudElement extends ShortListHudElement {\n\n private QueueStatus queueStatus = new QueueStatus(OffsetDateTime.now(), 0, 0);\n private long lastRefreshedEpochS = 0L;\n private final VcApi api;\n final BooleanSetting showPrio = new BooleanSetting(\"Show Prio\", true);\n final BooleanSetting showRegular = new BooleanSetting(\"Show Regular\", true);\n final BooleanSetting showUpdatedTime = new BooleanSetting(\"Show Updated Time\", false);\n\n public Queue2b2tHudElement(final VcApi api) {\n super(\"2b2t Queue\");\n this.api = api;\n registerSettings(showPrio, showRegular, showUpdatedTime);\n }\n\n private void refreshQueueStatus() {\n lastRefreshedEpochS = Instant.now().getEpochSecond();\n ForkJoinPool.commonPool().execute(() -> {\n Optional<QueueStatus> status = this.api.getQueueStatus();\n if (status.isPresent()) {\n queueStatus = status.get();\n } else {\n getLogger().error(\"Failed refreshing 2b2t queue!\");\n }\n });\n }\n\n @Override\n public Component[] getComponents() {\n // refresh every 5 mins in the background\n if (Instant.now().getEpochSecond() - lastRefreshedEpochS > 300L)\n refreshQueueStatus();\n Component regular = null;\n Component prio = null;\n Component updated = null;\n if (showRegular.getValue()) {\n regular = Component.literal(\"Regular: \" + queueStatus.regular());\n }\n if (showPrio.getValue()) {\n prio = Component.literal(\"Prio: \" + queueStatus.prio());\n }\n if (showUpdatedTime.getValue()) {\n updated = Component\n .literal(\"Updated \"\n + FormatUtil.formatDuration(Duration.between(queueStatus.time().toInstant(), Instant.now()))\n + \" ago\");\n }\n return Stream.of(regular, prio, updated)\n .filter(Objects::nonNull)\n .toArray(Component[]::new);\n }\n}"
}
] | import org.rusherhack.client.api.RusherHackAPI;
import org.rusherhack.client.api.plugin.Plugin;
import vc.api.VcApi;
import vc.command.PlaytimeCommand;
import vc.command.QueueCommand;
import vc.command.SeenCommand;
import vc.command.StatsCommand;
import vc.hud.Queue2b2tHudElement; | 2,329 | package vc;
public class VcPlugin extends Plugin {
@Override
public void onLoad() { | package vc;
public class VcPlugin extends Plugin {
@Override
public void onLoad() { | final VcApi api = new VcApi(getLogger()); | 0 | 2023-10-22 20:22:42+00:00 | 4k |
Dwight-Studio/JArmEmu | src/main/java/fr/dwightstudio/jarmemu/gui/view/MemoryChunkView.java | [
{
"identifier": "MemoryAccessor",
"path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/MemoryAccessor.java",
"snippet": "public class MemoryAccessor {\n\n private final HashMap<Integer, IntegerProperty> memory;\n private final HashSet<Integer> initiationMap;\n\n public MemoryAccessor() {\n memory = new HashMap<>();\n initiationMap = new HashSet<>();\n }\n\n public byte getByte(int add) {\n int aAdd = Math.floorDiv(add, 4);\n int rAdd = (add % 4) < 0 ? 4 + (add % 4) : (add % 4);\n\n if (memory.containsKey(aAdd)) {\n byte[] bytes = new byte[4];\n ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt(0, memory.get(aAdd).get());\n return bytes[rAdd];\n } else {\n return 0;\n }\n }\n\n public short getHalf(int add) {\n byte[] bytes = new byte[]{getByte(add), getByte(add + 1)};\n return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();\n }\n\n public int getWord(int add) {\n byte[] bytes = new byte[]{getByte(add), getByte(add + 1), getByte(add + 2), getByte(add + 3)};\n return ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt();\n }\n public void putByte(int add, byte b) {\n int aAdd = Math.floorDiv(add, 4);\n int rAdd = (add % 4) < 0 ? 4 + (add % 4) : (add % 4);\n byte[] bytes = new byte[4];\n ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);\n IntegerProperty property;\n\n if (memory.containsKey(aAdd)) {\n property = memory.get(aAdd);\n buffer.putInt(0, property.get());\n } else {\n property = new SimpleIntegerProperty(0);\n memory.put(aAdd, property);\n }\n\n buffer.put(rAdd, b);\n property.set(buffer.getInt(0));\n initiationMap.add(add);\n }\n\n public void putHalf(int add, short s) {\n byte[] bytes = new byte[2];\n ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putShort(s);\n\n for (int i = 0; i < bytes.length; i++) {\n putByte(add + i, bytes[i]);\n }\n }\n\n public void putWord(int add, int i) {\n byte[] bytes = new byte[4];\n ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt(i);\n\n for (int j = 0; j < bytes.length; j++) {\n putByte(add + j, bytes[j]);\n }\n }\n\n public void clear() {\n memory.clear();\n }\n\n public boolean isByteInitiated(int address) {\n return initiationMap.contains(address);\n }\n\n public boolean isHalfInitiated(int address) {\n return isByteInitiated(address - (address % 4)) || isByteInitiated(address - (address % 4) + 1);\n }\n\n public boolean isWordInitiated(int address) {\n return isHalfInitiated(address - (address % 4)) || isHalfInitiated(address - (address % 4) + 2);\n }\n\n public IntegerProperty getProperty(int address) {\n int aAdd = Math.floorDiv(address, 4);\n if (memory.containsKey(aAdd)) {\n return memory.get(aAdd);\n } else {\n IntegerProperty property = new SimpleIntegerProperty(0);\n memory.put(aAdd, property);\n return property;\n }\n }\n\n}"
},
{
"identifier": "WordASCIIStringConverter",
"path": "src/main/java/fr/dwightstudio/jarmemu/util/converters/WordASCIIStringConverter.java",
"snippet": "public class WordASCIIStringConverter extends StringConverter<Number> {\n @Override\n public String toString(Number number) {\n byte[] bytes = new byte[4];\n ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt((Integer) number);\n\n String s0 = new String(new byte[]{bytes[0]}, StandardCharsets.UTF_8).replace('\\0', '_');\n String s1 = new String(new byte[]{bytes[1]}, StandardCharsets.UTF_8).replace('\\0', '_');\n String s2 = new String(new byte[]{bytes[2]}, StandardCharsets.UTF_8).replace('\\0', '_');\n String s3 = new String(new byte[]{bytes[3]}, StandardCharsets.UTF_8).replace('\\0', '_');\n\n return s0 + s1 + s2 + s3;\n }\n\n @Override\n public Number fromString(String s) {\n\n switch (s.length()) {\n case 0 -> s = \"\\0\\0\\0\\0\";\n case 1 -> s = s + \"\\0\\0\\0\";\n case 2 -> s = s + \"\\0\\0\";\n case 3 -> s = s + \"\\0\";\n default -> s = s.substring(0,4);\n }\n\n return ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)).order(ByteOrder.LITTLE_ENDIAN).getInt();\n }\n}"
}
] | import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import java.util.ArrayList;
import fr.dwightstudio.jarmemu.sim.obj.MemoryAccessor;
import fr.dwightstudio.jarmemu.util.converters.WordASCIIStringConverter;
import javafx.beans.InvalidationListener;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.property.ReadOnlyStringProperty; | 1,983 | /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.view;
public class MemoryChunkView {
private final MemoryAccessor memoryAccessor;
private final ReadOnlyIntegerProperty addressProperty;
private final IntegerProperty value0Property;
private final IntegerProperty value1Property;
private final IntegerProperty value2Property;
private final IntegerProperty value3Property;
public MemoryChunkView(MemoryAccessor memoryAccessor, int address) {
this.memoryAccessor = memoryAccessor;
this.addressProperty = new ReadOnlyIntegerWrapper(address);
this.value0Property = memoryAccessor.getProperty(address);
this.value1Property = memoryAccessor.getProperty(address + 4);
this.value2Property = memoryAccessor.getProperty(address + 8);
this.value3Property = memoryAccessor.getProperty(address + 12);
}
public MemoryAccessor getMemoryAccessor() {
return memoryAccessor;
}
public ReadOnlyIntegerProperty getAddressProperty() {
return addressProperty;
}
public IntegerProperty getValue0Property() {
return value0Property;
}
public IntegerProperty getValue1Property() {
return value1Property;
}
public IntegerProperty getValue2Property() {
return value2Property;
}
public IntegerProperty getValue3Property() {
return value3Property;
}
public ObservableValue<String> getASCIIProperty() {
return new ChunkASCIIProperty();
}
public class ChunkASCIIProperty extends ReadOnlyStringProperty {
private final ArrayList<ChangeListener<? super String>> changeListeners;
private final ArrayList<InvalidationListener> invalidationListeners;
| /*
* ____ _ __ __ _____ __ ___
* / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___
* / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \
* / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ /
* /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/
* /____/
* Copyright (C) 2023 Dwight Studio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package fr.dwightstudio.jarmemu.gui.view;
public class MemoryChunkView {
private final MemoryAccessor memoryAccessor;
private final ReadOnlyIntegerProperty addressProperty;
private final IntegerProperty value0Property;
private final IntegerProperty value1Property;
private final IntegerProperty value2Property;
private final IntegerProperty value3Property;
public MemoryChunkView(MemoryAccessor memoryAccessor, int address) {
this.memoryAccessor = memoryAccessor;
this.addressProperty = new ReadOnlyIntegerWrapper(address);
this.value0Property = memoryAccessor.getProperty(address);
this.value1Property = memoryAccessor.getProperty(address + 4);
this.value2Property = memoryAccessor.getProperty(address + 8);
this.value3Property = memoryAccessor.getProperty(address + 12);
}
public MemoryAccessor getMemoryAccessor() {
return memoryAccessor;
}
public ReadOnlyIntegerProperty getAddressProperty() {
return addressProperty;
}
public IntegerProperty getValue0Property() {
return value0Property;
}
public IntegerProperty getValue1Property() {
return value1Property;
}
public IntegerProperty getValue2Property() {
return value2Property;
}
public IntegerProperty getValue3Property() {
return value3Property;
}
public ObservableValue<String> getASCIIProperty() {
return new ChunkASCIIProperty();
}
public class ChunkASCIIProperty extends ReadOnlyStringProperty {
private final ArrayList<ChangeListener<? super String>> changeListeners;
private final ArrayList<InvalidationListener> invalidationListeners;
| private WordASCIIStringConverter converter; | 1 | 2023-10-17 18:22:09+00:00 | 4k |
GTNewHorizons/FarmingForEngineers | src/main/java/com/guigs44/farmingforengineers/container/ContainerMarket.java | [
{
"identifier": "MessageMarketList",
"path": "src/main/java/com/guigs44/farmingforengineers/network/MessageMarketList.java",
"snippet": "public class MessageMarketList implements IMessage {\n\n private Collection<MarketEntry> entryList;\n\n public MessageMarketList() {}\n\n public MessageMarketList(Collection<MarketEntry> entryList) {\n this.entryList = entryList;\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n int entryCount = buf.readInt();\n entryList = Lists.newArrayListWithCapacity(entryCount);\n for (int i = 0; i < entryCount; i++) {\n entryList.add(readEntry(buf));\n }\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n int count = entryList.size();\n buf.writeInt(count);\n for (MarketEntry recipe : entryList) {\n writeEntry(recipe, buf);\n }\n }\n\n public Collection<MarketEntry> getEntryList() {\n return entryList;\n }\n\n private MarketEntry readEntry(ByteBuf buf) {\n ItemStack outputItem = ByteBufUtils.readItemStack(buf);\n ItemStack costItem = ByteBufUtils.readItemStack(buf);\n MarketEntry.EntryType type = MarketEntry.EntryType.fromId(buf.readByte());\n return new MarketEntry(outputItem, costItem, type);\n }\n\n private void writeEntry(MarketEntry entry, ByteBuf buf) {\n ByteBufUtils.writeItemStack(buf, entry.getOutputItem());\n ByteBufUtils.writeItemStack(buf, entry.getCostItem());\n buf.writeByte(entry.getType().ordinal());\n }\n}"
},
{
"identifier": "NetworkHandler",
"path": "src/main/java/com/guigs44/farmingforengineers/network/NetworkHandler.java",
"snippet": "public class NetworkHandler {\n\n public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE\n .newSimpleChannel(FarmingForEngineers.MOD_ID);\n\n public static void init() {\n instance.registerMessage(HandlerMarketList.class, MessageMarketList.class, 0, Side.CLIENT);\n instance.registerMessage(HandlerMarketSelect.class, MessageMarketSelect.class, 1, Side.SERVER);\n }\n\n // public static Minecraft getThreadListener(MessageContext ctx) {\n // return ctx.side == Side.SERVER ? ctx.getServerHandler().playerEntity.worldObj : getClientThreadListener();\n // }\n\n @SideOnly(Side.CLIENT)\n public static Minecraft getClientThreadListener() {\n return Minecraft.getMinecraft();\n }\n}"
},
{
"identifier": "MarketEntry",
"path": "src/main/java/com/guigs44/farmingforengineers/registry/MarketEntry.java",
"snippet": "public class MarketEntry {\n\n public enum EntryType {\n\n SEEDS(\"gui.farmingforengineers:market.tooltip_seeds\"),\n SAPLINGS(\"gui.farmingforengineers:market.tooltip_saplings\"),\n OTHER(\"gui.farmingforengineers:market.tooltip_other\");\n\n private static final ResourceLocation TEXTURE = new ResourceLocation(\n FarmingForEngineers.MOD_ID,\n \"textures/gui/market.png\");\n private static final EntryType[] values = values();\n private String tooltip;\n\n EntryType(String tooltip) {\n this.tooltip = tooltip;\n }\n\n public String getTooltip() {\n return tooltip;\n }\n\n public ResourceLocation getIconTexture() {\n return TEXTURE;\n }\n\n public int getIconTextureX() {\n return 196 + ordinal() * 20;\n }\n\n public int getIconTextureY() {\n return 14;\n }\n\n public boolean passes(MarketEntry entry) {\n return entry.getType() == this;\n }\n\n public static EntryType fromId(int id) {\n return values[id];\n }\n }\n\n private final ItemStack outputItem;\n private final ItemStack costItem;\n private final EntryType type;\n\n public MarketEntry(ItemStack outputItem, ItemStack costItem, EntryType type) {\n this.outputItem = outputItem;\n this.costItem = costItem;\n this.type = type;\n }\n\n public ItemStack getCostItem() {\n return costItem;\n }\n\n public ItemStack getOutputItem() {\n return outputItem;\n }\n\n public EntryType getType() {\n return type;\n }\n}"
},
{
"identifier": "MarketRegistry",
"path": "src/main/java/com/guigs44/farmingforengineers/registry/MarketRegistry.java",
"snippet": "public class MarketRegistry extends AbstractRegistry {\n\n public static final MarketRegistry INSTANCE = new MarketRegistry();\n\n private static final Pattern ITEMSTACK_PATTERN = Pattern\n .compile(\"(?:([0-9]+)\\\\*)?(?:([\\\\w]+):)([\\\\w]+)(?::([0-9]+))?(?:@(.+))?\");\n\n private final List<MarketEntry> entries = Lists.newArrayList();\n\n private final Map<String, ItemStack> defaultPayments = Maps.newHashMap();\n private final Map<String, MarketRegistryDefaultHandler> defaultHandlers = Maps.newHashMap();\n\n public MarketRegistry() {\n super(\"Market\");\n }\n\n public void registerEntry(ItemStack outputItem, ItemStack costItem, MarketEntry.EntryType type) {\n entries.add(new MarketEntry(outputItem, costItem, type));\n }\n\n @Nullable\n public static MarketEntry getEntryFor(ItemStack outputItem) {\n for (MarketEntry entry : INSTANCE.entries) {\n if (entry.getOutputItem().isItemEqual(outputItem)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), outputItem)) {\n return entry;\n }\n }\n return null;\n }\n\n public static Collection<MarketEntry> getEntries() {\n return INSTANCE.entries;\n }\n\n @Override\n protected void clear() {\n entries.clear();\n }\n\n @Override\n protected JsonObject create() {\n JsonObject root = new JsonObject();\n\n JsonObject defaults = new JsonObject();\n defaults.addProperty(\n \"__comment\",\n \"You can disable defaults by setting these to false. Do *NOT* try to add additional entries here. You can add additional entries in the custom section.\");\n root.add(\"defaults\", defaults);\n\n JsonObject payment = new JsonObject();\n payment.addProperty(\"__comment\", \"You can define custom payment items for the default entries here.\");\n root.add(\"defaults payment\", payment);\n\n JsonArray blacklist = new JsonArray();\n blacklist.add(new JsonPrimitive(\"examplemod:example_item\"));\n root.add(\"defaults blacklist\", blacklist);\n\n JsonObject custom = new JsonObject();\n custom.addProperty(\n \"__comment\",\n \"You can define additional items to be sold by the Market here. Defaults can be overridden. Prefix with ! to blacklist instead.\");\n custom.addProperty(\"examplemod:example_item\", \"2*minecraft:emerald\");\n root.add(\"custom entries\", custom);\n\n return root;\n }\n\n @Override\n protected void load(JsonObject root) {\n JsonObject payments = tryGetObject(root, \"defaults payment\");\n loadDefaultPayments(payments);\n\n JsonObject defaults = tryGetObject(root, \"defaults\");\n registerDefaults(defaults);\n\n JsonArray blacklist = tryGetArray(root, \"defaults blacklist\");\n for (int i = 0; i < blacklist.size(); i++) {\n JsonElement element = blacklist.get(i);\n if (element.isJsonPrimitive()) {\n loadDefaultBlacklistEntry(element.getAsString());\n } else {\n logError(\"Failed to load %s registry: blacklist entries must be strings\", registryName);\n }\n }\n\n JsonObject custom = tryGetObject(root, \"custom entries\");\n for (Map.Entry<String, JsonElement> entry : custom.entrySet()) {\n if (entry.getValue().isJsonPrimitive()) {\n loadMarketEntry(entry.getKey(), entry.getValue().getAsString());\n } else {\n logError(\"Failed to load %s registry: entries must be strings\", registryName);\n }\n }\n }\n\n @Override\n protected boolean hasCustomLoader() {\n return true;\n }\n\n private void loadMarketEntry(String key, String value) {\n if (key.equals(\"__comment\") || key.equals(\"examplemod:example_item\")) {\n return;\n }\n\n ItemStack outputStack = parseItemStack(key);\n ItemStack costStack = parseItemStack(value);\n if (outputStack == null || costStack == null) {\n return;\n }\n\n tryRemoveEntry(outputStack);\n\n MarketEntry.EntryType type = MarketEntry.EntryType.OTHER;\n\n // outputStack.getItem().getRegistryName().getResourcePath().contains(\"sapling\") maybe\n if (outputStack.getItem().getUnlocalizedName().contains(\"sapling\")) {\n type = MarketEntry.EntryType.SAPLINGS;\n } else if (outputStack.getItem().getUnlocalizedName().contains(\"seed\")) {\n type = MarketEntry.EntryType.SEEDS;\n }\n\n registerEntry(outputStack, costStack, type);\n }\n\n private void loadDefaultBlacklistEntry(String input) {\n if (input.equals(\"examplemod:example_item\")) {\n return;\n }\n ItemStack itemStack = parseItemStack(input);\n if (itemStack != null) {\n if (!tryRemoveEntry(itemStack)) {\n logError(\"Could not find default entry for blacklisted item %s\", input);\n }\n }\n }\n\n private void loadDefaultPayments(JsonObject defaults) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n String value = tryGetString(defaults, entry.getKey(), \"\");\n if (value.isEmpty()) {\n ItemStack defaultPayment = entry.getValue().getDefaultPayment();\n defaults.addProperty(\n entry.getKey(),\n String.format(\n \"%d*%s:%d\",\n defaultPayment.stackSize,\n defaultPayment.getItem().getUnlocalizedName(),\n defaultPayment.getItemDamage()));\n }\n ItemStack itemStack = !value.isEmpty() ? parseItemStack(value) : null;\n if (itemStack == null) {\n itemStack = entry.getValue().getDefaultPayment();\n }\n defaultPayments.put(entry.getKey(), itemStack);\n }\n }\n\n @Override\n protected void registerDefaults(JsonObject json) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n if (tryGetBoolean(json, entry.getKey(), entry.getValue().isEnabledByDefault())) {\n entry.getValue().apply(this, INSTANCE.defaultPayments.get(entry.getKey()));\n }\n }\n }\n\n public static void registerDefaultHandler(String defaultKey, MarketRegistryDefaultHandler handler) {\n INSTANCE.defaultHandlers.put(defaultKey, handler);\n }\n\n private boolean tryRemoveEntry(ItemStack itemStack) {\n for (int i = entries.size() - 1; i >= 0; i--) {\n MarketEntry entry = entries.get(i);\n if (entry.getOutputItem().isItemEqual(itemStack)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), itemStack)) {\n entries.remove(i);\n return true;\n }\n }\n return false;\n }\n\n @Nullable\n private ItemStack parseItemStack(String input) {\n Matcher matcher = ITEMSTACK_PATTERN.matcher(input);\n if (!matcher.find()) {\n logError(\"Invalid item %s, format mismatch\", input);\n return null;\n }\n\n ResourceLocation resourceLocation = new ResourceLocation(matcher.group(2), matcher.group(3));\n Item item = (Item) Item.itemRegistry.getObject(resourceLocation.toString());\n if (item == null) {\n logUnknownItem(resourceLocation);\n return null;\n }\n int count = matcher.group(1) != null ? tryParseInt(matcher.group(1)) : 1;\n int meta = matcher.group(4) != null ? tryParseInt(matcher.group(4)) : 0;\n String nbt = matcher.group(5);\n NBTTagCompound tagCompound = null;\n if (nbt != null) {\n tagCompound = (NBTTagCompound) codechicken.nei.util.NBTJson.toNbt(JsonParser.parseString(nbt));\n }\n ItemStack itemStack = new ItemStack(item, count, meta);\n if (tagCompound != null) {\n itemStack.setTagCompound(tagCompound);\n }\n return itemStack;\n }\n}"
}
] | import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryBasic;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import com.google.common.collect.Lists;
import com.guigs44.farmingforengineers.network.MessageMarketList;
import com.guigs44.farmingforengineers.network.NetworkHandler;
import com.guigs44.farmingforengineers.registry.MarketEntry;
import com.guigs44.farmingforengineers.registry.MarketRegistry; | 3,172 | package com.guigs44.farmingforengineers.container;
public class ContainerMarket extends Container {
private final EntityPlayer player;
private final int posX;
private final int posY;
private final int posZ;
private final InventoryBasic marketInputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
private final InventoryBasic marketOutputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList();
private boolean sentItemList; | package com.guigs44.farmingforengineers.container;
public class ContainerMarket extends Container {
private final EntityPlayer player;
private final int posX;
private final int posY;
private final int posZ;
private final InventoryBasic marketInputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
private final InventoryBasic marketOutputBuffer = new InventoryBasic(
"container.farmingforengineers:market",
false,
1);
protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList();
private boolean sentItemList; | protected MarketEntry selectedEntry; | 2 | 2023-10-17 00:25:50+00:00 | 4k |
mnesimiyilmaz/sql4json | src/main/java/io/github/mnesimiyilmaz/sql4json/grouping/GroupByProcessor.java | [
{
"identifier": "JsonColumnWithNonAggFunctionDefinion",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/definitions/JsonColumnWithNonAggFunctionDefinion.java",
"snippet": "@Getter\npublic class JsonColumnWithNonAggFunctionDefinion {\n\n private final SQL4JsonParser.JsonColumnWithNonAggFunctionContext columnContext;\n private final String columnName;\n private final Function<Object, Object> valueDecorator;\n\n public JsonColumnWithNonAggFunctionDefinion(SQL4JsonParser.JsonColumnWithNonAggFunctionContext columnContext) {\n this.columnContext = columnContext;\n this.columnName = columnContext.jsonColumn().getText();\n if (columnContext.NON_AGG_FUNCTION() != null) {\n List<Object> args = new ArrayList<>();\n if (columnContext.params() != null && columnContext.params().value() != null) {\n List<SQL4JsonParser.ValueContext> valueContexts = columnContext.params().value();\n for (SQL4JsonParser.ValueContext valueContext : valueContexts) {\n args.add(ValueUtils.getValueFromContext(valueContext));\n }\n }\n this.valueDecorator = in -> ParameterizedFunctionUtils.getFunction(\n columnContext.NON_AGG_FUNCTION().getText().toLowerCase()).apply(in, args);\n } else {\n this.valueDecorator = null;\n }\n }\n\n public Optional<Function<Object, Object>> getValueDecorator() {\n return Optional.ofNullable(valueDecorator);\n }\n\n}"
},
{
"identifier": "SelectColumnDefinition",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/definitions/SelectColumnDefinition.java",
"snippet": "@Getter\npublic class SelectColumnDefinition {\n\n private final SQL4JsonParser.SelectColumnContext ctx;\n private final JsonColumnWithAggFunctionDefinion columnDefinition;\n private final String alias;\n private final boolean isAsterisk;\n\n private SelectColumnDefinition() {\n this.ctx = null;\n this.columnDefinition = null;\n this.alias = null;\n this.isAsterisk = true;\n }\n\n public SelectColumnDefinition(SQL4JsonParser.SelectColumnContext ctx) {\n this.ctx = ctx;\n this.columnDefinition = new JsonColumnWithAggFunctionDefinion(ctx.jsonColumnWithAggFunction());\n if (ctx.AS() != null) {\n this.alias = ctx.jsonColumn().getText();\n } else {\n this.alias = null;\n }\n this.isAsterisk = false;\n }\n\n public static SelectColumnDefinition ofAsterisk() {\n return new SelectColumnDefinition();\n }\n\n}"
},
{
"identifier": "AggregateFunction",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/utils/AggregateFunction.java",
"snippet": "public enum AggregateFunction {\n SUM,\n AVG,\n MAX,\n MIN,\n COUNT\n}"
},
{
"identifier": "AggregationUtils",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/utils/AggregationUtils.java",
"snippet": "public final class AggregationUtils {\n\n private static final Map<AggregateFunction, Function<List<Object>, Object>> AGG_MAP;\n\n private AggregationUtils() {}\n\n public static Map<AggregateFunction, Function<List<Object>, Object>> getAggregationFunctionMap() {\n return AGG_MAP;\n }\n\n public static Function<List<Object>, Object> getAggregationFunction(AggregateFunction function) {\n return AGG_MAP.get(function);\n }\n\n static {\n Map<AggregateFunction, Function<List<Object>, Object>> aggMap = new EnumMap<>(AggregateFunction.class);\n aggMap.put(AggregateFunction.COUNT, List::size);\n aggMap.put(AggregateFunction.SUM, values -> values.stream().map(x -> ((Number) x).doubleValue()).reduce(0.0, Double::sum));\n aggMap.put(AggregateFunction.AVG, values -> values.stream().map(x -> ((Number) x).doubleValue()).reduce(0.0, Double::sum) / values.size());\n aggMap.put(AggregateFunction.MIN, values -> {\n if (values.get(0) instanceof Number) {\n return values.stream().map(x -> ((Number) x).doubleValue()).min(Double::compareTo).orElse(null);\n } else if (values.get(0) instanceof LocalDate) {\n return values.stream().map(x -> ((LocalDate) x)).min(LocalDate::compareTo).orElse(null);\n } else if (values.get(0) instanceof LocalDateTime) {\n return values.stream().map(x -> ((LocalDateTime) x)).min(LocalDateTime::compareTo).orElse(null);\n } else {\n throw new IllegalArgumentException(\"Unsupported type for min aggregation: \" + values.get(0).getClass().getName());\n }\n });\n aggMap.put(AggregateFunction.MAX, values -> {\n if (values.get(0) instanceof Number) {\n return values.stream().map(x -> ((Number) x).doubleValue()).max(Double::compareTo).orElse(null);\n } else if (values.get(0) instanceof LocalDate) {\n return values.stream().map(x -> ((LocalDate) x)).max(LocalDate::compareTo).orElse(null);\n } else if (values.get(0) instanceof LocalDateTime) {\n return values.stream().map(x -> ((LocalDateTime) x)).max(LocalDateTime::compareTo).orElse(null);\n } else {\n throw new IllegalArgumentException(\"Unsupported type for max aggregation: \" + values.get(0).getClass().getName());\n }\n });\n AGG_MAP = Collections.unmodifiableMap(aggMap);\n }\n\n}"
},
{
"identifier": "FieldKey",
"path": "src/main/java/io/github/mnesimiyilmaz/sql4json/utils/FieldKey.java",
"snippet": "@Getter\npublic class FieldKey {\n\n private final String key;\n private final String family;\n\n public FieldKey(String key, String family) {\n Objects.requireNonNull(key);\n this.key = key;\n this.family = family;\n }\n\n public FieldKey(String key) {\n this(key, null);\n }\n\n public static FieldKey of(String key, String family) {\n return new FieldKey(key, family);\n }\n\n public static FieldKey of(String key) {\n return new FieldKey(key);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n FieldKey fieldKey = (FieldKey) o;\n return Objects.equals(key, fieldKey.key);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(key);\n }\n\n}"
}
] | import io.github.mnesimiyilmaz.sql4json.definitions.JsonColumnWithNonAggFunctionDefinion;
import io.github.mnesimiyilmaz.sql4json.definitions.SelectColumnDefinition;
import io.github.mnesimiyilmaz.sql4json.utils.AggregateFunction;
import io.github.mnesimiyilmaz.sql4json.utils.AggregationUtils;
import io.github.mnesimiyilmaz.sql4json.utils.FieldKey;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static io.github.mnesimiyilmaz.sql4json.utils.AggregateFunction.COUNT; | 2,044 | package io.github.mnesimiyilmaz.sql4json.grouping;
/**
* @author mnesimiyilmaz
*/
public class GroupByProcessor {
private final GroupByInput groupByInput;
private final Map<String, FieldKey> groupByFieldCache;
private final List<SelectColumnDefinition> nonAggColumnsCache;
private final List<SelectColumnDefinition> aggColumnsCache;
public GroupByProcessor(GroupByInput groupByInput) {
this.groupByInput = groupByInput;
this.groupByFieldCache = new HashMap<>();
this.groupByInput.getGroupByColumns()
.forEach(x -> groupByFieldCache.put(x.getColumnName(), FieldKey.of(x.getColumnName())));
this.nonAggColumnsCache = groupByInput.getSelectedColumns().stream()
.filter(x -> x.getColumnDefinition().getAggregateFunction() == null).collect(Collectors.toList());
this.aggColumnsCache = groupByInput.getSelectedColumns()
.stream().filter(x -> x.getColumnDefinition().getAggregateFunction() != null).collect(Collectors.toList());
}
public List<Map<FieldKey, Object>> process() {
Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = groupRows();
List<Map<FieldKey, Object>> groupByResult = applyAggregations(groupedRows);
if (groupByInput.getHavingClause() != null) {
groupByResult.removeIf(x -> !groupByInput.getHavingClause().test(x));
}
return groupByResult;
}
private Map<GroupRowData, List<Map<FieldKey, Object>>> groupRows() {
Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = new HashMap<>();
for (Map<FieldKey, Object> row : this.groupByInput.getFlattenedInputJsonNode()) {
Map<String, Object> groupRowData = new HashMap<>(); | package io.github.mnesimiyilmaz.sql4json.grouping;
/**
* @author mnesimiyilmaz
*/
public class GroupByProcessor {
private final GroupByInput groupByInput;
private final Map<String, FieldKey> groupByFieldCache;
private final List<SelectColumnDefinition> nonAggColumnsCache;
private final List<SelectColumnDefinition> aggColumnsCache;
public GroupByProcessor(GroupByInput groupByInput) {
this.groupByInput = groupByInput;
this.groupByFieldCache = new HashMap<>();
this.groupByInput.getGroupByColumns()
.forEach(x -> groupByFieldCache.put(x.getColumnName(), FieldKey.of(x.getColumnName())));
this.nonAggColumnsCache = groupByInput.getSelectedColumns().stream()
.filter(x -> x.getColumnDefinition().getAggregateFunction() == null).collect(Collectors.toList());
this.aggColumnsCache = groupByInput.getSelectedColumns()
.stream().filter(x -> x.getColumnDefinition().getAggregateFunction() != null).collect(Collectors.toList());
}
public List<Map<FieldKey, Object>> process() {
Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = groupRows();
List<Map<FieldKey, Object>> groupByResult = applyAggregations(groupedRows);
if (groupByInput.getHavingClause() != null) {
groupByResult.removeIf(x -> !groupByInput.getHavingClause().test(x));
}
return groupByResult;
}
private Map<GroupRowData, List<Map<FieldKey, Object>>> groupRows() {
Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = new HashMap<>();
for (Map<FieldKey, Object> row : this.groupByInput.getFlattenedInputJsonNode()) {
Map<String, Object> groupRowData = new HashMap<>(); | for (JsonColumnWithNonAggFunctionDefinion groupByColumn : this.groupByInput.getGroupByColumns()) { | 0 | 2023-10-24 18:34:33+00:00 | 4k |
clclab/pcfg-lm | src/berkeley_parser/edu/berkeley/nlp/treebank/AbstractTreebankLanguagePack.java | [
{
"identifier": "Filter",
"path": "src/berkeley_parser/edu/berkeley/nlp/util/Filter.java",
"snippet": "public interface Filter<T> {\n\tboolean accept(T t);\n}"
},
{
"identifier": "Filters",
"path": "src/berkeley_parser/edu/berkeley/nlp/util/Filters.java",
"snippet": "public class Filters {\n\n\t/**\n\t * Nothing to instantiate\n\t */\n\tprivate Filters() {\n\t}\n\n\t/**\n\t * The acceptFilter accepts everything.\n\t */\n\tpublic static Filter acceptFilter() {\n\t\treturn new CategoricalFilter(true);\n\t}\n\n\tpublic static <T> Filter<T> acceptFilter(Class<T> name) {\n\t\treturn new CategoricalFilter<T>(true);\n\t}\n\n\tpublic static <T> Filter<T> acceptFilter(T dummyObject) {\n\t\treturn new CategoricalFilter<T>(true);\n\t}\n\n\t/**\n\t * The rejectFilter accepts nothing.\n\t */\n\tpublic static Filter rejectFilter() {\n\t\treturn new CategoricalFilter(false);\n\t}\n\n\tprivate static final class CategoricalFilter<T> implements Filter<T> {\n\n\t\tprivate final boolean judgment;\n\n\t\tprivate CategoricalFilter(boolean judgment) {\n\t\t\tthis.judgment = judgment;\n\t\t}\n\n\t\t/**\n\t\t * Checks if the given object passes the filter.\n\t\t * \n\t\t * @param obj\n\t\t * an object to test\n\t\t */\n\t\tpublic boolean accept(T obj) {\n\t\t\treturn judgment;\n\t\t}\n\t}\n\n\t/**\n\t * The collectionAcceptFilter accepts a certain collection.\n\t */\n\tpublic static <T> Filter<T> collectionAcceptFilter(T[] objs) {\n\t\treturn new CollectionAcceptFilter<T>(Arrays.asList(objs), true);\n\t}\n\n\t/**\n\t * The collectionAcceptFilter accepts a certain collection.\n\t */\n\tpublic static <T> Filter<T> collectionAcceptFilter(Collection<T> objs) {\n\t\treturn new CollectionAcceptFilter<T>(objs, true);\n\t}\n\n\t/**\n\t * The collectionRejectFilter rejects a certain collection.\n\t */\n\tpublic static <T> Filter<T> collectionRejectFilter(T[] objs) {\n\t\treturn new CollectionAcceptFilter<T>(Arrays.asList(objs), false);\n\t}\n\n\t/**\n\t * The collectionRejectFilter rejects a certain collection.\n\t */\n\tpublic static <T> Filter<T> collectionRejectFilter(Collection<T> objs) {\n\t\treturn new CollectionAcceptFilter<T>(objs, false);\n\t}\n\n\tprivate static final class CollectionAcceptFilter<T> implements Filter<T>,\n\t\t\tSerializable {\n\n\t\tprivate static final long serialVersionUID = 1L;\n\t\tprivate final Collection<T> args;\n\t\tprivate final boolean judgment;\n\n\t\tprivate CollectionAcceptFilter(Collection<T> c, boolean judgment) {\n\t\t\tthis.args = new HashSet<T>(c);\n\t\t\tthis.judgment = judgment;\n\t\t}\n\n\t\t/**\n\t\t * Checks if the given object passes the filter.\n\t\t * \n\t\t * @param obj\n\t\t * an object to test\n\t\t */\n\t\tpublic boolean accept(T obj) {\n\t\t\tif (args.contains(obj)) {\n\t\t\t\treturn judgment;\n\t\t\t} else {\n\t\t\t\treturn !judgment;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Filter that accepts only when both filters accept (AND).\n\t */\n\tpublic static <T> Filter<T> andFilter(Filter<T> f1, Filter<T> f2) {\n\t\treturn (new CombinedFilter<T>(f1, f2, true));\n\t}\n\n\t/**\n\t * Filter that accepts when either filter accepts (OR).\n\t */\n\tpublic static <T> Filter<T> orFilter(Filter<T> f1, Filter<T> f2) {\n\t\treturn (new CombinedFilter<T>(f1, f2, false));\n\t}\n\n\t/**\n\t * Conjunction or disjunction of two filters.\n\t */\n\tprivate static class CombinedFilter<T> implements Filter<T> {\n\t\tprivate Filter<T> f1, f2;\n\t\tprivate boolean conjunction; // and vs. or\n\n\t\tpublic CombinedFilter(Filter<T> f1, Filter<T> f2, boolean conjunction) {\n\t\t\tthis.f1 = f1;\n\t\t\tthis.f2 = f2;\n\t\t\tthis.conjunction = conjunction;\n\t\t}\n\n\t\tpublic boolean accept(T o) {\n\t\t\tif (conjunction) {\n\t\t\t\treturn (f1.accept(o) && f2.accept(o));\n\t\t\t}\n\t\t\treturn (f1.accept(o) || f2.accept(o));\n\t\t}\n\t}\n\n\t/**\n\t * Filter that does the opposite of given filter (NOT).\n\t */\n\tpublic static <T> Filter<T> notFilter(Filter<T> filter) {\n\t\treturn (new NegatedFilter<T>(filter));\n\t}\n\n\t/**\n\t * Filter that's either negated or normal as specified.\n\t */\n\tpublic static <T> Filter<T> switchedFilter(Filter<T> filter, boolean negated) {\n\t\treturn (new NegatedFilter<T>(filter, negated));\n\t}\n\n\t/**\n\t * Negation of a filter.\n\t */\n\tprivate static class NegatedFilter<T> implements Filter<T> {\n\t\tprivate Filter<T> filter;\n\t\tprivate boolean negated;\n\n\t\tpublic NegatedFilter(Filter<T> filter, boolean negated) {\n\t\t\tthis.filter = filter;\n\t\t\tthis.negated = negated;\n\t\t}\n\n\t\tpublic NegatedFilter(Filter<T> filter) {\n\t\t\tthis(filter, true);\n\t\t}\n\n\t\tpublic boolean accept(T o) {\n\t\t\treturn (negated ^ filter.accept(o)); // xor\n\t\t}\n\t}\n\n\t/**\n\t * Applies the given filter to each of the given elems, and returns the list\n\t * of elems that were accepted. The runtime type of the returned array is\n\t * the same as the passed in array.\n\t */\n\tpublic static <T> Object[] filter(T[] elems, Filter<T> filter) {\n\t\tList<T> filtered = new ArrayList<T>();\n\t\tfor (int i = 0; i < elems.length; i++) {\n\t\t\tif (filter.accept(elems[i])) {\n\t\t\t\tfiltered.add(elems[i]);\n\t\t\t}\n\t\t}\n\t\treturn (filtered.toArray((Object[]) Array.newInstance(elems.getClass()\n\t\t\t\t.getComponentType(), filtered.size())));\n\t}\n\n\t/**\n\t * Removes all elems in the given Collection that aren't accepted by the\n\t * given Filter.\n\t */\n\tpublic static <T> void retainAll(Collection<T> elems, Filter<T> filter) {\n\t\tfor (T elem : elems) {\n\t\t\tif (!filter.accept(elem)) {\n\t\t\t\telems.remove(elem);\n\t\t\t}\n\t\t}\n\t}\n\n}"
}
] | import java.io.Serializable;
import edu.berkeley.nlp.util.Filter;
import edu.berkeley.nlp.util.Filters; | 2,472 | package edu.berkeley.nlp.treebank;
/**
* This provides an implementation of parts of the TreebankLanguagePack API to
* reduce the load on fresh implementations. Only the abstract methods below
* need to be implemented to give a reasonable solution for a new language.
*
* @author Christopher Manning
* @version 1.1
*/
public abstract class AbstractTreebankLanguagePack implements
TreebankLanguagePack, Serializable {
/**
* Use this as the default encoding for Readers and Writers of Treebank
* data.
*/
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* Gives a handle to the TreebankLanguagePack
*/
public AbstractTreebankLanguagePack() {
}
/**
* Returns a String array of punctuation tags for this treebank/language.
*
* @return The punctuation tags
*/
public abstract String[] punctuationTags();
/**
* Returns a String array of punctuation words for this treebank/language.
*
* @return The punctuation words
*/
public abstract String[] punctuationWords();
/**
* Returns a String array of sentence final punctuation tags for this
* treebank/language.
*
* @return The sentence final punctuation tags
*/
public abstract String[] sentenceFinalPunctuationTags();
/**
* Returns a String array of punctuation tags that EVALB-style evaluation
* should ignore for this treebank/language. Traditionally, EVALB has
* ignored a subset of the total set of punctuation tags in the English Penn
* Treebank (quotes and period, comma, colon, etc., but not brackets)
*
* @return Whether this is a EVALB-ignored punctuation tag
*/
public String[] evalBIgnoredPunctuationTags() {
return punctuationTags();
}
/**
* Accepts a String that is a punctuation tag name, and rejects everything
* else.
*
* @return Whether this is a punctuation tag
*/
public boolean isPunctuationTag(String str) {
return punctTagStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a punctuation word, and rejects everything else.
* If one can't tell for sure (as for ' in the Penn Treebank), it maks the
* best guess that it can.
*
* @return Whether this is a punctuation word
*/
public boolean isPunctuationWord(String str) {
return punctWordStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a sentence end punctuation tag, and rejects
* everything else.
*
* @return Whether this is a sentence final punctuation tag
*/
public boolean isSentenceFinalPunctuationTag(String str) {
return sFPunctTagStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a punctuation tag that should be ignored by
* EVALB-style evaluation, and rejects everything else. Traditionally, EVALB
* has ignored a subset of the total set of punctuation tags in the English
* Penn Treebank (quotes and period, comma, colon, etc., but not brackets)
*
* @return Whether this is a EVALB-ignored punctuation tag
*/
public boolean isEvalBIgnoredPunctuationTag(String str) {
return eIPunctTagStringAcceptFilter.accept(str);
}
/**
* Return a filter that accepts a String that is a punctuation tag name, and
* rejects everything else.
*
* @return The filter
*/
public Filter punctuationTagAcceptFilter() {
return punctTagStringAcceptFilter;
}
/**
* Return a filter that rejects a String that is a punctuation tag name, and
* rejects everything else.
*
* @return The filter
*/
public Filter punctuationTagRejectFilter() { | package edu.berkeley.nlp.treebank;
/**
* This provides an implementation of parts of the TreebankLanguagePack API to
* reduce the load on fresh implementations. Only the abstract methods below
* need to be implemented to give a reasonable solution for a new language.
*
* @author Christopher Manning
* @version 1.1
*/
public abstract class AbstractTreebankLanguagePack implements
TreebankLanguagePack, Serializable {
/**
* Use this as the default encoding for Readers and Writers of Treebank
* data.
*/
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* Gives a handle to the TreebankLanguagePack
*/
public AbstractTreebankLanguagePack() {
}
/**
* Returns a String array of punctuation tags for this treebank/language.
*
* @return The punctuation tags
*/
public abstract String[] punctuationTags();
/**
* Returns a String array of punctuation words for this treebank/language.
*
* @return The punctuation words
*/
public abstract String[] punctuationWords();
/**
* Returns a String array of sentence final punctuation tags for this
* treebank/language.
*
* @return The sentence final punctuation tags
*/
public abstract String[] sentenceFinalPunctuationTags();
/**
* Returns a String array of punctuation tags that EVALB-style evaluation
* should ignore for this treebank/language. Traditionally, EVALB has
* ignored a subset of the total set of punctuation tags in the English Penn
* Treebank (quotes and period, comma, colon, etc., but not brackets)
*
* @return Whether this is a EVALB-ignored punctuation tag
*/
public String[] evalBIgnoredPunctuationTags() {
return punctuationTags();
}
/**
* Accepts a String that is a punctuation tag name, and rejects everything
* else.
*
* @return Whether this is a punctuation tag
*/
public boolean isPunctuationTag(String str) {
return punctTagStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a punctuation word, and rejects everything else.
* If one can't tell for sure (as for ' in the Penn Treebank), it maks the
* best guess that it can.
*
* @return Whether this is a punctuation word
*/
public boolean isPunctuationWord(String str) {
return punctWordStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a sentence end punctuation tag, and rejects
* everything else.
*
* @return Whether this is a sentence final punctuation tag
*/
public boolean isSentenceFinalPunctuationTag(String str) {
return sFPunctTagStringAcceptFilter.accept(str);
}
/**
* Accepts a String that is a punctuation tag that should be ignored by
* EVALB-style evaluation, and rejects everything else. Traditionally, EVALB
* has ignored a subset of the total set of punctuation tags in the English
* Penn Treebank (quotes and period, comma, colon, etc., but not brackets)
*
* @return Whether this is a EVALB-ignored punctuation tag
*/
public boolean isEvalBIgnoredPunctuationTag(String str) {
return eIPunctTagStringAcceptFilter.accept(str);
}
/**
* Return a filter that accepts a String that is a punctuation tag name, and
* rejects everything else.
*
* @return The filter
*/
public Filter punctuationTagAcceptFilter() {
return punctTagStringAcceptFilter;
}
/**
* Return a filter that rejects a String that is a punctuation tag name, and
* rejects everything else.
*
* @return The filter
*/
public Filter punctuationTagRejectFilter() { | return Filters.notFilter(punctTagStringAcceptFilter); | 1 | 2023-10-22 13:13:22+00:00 | 4k |
UZ9/cs-1331-drivers | src/com/cs1331/drivers/testing/TestContainer.java | [
{
"identifier": "TestFailedException",
"path": "src/com/cs1331/drivers/exception/TestFailedException.java",
"snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "AsciiColorCode",
"path": "src/com/cs1331/drivers/utils/AsciiColorCode.java",
"snippet": "public final class AsciiColorCode {\n\n public static final String RESET_COLOR = \"\\033[0m\";\n\n public static final String BLACK_FOREGROUND = \"\\033[30m\";\n public static final String BLACK_BACKGROUND = \"\\033[40m\";\n\n public static final String RED_FOREGROUND = \"\\033[31m\";\n public static final String RED_BACKGROUND = \"\\033[41m\";\n\n public static final String GREEN_FOREGROUND = \"\\033[32m\";\n public static final String GREEN_BACKGROUND = \"\\033[42m\";\n\n public static final String YELLOW_FOREGROUND = \"\\033[33m\";\n public static final String YELLOW_BACKGROUND = \"\\033[43m\";\n\n public static final String BLUE_FOREGROUND = \"\\033[34m\";\n public static final String BLUE_BACKGROUND = \"\\033[44m\";\n\n public static final String MAGENTA_FOREGROUND = \"\\033[35m\";\n public static final String MAGENTA_BACKGROUND = \"\\033[45m\";\n\n public static final String CYAN_FOREGROUND = \"\\033[36m\";\n public static final String CYAN_BACKGROUND = \"\\033[46m\";\n\n public static final String WHITE_FOREGROUND = \"\\033[37m\";\n public static final String WHITE_BACKGROUND = \"\\033[47m\";\n\n public static final String BRIGHT_BLACK_FOREGROUND = \"\\033[90m\";\n public static final String BRIGHT_BLACK_BACKGROUND = \"\\033[100m\";\n\n public static final String BRIGHT_RED_FOREGROUND = \"\\033[91m\";\n public static final String BRIGHT_RED_BACKGROUND = \"\\033[101m\";\n\n public static final String BRIGHT_GREEN_FOREGROUND = \"\\033[92m\";\n public static final String BRIGHT_GREEN_BACKGROUND = \"\\033[102m\";\n\n public static final String BRIGHT_YELLOW_FOREGROUND = \"\\033[93m\";\n public static final String BRIGHT_YELLOW_BACKGROUND = \"\\033[103m\";\n\n public static final String BRIGHT_BLUE_FOREGROUND = \"\\033[94m\";\n public static final String BRIGHT_BLUE_BACKGROUND = \"\\033[104m\";\n\n public static final String BRIGHT_MAGENTA_FOREGROUND = \"\\033[95m\";\n public static final String BRIGHT_MAGENTA_BACKGROUND = \"\\033[105m\";\n\n public static final String BRIGHT_CYAN_FOREGROUND = \"\\033[96m\";\n public static final String BRIGHT_CYAN_BACKGROUND = \"\\033[106m\";\n\n public static final String BRIGHT_WHITE_FOREGROUND = \"\\033[97m\";\n public static final String BRIGHT_WHITE_BACKGROUND = \"\\033[107m\";\n}"
},
{
"identifier": "ColorUtils",
"path": "src/com/cs1331/drivers/utils/ColorUtils.java",
"snippet": "public class ColorUtils {\n /**\n * Formats a string to have an ASCII background in terminal.\n * \n * @param background The ASCII representation of the background color, pulled\n * from AsciiColorCode\n * @param s The string to color\n * @return The colored string\n */\n public static String formatBackgroundColorString(String background, String s) {\n return background + s + AsciiColorCode.RESET_COLOR;\n }\n\n /**\n * Formats a string to have an ASCII foreground (text color) in terminal.\n * \n * @param foreground The ASCII representation of the foreground color, pulled\n * from AsciiColorCode\n * @param s The string to color\n * @return The colored string\n */\n public static String formatForegroundColorString(String foreground, String s) {\n return foreground + s + AsciiColorCode.RESET_COLOR;\n\n }\n\n /**\n * Formats a string to have both an ASCII foreground and background in terminal\n * \n * @param background The ASCII representation of the background color, pulled\n * from AsciiColorCode\n * @param foreground The ASCII representation of the foreground color, pulled\n * from AsciiColorCode\n * @param s The string to color\n * @return The colored string\n */\n public static String formatColorString(String background, String foreground, String s) {\n return foreground + background + s.replace(\"\\n\", AsciiColorCode.RESET_COLOR + \"\\n\" + foreground + background) + AsciiColorCode.RESET_COLOR;\n }\n}"
},
{
"identifier": "StringUtils",
"path": "src/com/cs1331/drivers/utils/StringUtils.java",
"snippet": "public class StringUtils {\n /**\n * The ASCII character to use for horizontal lines\n */\n public static final String HORIZONTAL_LINE_CHARACTER = \"\\u2500\";\n\n /**\n * The amount of HORIZONTAL_LINE_CHARACTER elements to use in a line\n */\n public static final int HORIZONTAL_LINE_LENGTH = 64;\n\n /**\n * Prints a horizontal line to the terminal.\n */\n public static void printHorizontalLine() {\n System.out\n .println(String.format(\"%0\" + HORIZONTAL_LINE_LENGTH + \"d\", 0).replace(\"0\", HORIZONTAL_LINE_CHARACTER));\n }\n\n /**\n * Prints centered text to the terminal.\n * \n * @param text The text to be centered\n */\n public static void printTextCentered(String text) {\n // HORIZONTAL_LINE_LENGTH is maximum width\n // if line is\n // xxxxxxxxxxxx\n // We can pad the start of the string with half of the horizontal:\n // xxxxxhelloxx\n // The problem is that this doesn't account for the length of the string.\n // We can add half of the string length as well to correct it:\n // xxxxhelloxxxx = CENTERED! (or at least as close as it can get)\n\n System.out.printf(\"%\" + (HORIZONTAL_LINE_LENGTH / 2 + text.length() / 2) + \"s%n\", text);\n }\n\n /**\n * Utility for converting a Throwable to a stack trace string.\n * \n * @param e Exception to print the stacktrace of\n * @return The formatted stack trace\n */\n public static String stackTraceToString(Throwable e) {\n StackTraceElement[] stackTrace = e.getStackTrace();\n\n if (stackTrace.length == 0) {\n return \"No stack trace.\";\n }\n\n StringBuilder sb = new StringBuilder(stackTrace[0].toString());\n for (int i = 1; i < stackTrace.length; i++) {\n sb.append(\"\\n\\t\");\n sb.append(stackTrace[i].toString());\n }\n return sb.toString();\n }\n\n /**\n * Converts an arraylist into a readable string.\n * @param inputs the input arraylist\n * @return the arraylist as a string\n * @throws TestFailedException if the method was unable to convert the arraylist\n */\n public static String arrayListToString(ArrayList<?> inputs) throws TestFailedException {\n return arrayToString(inputs.toArray(), \",\");\n }\n\n /**\n * Returns the Array as a String using the toString() method of each item.\n * The resulting String has an itemSeparator between each element.\n * @param inputs The Array to convert to String.\n * @param itemSeparator The String to put BETWEEN each item.\n * @return the array as a string\n */\n public static String arrayToString(Object[] inputs, String itemSeparator) throws TestFailedException {\n if (inputs.length == 0) {\n return \"\";\n }\n\n StringBuilder builder = new StringBuilder();\n\n for (Object input : inputs) {\n builder.append(input == null ? \"null\" : input.toString()).append(itemSeparator);\n }\n\n return builder.toString();\n }\n\n public static String arrayToString(Object[] inputs) throws TestFailedException {\n return arrayToString(inputs, \",\");\n }\n\n /**\n * Reads the contents of a file and converts it into a string,\n * using \\n as the delimiter.\n * @param path the path to the file\n * @return the file's contents as a string\n * @throws FileNotFoundException if the file cannot be found\n */\n public static String fileToString(String path) throws FileNotFoundException {\n Scanner scanner = new Scanner(new File(path));\n\n StringBuilder output = new StringBuilder();\n\n while (scanner.hasNextLine()) {\n String next = scanner.nextLine();\n\n output.append(next).append(\"\\n\");\n }\n\n scanner.close();\n\n return output.toString();\n }\n\n /**\n * Prints the given String to the file at the path.\n * THIS METHOD WILL OVERWRITE ANY DATA.\n * \n * @param path Path to write at.\n * @param data Data to write to the file.\n * @throws FileNotFoundException if the file cannot be found\n */\n public static void stringToFile(String path, String data) throws FileNotFoundException {\n\n PrintWriter writer = new PrintWriter(path);\n\n writer.write(data);\n\n writer.close();\n\n }\n\n /**\n * Returns a modified version of 'actual', where the first character that\n * differs from 'expected' is highlighted RED.\n * \n * @param actual The 'actual' String\n * @param expected The 'expected' String to compare against\n * @return The string showing the color coded difference.\n */\n public static String getColorCodedDifference(String actual, String expected) {\n StringBuilder colored = new StringBuilder();\n for (int i = 0; i < actual.length(); i++) {\n char actualChar = actual.charAt(i);\n\n if (expected.length() <= i) {\n colored.append(actual.substring(i));\n break;\n }\n\n if (actualChar == expected.charAt(i)) {\n colored.append(actual.charAt(i));\n } else {\n colored.append(ColorUtils.formatColorString(AsciiColorCode.RED_BACKGROUND,\n AsciiColorCode.WHITE_FOREGROUND, actualChar + \"\"));\n colored.append(actual.substring(i + 1));\n break;\n }\n\n }\n\n return colored.toString();\n\n }\n\n public static String formatIndented(String s) {\n\n String[] split = s.split(\"\\n\");\n\n StringBuilder output = new StringBuilder();\n\n for (int i = 0; i < split.length - 1; i++) {\n output.append(formatSingleLine(split[i])).append(\"\\n\");\n }\n\n output.append(formatSingleLine(split[split.length - 1]));\n\n return output + \"\\n\";\n }\n\n private static String formatSingleLine(String s) {\n int currentLength = 0;\n\n StringBuilder builder = new StringBuilder(\"\\t\" + s);\n\n while (currentLength + HORIZONTAL_LINE_LENGTH < builder.length()\n && (currentLength = builder.indexOf(\" \", currentLength + HORIZONTAL_LINE_LENGTH)) != -1) {\n \n builder.replace(currentLength, currentLength + 1, \"\\n\\t\");\n }\n\n return builder.toString();\n }\n}"
},
{
"identifier": "Tuple",
"path": "src/com/cs1331/drivers/utils/Tuple.java",
"snippet": "public class Tuple<X, Y> {\n /**\n * The first element\n */\n public final X first;\n\n /**\n * The second element\n */\n public final Y second;\n\n /**\n * Constructs a new Tuple.\n * @param first The first element\n * @param second The second element\n */\n public Tuple(X first, Y second) {\n this.first = first;\n this.second = second;\n }\n}"
}
] | import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import com.cs1331.drivers.annotations.AfterTest;
import com.cs1331.drivers.annotations.BeforeTest;
import com.cs1331.drivers.annotations.TestCase;
import com.cs1331.drivers.annotations.Tip;
import com.cs1331.drivers.exception.TestFailedException;
import com.cs1331.drivers.utils.AsciiColorCode;
import com.cs1331.drivers.utils.ColorUtils;
import com.cs1331.drivers.utils.StringUtils;
import com.cs1331.drivers.utils.Tuple;
import java.util.ArrayList; | 3,202 | package com.cs1331.drivers.testing;
/**
* Represents a Runnable that can be thrown into a ThreadPoolExecutor. The
* TestContainer will latch onto a Class<?> and attempt to run any methods
* labeled as test functions, e.g. @TestCase or @BeforeTest
*/
public class TestContainer implements Runnable {
/**
* The class belonging to the TestContainer
*/
private Class<?> clazz;
/**
* As the methods are non-static, there must be an instance all share when
* executing the methods. At the start of the test a single instance is
* initialized for all tests to use.
*/
private Object instance = null;
/**
* Initializes a new TestContainer. A TestContainer is used to prevent certain
* edge cases such as infinite loops.
*
* If an infinite loop occurs, the test will timeout and notify the user
* accordingly.
*
* @param clazz The class containing the tests
*/
public TestContainer(Class<?> clazz) {
this.clazz = clazz;
}
/**
* Executes a method belonging to this instance.
* This is used when cycling over the methods marked with @BeforeTest
* and @AfterTest, as both require the same invocation logic.
*
* @param method The method to execute
*/
private void executeFunction(Method method) {
try {
method.invoke(instance);
} catch (Exception e) { | package com.cs1331.drivers.testing;
/**
* Represents a Runnable that can be thrown into a ThreadPoolExecutor. The
* TestContainer will latch onto a Class<?> and attempt to run any methods
* labeled as test functions, e.g. @TestCase or @BeforeTest
*/
public class TestContainer implements Runnable {
/**
* The class belonging to the TestContainer
*/
private Class<?> clazz;
/**
* As the methods are non-static, there must be an instance all share when
* executing the methods. At the start of the test a single instance is
* initialized for all tests to use.
*/
private Object instance = null;
/**
* Initializes a new TestContainer. A TestContainer is used to prevent certain
* edge cases such as infinite loops.
*
* If an infinite loop occurs, the test will timeout and notify the user
* accordingly.
*
* @param clazz The class containing the tests
*/
public TestContainer(Class<?> clazz) {
this.clazz = clazz;
}
/**
* Executes a method belonging to this instance.
* This is used when cycling over the methods marked with @BeforeTest
* and @AfterTest, as both require the same invocation logic.
*
* @param method The method to execute
*/
private void executeFunction(Method method) {
try {
method.invoke(instance);
} catch (Exception e) { | System.out.println(ColorUtils.formatColorString(AsciiColorCode.WHITE_BACKGROUND, | 1 | 2023-10-20 03:06:59+00:00 | 4k |
AkramLZ/ServerSync | serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServersManager.java | [
{
"identifier": "Server",
"path": "serversync-common/src/main/java/me/akraml/serversync/server/Server.java",
"snippet": "public interface Server {\n\n /**\n * Retrieves the name of the current synchronized server.\n *\n * @return {@link Server}'s current name.\n */\n String getName();\n\n /**\n * Retrieves the IP address of the current synchronized server.\n *\n * @return The IP address of the server.\n */\n String getIp();\n\n /**\n * Retrieves the port number on which the server is running.\n *\n * @return The port number of the server.\n */\n int getPort();\n\n /**\n * Retrieves a collection of the players currently online on this server.\n *\n * @return A collection of {@link SyncPlayer} representing the players online.\n */\n Collection<SyncPlayer> getOnlinePlayers();\n\n /**\n * Checks if the current server cache contains a player with the provided UUID.\n *\n * @param uuid UUID of the player to check.\n * @return If player is cached in the server.\n */\n boolean containsPlayer(final UUID uuid);\n\n /**\n * Retrieves a {@link SyncPlayer} instance by the provided UUID if present.\n *\n * @param uuid UUID of the player to retrieve.\n * @return A cached {@link SyncPlayer} instance, null if there's no instance with such UUID.\n */\n SyncPlayer getPlayer(final UUID uuid);\n\n /**\n * Retrieves the maximum number of players allowed on this server.\n *\n * @return An integer representing the maximum number of players.\n */\n int getMaxPlayers();\n\n /**\n * Updates the maximum number of players allowed on this server.\n *\n * @param maxPlayers The new integer to represent the maximum number of players.\n */\n void setMaxPlayers(final int maxPlayers);\n\n /**\n * Gets the timestamp of the last heartbeat received from this server.\n * This can be used to check the status or health of the server.\n *\n * @return A long representing the timestamp of the last heartbeat in milliseconds.\n */\n long getLastHeartbeat();\n\n /**\n * Computes the time elapsed since the last heartbeat received from this server.\n *\n * @return A long representing the time elapsed since the last heartbeat in milliseconds.\n */\n default long getSinceLastHeartbeat() {\n return System.currentTimeMillis() - getLastHeartbeat();\n }\n\n /**\n * Initializes a new instance of {@link ServerImpl} from the provided name, ip and port.\n *\n * @param name Name of the registered server.\n * @param ip IP Address of the server.\n * @param port Port of the server which will be accessed from.\n * @return New instance of {@link ServerImpl}\n */\n static Server of(final String name,\n final String ip,\n final int port) {\n return new ServerImpl(name, ip, port);\n }\n\n}"
},
{
"identifier": "ServersManager",
"path": "serversync-common/src/main/java/me/akraml/serversync/server/ServersManager.java",
"snippet": "public abstract class ServersManager {\n\n /** Timer to schedule and manage the heartbeat task. */\n private final Timer timer = new Timer();\n\n /** Map storing the servers using their names as the key. */\n private final Map<String, ServerImpl> servers = new HashMap<>();\n\n /** Integers for heartbeat task delay and maximum time to remove the server. */\n protected int heartbeatSchedulerDelay, maxAliveTime;\n\n /**\n * Starts a recurring task to check servers for their heartbeat signal.\n * Servers that haven't sent a heartbeat signal within the last 30 seconds will be removed.\n */\n public final void startHeartbeatTask() {\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n final List<ServerImpl> toRemove = new ArrayList<>();\n servers.values().forEach(server -> {\n if (System.currentTimeMillis() - server.getLastHeartbeat() > maxAliveTime) {\n toRemove.add(server);\n }\n });\n toRemove.forEach(ServersManager.this::removeServer);\n toRemove.clear();\n }\n }, 0L, Duration.ofSeconds(heartbeatSchedulerDelay).toMillis());\n }\n\n /**\n * Retrieves a server instance by its name.\n *\n * @param name The name of the server.\n * @return The server instance or null if not found.\n */\n public final Server getServer(String name) {\n return this.servers.get(name);\n }\n\n /**\n * Adds a server to the managed collection of servers.\n *\n * @param server The server to be added.\n */\n public final void addServer(Server server) {\n this.servers.put(server.getName(), (ServerImpl) server);\n registerInProxy(server);\n }\n\n /**\n * Removes a server from the managed collection of servers.\n * Also, triggers an unregister action specific to the proxy.\n *\n * @param server The server to be removed.\n */\n public final void removeServer(Server server) {\n unregisterFromProxy(server);\n this.servers.remove(server.getName());\n }\n\n /**\n * Abstract method that should be implemented to unregister a server from the associated proxy.\n *\n * @param server The server to be unregistered from the proxy.\n */\n protected abstract void unregisterFromProxy(Server server);\n\n /**\n * Abstract method that should be implemented to register a server in the proxy server.\n *\n * @param server The server to be registered in the proxy.\n */\n protected abstract void registerInProxy(Server server);\n}"
}
] | import me.akraml.serversync.server.Server;
import me.akraml.serversync.server.ServersManager;
import net.md_5.bungee.api.config.ServerInfo;
import java.net.InetSocketAddress; | 1,849 | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* Implementation of the {@link ServersManager} for a BungeeCord proxy environment.
* This manager handles the registration and un-registration of server instances specifically
* for BungeeCord.
*/
public final class BungeeServersManager extends ServersManager {
private final BungeeServerSyncPlugin plugin;
public BungeeServersManager(final BungeeServerSyncPlugin plugin) {
this.plugin = plugin;
this.heartbeatSchedulerDelay = plugin.getConfig().getInt("heartbeat-scheduler-delay");
this.maxAliveTime = plugin.getConfig().getInt("max-alive-time");
}
/**
* Unregisters a server from the BungeeCord proxy. This removes the server from the list of
* servers known to the proxy, effectively making it inaccessible to players through the proxy.
*
* @param server The server to unregister from the proxy.
*/
@Override | /*
* MIT License
*
* Copyright (c) 2023 Akram Louze
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.akraml.serversync.bungee;
/**
* Implementation of the {@link ServersManager} for a BungeeCord proxy environment.
* This manager handles the registration and un-registration of server instances specifically
* for BungeeCord.
*/
public final class BungeeServersManager extends ServersManager {
private final BungeeServerSyncPlugin plugin;
public BungeeServersManager(final BungeeServerSyncPlugin plugin) {
this.plugin = plugin;
this.heartbeatSchedulerDelay = plugin.getConfig().getInt("heartbeat-scheduler-delay");
this.maxAliveTime = plugin.getConfig().getInt("max-alive-time");
}
/**
* Unregisters a server from the BungeeCord proxy. This removes the server from the list of
* servers known to the proxy, effectively making it inaccessible to players through the proxy.
*
* @param server The server to unregister from the proxy.
*/
@Override | protected void unregisterFromProxy(Server server) { | 0 | 2023-10-21 12:47:58+00:00 | 4k |
neftalito/R-Info-Plus | arbol/sentencia/Asignacion.java | [
{
"identifier": "Programa",
"path": "arbol/Programa.java",
"snippet": "public class Programa extends AST {\n Identificador I;\n DeclaracionRobots DR;\n DeclaracionProcesos DP;\n DeclaracionVariable DV;\n DeclaracionAreas DA;\n Cuerpo C;\n Robot R;\n Ciudad city;\n CodePanel codigo;\n\n public Programa(final Identificador I, final DeclaracionProcesos DP, final DeclaracionVariable DV,\n final DeclaracionRobots DR, final Ciudad city, final Cuerpo C, final DeclaracionAreas DA) {\n this.DP = null;\n this.setI(I);\n this.setC(C);\n if (DP != null) {\n this.setDP(DP);\n }\n if (DV != null) {\n this.setDV(DV);\n }\n this.setDR(DR);\n this.setDA(DA);\n this.city = city;\n }\n\n public DeclaracionAreas getDA() {\n return this.DA;\n }\n\n public void setDA(final DeclaracionAreas DA) {\n this.DA = DA;\n }\n\n public Cuerpo getC() {\n return this.C;\n }\n\n public DeclaracionProcesos getDP() {\n return this.DP;\n }\n\n public DeclaracionVariable getDV() {\n return this.DV;\n }\n\n public DeclaracionRobots getDR() {\n return this.DR;\n }\n\n public void setDR(final DeclaracionRobots DR) {\n this.DR = DR;\n }\n\n public Identificador getI() {\n return this.I;\n }\n\n public Robot getRobot() {\n return this.R;\n }\n\n public void setI(final Identificador I) {\n this.I = I;\n }\n\n public void setC(final Cuerpo C) {\n (this.C = C).setPrograma(this);\n }\n\n public void setDP(final DeclaracionProcesos DP) {\n this.DP = DP;\n }\n\n public void setDV(final DeclaracionVariable DV) {\n this.DV = DV;\n }\n\n public void setRobot(final Robot R) {\n this.R = R;\n }\n\n public Ciudad getCity() {\n return this.city;\n }\n\n public void setCity(final Ciudad c) {\n this.city = c;\n }\n\n public CodePanel getCodigo() {\n return this.codigo;\n }\n\n public void setCodigo(final CodePanel codigo) {\n this.codigo = codigo;\n }\n\n public void ejecutar() throws Exception {\n this.getC().ejecutar();\n }\n}"
},
{
"identifier": "Variable",
"path": "arbol/Variable.java",
"snippet": "public class Variable extends Expresion {\n private String value;\n private boolean editable;\n Robot rob;\n RobotAST r;\n private String nombreTipoRobot;\n DeclaracionRobots dr;\n\n public Variable(final Identificador I, final Tipo T, final DeclaracionVariable var, final DeclaracionRobots robAST,\n final String nombreTipoRobot) throws Exception {\n synchronized (this) {\n this.dr = robAST;\n this.DV = var;\n this.setI(I);\n this.value = \"Undefined\";\n if (T == null) {\n if (var.EstaVariable(I.toString())) {\n final Variable tmp = var.findByName(I.toString());\n this.setT(tmp.getT());\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n }\n } else {\n this.setT(T);\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n if (this.getT().tipo == 66) {\n this.r = robAST.getRobot(nombreTipoRobot);\n }\n }\n }\n }\n\n public RobotAST getR() {\n return this.r;\n }\n\n @Override\n public String getValue(final DeclaracionVariable var) throws Exception {\n String res = \"undefineD\";\n if (var.EstaParametro(this.I.toString())) {\n final Variable tmp = var.findByName(this.I.toString());\n res = tmp.getValor();\n return res;\n }\n this.reportError(\"Variable \" + this.getI().toString() + \" no declarada\");\n throw new Exception(\"Variable \" + this.getI().toString() + \" no declarada\");\n }\n\n public String getValor() {\n return this.value;\n }\n\n public void setValue(final String str) {\n this.value = str;\n }\n\n public boolean esEditable() {\n return this.editable;\n }\n\n public void setEditable(final boolean bool) {\n this.editable = bool;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public boolean isCompatible(final Variable tmp) {\n switch (tmp.getT().getTipo()) {\n case 19:\n case 23: {\n return this.getT().getTipo() == 23 || this.getT().getTipo() == 19;\n }\n case 20:\n case 32:\n case 33: {\n return this.getT().getTipo() == 20 || this.getT().getTipo() == 32 || this.getT().getTipo() == 33;\n }\n default: {\n return false;\n }\n }\n }\n\n public void setTipoRobot(final String nombreTipoRobot) {\n this.nombreTipoRobot = nombreTipoRobot;\n }\n\n public String getTipoRobot() {\n return this.nombreTipoRobot;\n }\n\n @Override\n public Object clone() {\n synchronized (this) {\n Variable obj = null;\n try {\n obj = new Variable(this.I, this.T, this.DV, this.dr, null);\n obj.setValue(this.getValor());\n } catch (Exception ex) {\n System.out.println(\"error en el clone de Variable!\");\n Logger.getLogger(Variable.class.getName()).log(Level.SEVERE, null, ex);\n }\n return obj;\n }\n }\n}"
},
{
"identifier": "DeclaracionVariable",
"path": "arbol/DeclaracionVariable.java",
"snippet": "public class DeclaracionVariable extends AST {\n public ArrayList<Variable> variables;\n\n public DeclaracionVariable(final ArrayList<Variable> var) {\n this.variables = var;\n }\n\n public void imprimir() {\n for (final Variable variable : this.variables) {\n System.out.println(variable.getI().toString());\n }\n }\n\n public boolean EstaParametro(final String act) throws Exception {\n int i;\n for (i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n if (i == this.variables.size()) {\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n return false;\n }\n\n public boolean EstaVariable(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public Variable findByName(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().toString().equals(act)) {\n return this.variables.get(i);\n }\n }\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n}"
},
{
"identifier": "Expresion",
"path": "arbol/expresion/Expresion.java",
"snippet": "public abstract class Expresion extends AST {\n public DeclaracionVariable DV;\n public Tipo T;\n public Identificador I;\n public Robot r;\n\n public DeclaracionVariable getDV() {\n return this.DV;\n }\n\n public void setDV(final DeclaracionVariable DV) {\n this.DV = DV;\n }\n\n public Identificador getI() {\n return this.I;\n }\n\n public void setI(final Identificador I) {\n this.I = I;\n }\n\n public boolean ejecutar() {\n return true;\n }\n\n public String getValue(final DeclaracionVariable DV) throws Exception {\n return \"undefinedd\";\n }\n\n public Tipo getT() {\n return this.T;\n }\n\n public void setT(final Tipo T) {\n this.T = T;\n }\n\n public Robot getRobot() {\n return this.r;\n }\n\n public void setRobot(final Robot r) {\n this.r = r;\n }\n\n @Override\n public abstract Object clone() throws CloneNotSupportedException;\n}"
},
{
"identifier": "Identificador",
"path": "arbol/Identificador.java",
"snippet": "public class Identificador extends AST {\n String spelling;\n\n public Identificador(final String spelling) {\n this.spelling = spelling;\n }\n\n public boolean equals(final String str) {\n return this.spelling.equals(str);\n }\n\n @Override\n public String toString() {\n return this.spelling;\n }\n}"
}
] | import arbol.Programa;
import arbol.Variable;
import arbol.DeclaracionVariable;
import arbol.expresion.Expresion;
import arbol.Identificador; | 2,988 |
package arbol.sentencia;
public class Asignacion extends Sentencia {
Identificador I;
Expresion E;
DeclaracionVariable DV;
public Asignacion(final Identificador I, final Expresion E, final DeclaracionVariable DV) {
this.I = I;
this.E = E;
this.DV = DV;
}
@Override
public void ejecutar() throws Exception {
synchronized (this) {
this.E.setRobot(this.getRobot());
if (!this.DV.EstaParametro(this.I.toString())) {
this.programa.getCity().parseError("Variable: " + this.I.toString() + "no encontrada");
throw new Exception("Variable: " + this.I.toString() + "no encontrada");
}
final Variable tmp = this.DV.findByName(this.I.toString());
final String eValue = this.E.getValue(this.DV);
if (tmp.getT().toString().equals("boolean") && !eValue.equals("V") && !eValue.equals("F")) {
this.programa.getCity().parseError(
"Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString());
throw new Exception(
"Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString());
}
if (tmp.getT().toString().equals("numero")) {
try {
System.out.println("e value vale: " + eValue);
Integer.parseInt(eValue);
} catch (Exception ex) {
this.programa.getCity().parseError(
"Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString());
throw new Exception(
"Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString());
}
}
this.DV.findByName(this.I.toString()).setValue(eValue);
}
}
@Override
public Object clone() throws CloneNotSupportedException {
final Object obj = null;
final Identificador II = new Identificador(this.I.toString());
System.out.println("Intentando clonar expresion en asignacion");
final Expresion EE = (Expresion) this.E.clone();
return new Asignacion(II, EE, this.DV);
}
@Override
public void setDV(final DeclaracionVariable varAST) {
this.DV = varAST;
}
@Override |
package arbol.sentencia;
public class Asignacion extends Sentencia {
Identificador I;
Expresion E;
DeclaracionVariable DV;
public Asignacion(final Identificador I, final Expresion E, final DeclaracionVariable DV) {
this.I = I;
this.E = E;
this.DV = DV;
}
@Override
public void ejecutar() throws Exception {
synchronized (this) {
this.E.setRobot(this.getRobot());
if (!this.DV.EstaParametro(this.I.toString())) {
this.programa.getCity().parseError("Variable: " + this.I.toString() + "no encontrada");
throw new Exception("Variable: " + this.I.toString() + "no encontrada");
}
final Variable tmp = this.DV.findByName(this.I.toString());
final String eValue = this.E.getValue(this.DV);
if (tmp.getT().toString().equals("boolean") && !eValue.equals("V") && !eValue.equals("F")) {
this.programa.getCity().parseError(
"Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString());
throw new Exception(
"Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString());
}
if (tmp.getT().toString().equals("numero")) {
try {
System.out.println("e value vale: " + eValue);
Integer.parseInt(eValue);
} catch (Exception ex) {
this.programa.getCity().parseError(
"Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString());
throw new Exception(
"Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString());
}
}
this.DV.findByName(this.I.toString()).setValue(eValue);
}
}
@Override
public Object clone() throws CloneNotSupportedException {
final Object obj = null;
final Identificador II = new Identificador(this.I.toString());
System.out.println("Intentando clonar expresion en asignacion");
final Expresion EE = (Expresion) this.E.clone();
return new Asignacion(II, EE, this.DV);
}
@Override
public void setDV(final DeclaracionVariable varAST) {
this.DV = varAST;
}
@Override | public void setPrograma(final Programa P) { | 0 | 2023-10-20 15:45:37+00:00 | 4k |
wevez/ClientCoderPack | src/tech/tenamen/client/Client.java | [
{
"identifier": "Main",
"path": "src/tech/tenamen/Main.java",
"snippet": "public class Main {\n public static IDE IDE = new InteliJIDE();\n public static Client client;\n\n public static File WORKING_DIR = new File(System.getProperty(\"user.dir\")),\n ASSETS_DIR = new File(WORKING_DIR, \"assets\"),\n LIBRARIES_DIR = new File(WORKING_DIR, \"libraries\"),\n OBJECTS_DIR = new File(ASSETS_DIR, \"objects\"),\n INDEXES_DIR = new File(ASSETS_DIR, \"indexes\"),\n SRC_DIR = new File(WORKING_DIR, \"src\"),\n NATIVES_DIR = new File(LIBRARIES_DIR, \"natives\");\n\n public static void main(String[] main) throws Exception {\n final Scanner scanner = new Scanner(System.in);\n System.out.println(\"ClientCoderPack\");\n System.out.print(\"Version<<\");\n final File versionFile = new File(String.format(\"%s\\\\.minecraft\\\\versions\\\\%s\", System.getenv(\"APPDATA\"), scanner.next()));\n if (!versionFile.exists()) {\n System.out.printf(\"File %s not found%n\", versionFile.getAbsolutePath());\n return;\n }\n ASSETS_DIR.mkdirs();\n LIBRARIES_DIR.mkdirs();\n OBJECTS_DIR.mkdirs();\n INDEXES_DIR.mkdirs();\n SRC_DIR.mkdirs();\n NATIVES_DIR.mkdirs();\n client = new Client(versionFile);\n System.out.println(\"Downloading dependencies\");\n client.parseDependencies();\n client.download(getOs());\n System.out.println(\"Making IDE property file\");\n IDE.createProperties();\n System.out.println(\"Process has finished!\");\n\n }\n\n private static OS getOs() {\n final String OS_NAME = System.getProperty(\"os.name\").toLowerCase();\n if (OS_NAME.startsWith(\"linux\")) return OS.LINUX;\n if (OS_NAME.startsWith(\"mac\")) return OS.MAC;\n return OS.WINDOWS;\n }\n\n}"
},
{
"identifier": "OS",
"path": "src/tech/tenamen/property/OS.java",
"snippet": "public enum OS {\n\n WINDOWS(\"windows\", \"natives-windows\"),\n MAC(\"osx\", \"natives-macos\"),\n LINUX(\"linux\", \"natives-linux\");\n\n private final String OS_RULE_NAME, NATIVE_OS_NAME;\n\n OS(final String OS_RULE_NAME, final String NATIVE_OS_NAME) {\n this.OS_RULE_NAME = OS_RULE_NAME;\n this.NATIVE_OS_NAME = NATIVE_OS_NAME;\n }\n\n public String toOsRule() { return OS_RULE_NAME; }\n public String toNativeOs() { return NATIVE_OS_NAME; }\n}"
},
{
"identifier": "NetUtil",
"path": "src/tech/tenamen/util/NetUtil.java",
"snippet": "public class NetUtil {\n\n public static boolean checkExist(final File file, final long size) {\n return file.length() == size;\n }\n\n public static void download(final String urly, final File file) {\n System.out.printf(\"Downloading %s -> %s\\n\", urly, file.getAbsolutePath());\n try {\n URL url = new URL(urly);\n final HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setAllowUserInteraction(false);\n conn.setInstanceFollowRedirects(true);\n conn.setRequestMethod(\"GET\");\n conn.connect();\n int httpStatusCode = conn.getResponseCode();\n if (httpStatusCode != HttpURLConnection.HTTP_OK) {\n throw new Exception(\"HTTP Status \" + httpStatusCode);\n }\n final DataInputStream dataInStream = new DataInputStream(conn.getInputStream());\n final DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(file.toPath())));\n final byte[] b = new byte[4096];\n int readByte = 0;\n while (-1 != (readByte = dataInStream.read(b))) {\n dataOutStream.write(b, 0, readByte);\n }\n dataInStream.close();\n dataOutStream.close();\n } catch (final Exception e) {\n e.printStackTrace();\n }\n }\n\n public static String download(final String urly) {\n final StringBuilder buffer = new StringBuilder();\n URL url;\n try {\n url = new URL(urly);\n final HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n final InputStreamReader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);\n final BufferedReader in = new BufferedReader(reader);\n String line = null;\n while ((line = in.readLine()) != null) {\n buffer.append(line);\n buffer.append('\\n');\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return buffer.toString();\n }\n\n public static String clip(String target, String first, String last) {\n final int startIndex = target.indexOf(first) + first.length();\n return target.substring(startIndex, target.indexOf(last, startIndex));\n }\n\n public static String clip(String target, String first, int last) {\n final int startIndex = target.indexOf(first) + first.length();\n return target.substring(startIndex, last);\n }\n\n}"
}
] | import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import tech.tenamen.Main;
import tech.tenamen.property.OS;
import tech.tenamen.util.NetUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.*; | 3,087 | final JsonObject assetIndex = object.getAsJsonObject("assetIndex");
String assetId = null, assetSha1 = null, assetUrl = null;
long assetSize = -1, assetTutorialSize = -1;
if (assetIndex.has("id")) assetId = assetIndex.get("id").getAsString();
if (assetIndex.has("sha1")) assetSha1 = assetIndex.get("sha1").getAsString();
if (assetIndex.has("url")) assetUrl = assetIndex.get("url").getAsString();
if (assetIndex.has("size")) assetSize = assetIndex.get("size").getAsLong();
if (assetIndex.has("totalSize")) assetTutorialSize = assetIndex.get("totalSize").getAsLong();
if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) {
asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl);
}
}
// downloads
if (object.has("downloads")) {
final JsonObject downloads = object.getAsJsonObject("downloads");
if (downloads.has("client")) {
final JsonObject client = downloads.getAsJsonObject("client");
new Thread(() -> {
NetUtil.download(client.get("url").getAsString(), new File(Main.LIBRARIES_DIR, "client.jar"));
}).start();
Main.IDE.getLibraryNames().add("client.jar");
}
if (downloads.has("client_mappings")) {
final JsonObject clientMappings = downloads.getAsJsonObject("client_mappings");
}
if (downloads.has("server")) {
final JsonObject server = downloads.getAsJsonObject("server");
}
if (downloads.has("server_mappings")) {
final JsonObject serverMappings = downloads.getAsJsonObject("server_mappings");
}
}
// java version
if (object.has("javaVersion")) {
final JsonObject javaVersion = object.getAsJsonObject("javaVersion");
// if (javaVersion.has("component"))
if (javaVersion.has("majorVersion")) this.javaMajorVersion = javaVersion.get("majorVersion").getAsInt();
}
if (object.has("libraries")) {
final JsonArray libraries = object.getAsJsonArray("libraries");
for (JsonElement e : libraries) {
String libName = null, libPath = null, libSha1 = null, libUrl = null;
long libSize = -1;
final OSRule osRule = new OSRule();
final List<NativeLibrary> nativeLibraries = new ArrayList<>();
final JsonObject library = e.getAsJsonObject();
if (library.has("downloads")) {
final JsonObject downloads = library.getAsJsonObject("downloads");
if (downloads.has("artifact")) {
final JsonObject artifact = downloads.getAsJsonObject("artifact");
if (artifact.has("path")) libPath = artifact.get("path").getAsString();
if (artifact.has("sha1")) libSha1 = artifact.get("sha1").getAsString();
if (artifact.has("url")) libUrl = artifact.get("url").getAsString();
if (artifact.has("size")) libSize = artifact.get("size").getAsLong();
}
if (downloads.has("classifiers")) {
final JsonObject classifiers = downloads.getAsJsonObject("classifiers");
final Map<String, JsonObject> nativeObjects = new HashMap<>();
if (classifiers.has("natives-windows")) {
nativeObjects.put("natives-windows", classifiers.getAsJsonObject("natives-windows"));
}
if (classifiers.has("natives-linux")) {
nativeObjects.put("natives-linux", classifiers.getAsJsonObject("natives-linux"));
}
if (classifiers.has("natives-macos")) {
nativeObjects.put("natives-macos", classifiers.getAsJsonObject("natives-macos"));
}
nativeObjects.forEach((k, v) -> {
String nativePath = null, nativeSha1 = null, nativeUrl = null;
long nativeSize = -1;
if (v.has("path")) nativePath = v.get("path").getAsString();
if (v.has("sha1")) nativeSha1 = v.get("sha1").getAsString();
if (v.has("url")) nativeUrl = v.get("url").getAsString();
if (v.has("size")) nativeSize = v.get("size").getAsLong();
if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) {
nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl));
}
});
}
}
if (library.has("name")) {
libName = library.get("name").getAsString();
}
if (library.has("rules")) {
for (JsonElement r : library.getAsJsonArray("rules")) {
// os
final JsonObject rule = r.getAsJsonObject();
if (rule.has("action")) {
final String action = rule.get("action").getAsString();
osRule.setAllow(action.equalsIgnoreCase("allow"));
}
if (rule.has("os")) {
final JsonObject os = rule.getAsJsonObject("os");
if (os.has("name")) osRule.setOSName(os.get("name").getAsString());
}
}
}
if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) {
this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries));
}
}
}
// release time
if (object.has("releaseTime")) {
final String releaseTime = object.get("releaseTime").getAsString();
}
// time
if (object.has("time")) {
final String time = object.get("time").getAsString();
}
// type
if (object.has("type")) {
final String type = object.get("type").getAsString();
}
Main.IDE.getLibraryNames().add("jsr305-3.0.2.jar");
}
public final String getVersionName() { return this.VERSION_NAME; }
@Override | package tech.tenamen.client;
public class Client implements Downloadable {
private String VERSION_NAME;
private File JSON_FILE, JAR_FILE;
private final List<Library> LIBRARIES = new ArrayList<>();
public Asset asset;
private int javaMajorVersion = -1;
public Client(final File folder) throws Exception {
if (!folder.isFile()) {
final List<File> JSON_CANDIDATE = new ArrayList<>(), JAR_CANDIDATE = new ArrayList<>();
// collect json and jar candidates
for (final File f : Objects.requireNonNull(folder.listFiles())) {
if (!f.isFile()) continue;
final String upperFileName = f.getName().toUpperCase();
if (upperFileName.endsWith(".JSON")) {
JSON_CANDIDATE.add(f);
} else if (upperFileName.endsWith(".JAR")) {
JAR_CANDIDATE.add(f);
}
}
for (File jsonCandidate : JSON_CANDIDATE) {
final String jsonFileRawName = jsonCandidate.getName();
final String jsonFileName = jsonFileRawName.substring(0, jsonFileRawName.length() - ".json".length());
for (File jarCandidate : JAR_CANDIDATE) {
final String jarFileRawName = jarCandidate.getName();
final String jarFileName = jarFileRawName.substring(0, jarFileRawName.length() - ".jar".length());
if (jsonFileName.equalsIgnoreCase(jarFileName)) {
this.VERSION_NAME = jsonFileName;
this.JAR_FILE = jarCandidate;
this.JSON_FILE = jsonCandidate;
break;
}
}
if (JSON_FILE != null && JAR_FILE != null && VERSION_NAME != null) break;
}
if (JSON_FILE == null) throw new Exception("The folder doesn't have json");
if (JAR_FILE == null) throw new Exception("The folder doesn't have jar");
if (VERSION_NAME == null) throw new Exception("The name is null");
} else {
throw new Exception("The folder is not folder");
}
}
public void parseDependencies() {
JsonObject object = null;
try {
object = new GsonBuilder().setPrettyPrinting().create().fromJson(new FileReader(this.JSON_FILE), JsonObject.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (object == null) return;
// arguments
if (object.has("arguments")) {
// TODO make launch property from json
final JsonObject arguments = object.getAsJsonObject("arguments");
}
// asset index
if (object.has("assetIndex")) {
final JsonObject assetIndex = object.getAsJsonObject("assetIndex");
String assetId = null, assetSha1 = null, assetUrl = null;
long assetSize = -1, assetTutorialSize = -1;
if (assetIndex.has("id")) assetId = assetIndex.get("id").getAsString();
if (assetIndex.has("sha1")) assetSha1 = assetIndex.get("sha1").getAsString();
if (assetIndex.has("url")) assetUrl = assetIndex.get("url").getAsString();
if (assetIndex.has("size")) assetSize = assetIndex.get("size").getAsLong();
if (assetIndex.has("totalSize")) assetTutorialSize = assetIndex.get("totalSize").getAsLong();
if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) {
asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl);
}
}
// downloads
if (object.has("downloads")) {
final JsonObject downloads = object.getAsJsonObject("downloads");
if (downloads.has("client")) {
final JsonObject client = downloads.getAsJsonObject("client");
new Thread(() -> {
NetUtil.download(client.get("url").getAsString(), new File(Main.LIBRARIES_DIR, "client.jar"));
}).start();
Main.IDE.getLibraryNames().add("client.jar");
}
if (downloads.has("client_mappings")) {
final JsonObject clientMappings = downloads.getAsJsonObject("client_mappings");
}
if (downloads.has("server")) {
final JsonObject server = downloads.getAsJsonObject("server");
}
if (downloads.has("server_mappings")) {
final JsonObject serverMappings = downloads.getAsJsonObject("server_mappings");
}
}
// java version
if (object.has("javaVersion")) {
final JsonObject javaVersion = object.getAsJsonObject("javaVersion");
// if (javaVersion.has("component"))
if (javaVersion.has("majorVersion")) this.javaMajorVersion = javaVersion.get("majorVersion").getAsInt();
}
if (object.has("libraries")) {
final JsonArray libraries = object.getAsJsonArray("libraries");
for (JsonElement e : libraries) {
String libName = null, libPath = null, libSha1 = null, libUrl = null;
long libSize = -1;
final OSRule osRule = new OSRule();
final List<NativeLibrary> nativeLibraries = new ArrayList<>();
final JsonObject library = e.getAsJsonObject();
if (library.has("downloads")) {
final JsonObject downloads = library.getAsJsonObject("downloads");
if (downloads.has("artifact")) {
final JsonObject artifact = downloads.getAsJsonObject("artifact");
if (artifact.has("path")) libPath = artifact.get("path").getAsString();
if (artifact.has("sha1")) libSha1 = artifact.get("sha1").getAsString();
if (artifact.has("url")) libUrl = artifact.get("url").getAsString();
if (artifact.has("size")) libSize = artifact.get("size").getAsLong();
}
if (downloads.has("classifiers")) {
final JsonObject classifiers = downloads.getAsJsonObject("classifiers");
final Map<String, JsonObject> nativeObjects = new HashMap<>();
if (classifiers.has("natives-windows")) {
nativeObjects.put("natives-windows", classifiers.getAsJsonObject("natives-windows"));
}
if (classifiers.has("natives-linux")) {
nativeObjects.put("natives-linux", classifiers.getAsJsonObject("natives-linux"));
}
if (classifiers.has("natives-macos")) {
nativeObjects.put("natives-macos", classifiers.getAsJsonObject("natives-macos"));
}
nativeObjects.forEach((k, v) -> {
String nativePath = null, nativeSha1 = null, nativeUrl = null;
long nativeSize = -1;
if (v.has("path")) nativePath = v.get("path").getAsString();
if (v.has("sha1")) nativeSha1 = v.get("sha1").getAsString();
if (v.has("url")) nativeUrl = v.get("url").getAsString();
if (v.has("size")) nativeSize = v.get("size").getAsLong();
if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) {
nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl));
}
});
}
}
if (library.has("name")) {
libName = library.get("name").getAsString();
}
if (library.has("rules")) {
for (JsonElement r : library.getAsJsonArray("rules")) {
// os
final JsonObject rule = r.getAsJsonObject();
if (rule.has("action")) {
final String action = rule.get("action").getAsString();
osRule.setAllow(action.equalsIgnoreCase("allow"));
}
if (rule.has("os")) {
final JsonObject os = rule.getAsJsonObject("os");
if (os.has("name")) osRule.setOSName(os.get("name").getAsString());
}
}
}
if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) {
this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries));
}
}
}
// release time
if (object.has("releaseTime")) {
final String releaseTime = object.get("releaseTime").getAsString();
}
// time
if (object.has("time")) {
final String time = object.get("time").getAsString();
}
// type
if (object.has("type")) {
final String type = object.get("type").getAsString();
}
Main.IDE.getLibraryNames().add("jsr305-3.0.2.jar");
}
public final String getVersionName() { return this.VERSION_NAME; }
@Override | public void download(OS os) { | 1 | 2023-10-20 06:56:19+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.