MOD:更换为Vertx框架 提高效率

This commit is contained in:
leosam1024
2023-06-15 15:56:41 +08:00
parent 08fe94f020
commit d78c34d18a
21 changed files with 913 additions and 325 deletions
@@ -1,12 +1,12 @@
package com.leosam.tvbox.mv.utils;
import org.springframework.core.io.ClassPathResource;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
/**
* @author admin
@@ -14,19 +14,33 @@ import java.util.Properties;
*/
public class ClassPathReaderUtils {
public static int getSize(String path) {
try {
ClassPathResource resource = new ClassPathResource(path);
InputStream inputStream = resource.getInputStream();
int available = inputStream.available();
return available;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static InputStreamReader getInputStreamReader(String path) {
try {
ClassPathResource resource = new ClassPathResource(path);
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream(),StandardCharsets.UTF_8);
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
return inputStreamReader;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public static BufferedReader getBufferedReader(String path) {
try {
ClassPathResource resource = new ClassPathResource(path);
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream(),StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(inputStreamReader);
return reader;
@@ -35,17 +49,6 @@ public class ClassPathReaderUtils {
}
}
public static Properties getProperties(String path) {
Properties properties = new Properties();
try {
ClassPathResource resource = new ClassPathResource(path);
InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
properties.load(new BufferedReader(inputStreamReader));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return properties;
}
public static String getContent(String path) {
StringBuilder content = new StringBuilder();
@@ -70,5 +73,52 @@ public class ClassPathReaderUtils {
System.out.println(json);
}
public static class ClassPathResource {
private final String path;
private final ClassLoader classLoader;
public ClassPathResource(String path) {
this.path = path;
this.classLoader = getDefaultClassLoader();
}
public InputStream getInputStream() throws IOException {
InputStream is;
if (this.classLoader != null) {
is = this.classLoader.getResourceAsStream(this.path);
} else {
is = ClassLoader.getSystemResourceAsStream(this.path);
}
if (is == null) {
throw new FileNotFoundException(path + " cannot be opened because it does not exist");
}
return is;
}
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassPathResource.class.getClassLoader();
if (cl == null) {
// getClassLoader() returning null indicates the bootstrap ClassLoader
try {
cl = ClassLoader.getSystemClassLoader();
} catch (Throwable ex) {
// Cannot access system ClassLoader - oh well, maybe the caller can live with null...
}
}
}
return cl;
}
}
}
@@ -0,0 +1,15 @@
package com.leosam.tvbox.mv.utils;
import java.util.Collection;
/**
* @author admin
* @since 2023/6/12 21:15
*/
public class CollectionUtils {
public static boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
}
@@ -1,93 +0,0 @@
package com.leosam.tvbox.mv.utils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
/**
*
*/
public class JsonUtils {
private static final Logger LOG = LoggerFactory.getLogger(JsonUtils.class);
private static final TypeReference<HashMap<String, String>> TYPE_MAP =
new TypeReference<HashMap<String, String>>() {
};
public static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.registerModule(new Jdk8Module());
objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
}
public static String writeValue(Object o) {
try {
return writeValueThrowException(o);
} catch (Exception e) {
return "";
}
}
public static String writeValuePrettyPrinter(Object o) {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
} catch (Exception e) {
LOG.error("exception occur when Json serializePretty", e);
return "";
}
}
public static String writeValueThrowException(Object o) throws JsonProcessingException {
try {
return objectMapper.writeValueAsString(o);
} catch (Exception e) {
LOG.error("exception occur when Json serialize", e);
throw e;
}
}
public static <T> T readValue(String json, Class<T> clazz) {
try {
return readValueThrowException(json, clazz);
} catch (IOException e) {
return null;
}
}
public static <T> T readValueThrowException(String json, Class<T> clazz) throws IOException {
try {
return objectMapper.readValue(json, clazz);
} catch (IOException e) {
LOG.warn("Failed to deserialize from JSON string", e);
throw e;
}
}
public static <T> T readValue(String json, TypeReference<T> typeReference) {
try {
return readValueThrowException(json, typeReference);
} catch (IOException e) {
return null;
}
}
public static <T> T readValueThrowException(String json, TypeReference<T> typeReference) throws IOException {
try {
return objectMapper.readValue(json, typeReference);
} catch (IOException e) {
LOG.warn("Failed to deserialize from JSON string", e);
throw e;
}
}
}
@@ -7,7 +7,7 @@ package com.leosam.tvbox.mv.utils;
public class NumberUtils {
public static int toInt(final String str, final int defaultValue) {
if (str == null) {
if (str == null || str.length() == 0) {
return defaultValue;
}
try {
@@ -0,0 +1,392 @@
package com.leosam.tvbox.mv.utils;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Simple stop watch, allowing for timing of a number of tasks, exposing total
* running time and running time for each named task.
*
* <p>Conceals use of {@link System#nanoTime()}, improving the readability of
* application code and reducing the likelihood of calculation errors.
*
* <p>Note that this object is not designed to be thread-safe and does not use
* synchronization.
*
* <p>This class is normally used to verify performance during proof-of-concept
* work and in development, rather than as part of production applications.
*
* <p>As of Spring Framework 5.2, running time is tracked and reported in
* nanoseconds.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @since May 2, 2001
*/
public class StopWatch {
/**
* Identifier of this {@code StopWatch}.
* <p>Handy when we have output from multiple stop watches and need to
* distinguish between them in log or console output.
*/
private final String id;
private boolean keepTaskList = true;
private final List<TaskInfo> taskList = new ArrayList<>(1);
/**
* Start time of the current task.
*/
private long startTimeNanos;
/**
* Name of the current task.
*/
private String currentTaskName;
private TaskInfo lastTaskInfo;
private int taskCount;
/**
* Total running time.
*/
private long totalTimeNanos;
/**
* Construct a new {@code StopWatch}.
* <p>Does not start any task.
*/
public StopWatch() {
this("");
}
/**
* Construct a new {@code StopWatch} with the given ID.
* <p>The ID is handy when we have output from multiple stop watches and need
* to distinguish between them.
* <p>Does not start any task.
*
* @param id identifier for this stop watch
*/
public StopWatch(String id) {
this.id = id;
}
/**
* Get the ID of this {@code StopWatch}, as specified on construction.
*
* @return the ID (empty String by default)
* @see #StopWatch(String)
* @since 4.2.2
*/
public String getId() {
return this.id;
}
/**
* Configure whether the {@link StopWatch.TaskInfo} array is built over time.
* <p>Set this to {@code false} when using a {@code StopWatch} for millions
* of intervals; otherwise, the {@code TaskInfo} structure will consume
* excessive memory.
* <p>Default is {@code true}.
*/
public void setKeepTaskList(boolean keepTaskList) {
this.keepTaskList = keepTaskList;
}
/**
* Start an unnamed task.
* <p>The results are undefined if {@link #stop()} or timing methods are
* called without invoking this method first.
*
* @see #start(String)
* @see #stop()
*/
public void start() throws IllegalStateException {
start("");
}
/**
* Start a named task.
* <p>The results are undefined if {@link #stop()} or timing methods are
* called without invoking this method first.
*
* @param taskName the name of the task to start
* @see #start()
* @see #stop()
*/
public void start(String taskName) throws IllegalStateException {
if (this.currentTaskName != null) {
throw new IllegalStateException("Can't start StopWatch: it's already running");
}
this.currentTaskName = taskName;
this.startTimeNanos = System.nanoTime();
}
/**
* Stop the current task.
* <p>The results are undefined if timing methods are called without invoking
* at least one pair of {@code start()} / {@code stop()} methods.
*
* @see #start()
* @see #start(String)
*/
public void stop() throws IllegalStateException {
if (this.currentTaskName == null) {
throw new IllegalStateException("Can't stop StopWatch: it's not running");
}
long lastTime = System.nanoTime() - this.startTimeNanos;
this.totalTimeNanos += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
if (this.keepTaskList) {
this.taskList.add(this.lastTaskInfo);
}
++this.taskCount;
this.currentTaskName = null;
}
/**
* Determine whether this {@code StopWatch} is currently running.
*
* @see #currentTaskName()
*/
public boolean isRunning() {
return (this.currentTaskName != null);
}
/**
* Get the name of the currently running task, if any.
*
* @see #isRunning()
* @since 4.2.2
*/
public String currentTaskName() {
return this.currentTaskName;
}
/**
* Get the time taken by the last task in nanoseconds.
*
* @see #getLastTaskTimeMillis()
* @since 5.2
*/
public long getLastTaskTimeNanos() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task interval");
}
return this.lastTaskInfo.getTimeNanos();
}
/**
* Get the time taken by the last task in milliseconds.
*
* @see #getLastTaskTimeNanos()
*/
public long getLastTaskTimeMillis() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task interval");
}
return this.lastTaskInfo.getTimeMillis();
}
/**
* Get the name of the last task.
*/
public String getLastTaskName() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task name");
}
return this.lastTaskInfo.getTaskName();
}
/**
* Get the last task as a {@link StopWatch.TaskInfo} object.
*/
public StopWatch.TaskInfo getLastTaskInfo() throws IllegalStateException {
if (this.lastTaskInfo == null) {
throw new IllegalStateException("No tasks run: can't get last task info");
}
return this.lastTaskInfo;
}
/**
* Get the total time in nanoseconds for all tasks.
*
* @see #getTotalTimeMillis()
* @see #getTotalTimeSeconds()
* @since 5.2
*/
public long getTotalTimeNanos() {
return this.totalTimeNanos;
}
/**
* Get the total time in milliseconds for all tasks.
*
* @see #getTotalTimeNanos()
* @see #getTotalTimeSeconds()
*/
public long getTotalTimeMillis() {
return nanosToMillis(this.totalTimeNanos);
}
/**
* Get the total time in seconds for all tasks.
*
* @see #getTotalTimeNanos()
* @see #getTotalTimeMillis()
*/
public double getTotalTimeSeconds() {
return nanosToSeconds(this.totalTimeNanos);
}
/**
* Get the number of tasks timed.
*/
public int getTaskCount() {
return this.taskCount;
}
/**
* Get an array of the data for tasks performed.
*/
public StopWatch.TaskInfo[] getTaskInfo() {
if (!this.keepTaskList) {
throw new UnsupportedOperationException("Task info is not being kept!");
}
return this.taskList.toArray(new StopWatch.TaskInfo[0]);
}
/**
* Get a short description of the total running time.
*/
public String shortSummary() {
return "StopWatch '" + getId() + "': running time = " + getTotalTimeNanos() + " ns";
}
/**
* Generate a string with a table describing all tasks performed.
* <p>For custom reporting, call {@link #getTaskInfo()} and use the task info
* directly.
*/
public String prettyPrint() {
StringBuilder sb = new StringBuilder(shortSummary());
sb.append('\n');
if (!this.keepTaskList) {
sb.append("No task info kept");
} else {
sb.append("---------------------------------------------\n");
sb.append("ns % Task name\n");
sb.append("---------------------------------------------\n");
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumIntegerDigits(9);
nf.setGroupingUsed(false);
NumberFormat pf = NumberFormat.getPercentInstance();
pf.setMinimumIntegerDigits(3);
pf.setGroupingUsed(false);
for (StopWatch.TaskInfo task : getTaskInfo()) {
sb.append(nf.format(task.getTimeNanos())).append(" ");
sb.append(pf.format((double) task.getTimeNanos() / getTotalTimeNanos())).append(" ");
sb.append(task.getTaskName()).append('\n');
}
}
return sb.toString();
}
/**
* Generate an informative string describing all tasks performed
* <p>For custom reporting, call {@link #getTaskInfo()} and use the task info
* directly.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(shortSummary());
if (this.keepTaskList) {
for (StopWatch.TaskInfo task : getTaskInfo()) {
sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeNanos()).append(" ns");
long percent = Math.round(100.0 * task.getTimeNanos() / getTotalTimeNanos());
sb.append(" = ").append(percent).append('%');
}
} else {
sb.append("; no task info kept");
}
return sb.toString();
}
private static long nanosToMillis(long duration) {
return TimeUnit.NANOSECONDS.toMillis(duration);
}
private static double nanosToSeconds(long duration) {
return duration / 1_000_000_000.0;
}
/**
* Nested class to hold data about one task executed within the {@code StopWatch}.
*/
public static final class TaskInfo {
private final String taskName;
private final long timeNanos;
TaskInfo(String taskName, long timeNanos) {
this.taskName = taskName;
this.timeNanos = timeNanos;
}
/**
* Get the name of this task.
*/
public String getTaskName() {
return this.taskName;
}
/**
* Get the time in nanoseconds this task took.
*
* @see #getTimeMillis()
* @see #getTimeSeconds()
* @since 5.2
*/
public long getTimeNanos() {
return this.timeNanos;
}
/**
* Get the time in milliseconds this task took.
*
* @see #getTimeNanos()
* @see #getTimeSeconds()
*/
public long getTimeMillis() {
return nanosToMillis(this.timeNanos);
}
/**
* Get the time in seconds this task took.
*
* @see #getTimeMillis()
* @see #getTimeNanos()
*/
public double getTimeSeconds() {
return nanosToSeconds(this.timeNanos);
}
}
}
@@ -0,0 +1,16 @@
package com.leosam.tvbox.mv.utils;
/**
* @author admin
* @since 2023/6/12 21:32
*/
public class StringUtils {
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
}
@@ -0,0 +1,20 @@
package com.leosam.tvbox.mv.utils;
import io.vertx.ext.web.RoutingContext;
import java.util.List;
/**
* @author admin
* @since 2023/6/12 21:16
*/
public class VertxUtils {
public static String queryParam(RoutingContext context, String wd) {
List<String> param = context.queryParam(wd);
if (param != null && param.size() > 0) {
return param.get(0);
}
return "";
}
}