file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
HAProxyProtocolException.java
/FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyProtocolException.java
package net.rezxis.mctp.client.haproxy; import io.netty.handler.codec.DecoderException; /** * A {@link DecoderException} which is thrown when an invalid HAProxy proxy protocol header is encountered */ public class HAProxyProtocolException extends DecoderException { private static final long serialVersionUID = 713710864325167351L; /** * Creates a new instance */ public HAProxyProtocolException() { } /** * Creates a new instance */ public HAProxyProtocolException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance */ public HAProxyProtocolException(String message) { super(message); } /** * Creates a new instance */ public HAProxyProtocolException(Throwable cause) { super(cause); } }
847
Java
.java
RezxisNetwork/MinecraftTransport-Client
9
4
1
2020-12-23T08:32:18Z
2021-07-31T14:09:19Z
HAProxyCommand.java
/FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/haproxy/HAProxyCommand.java
package net.rezxis.mctp.client.haproxy; public enum HAProxyCommand { /** * The LOCAL command represents a connection that was established on purpose by the proxy * without being relayed. */ LOCAL(HAProxyConstants.COMMAND_LOCAL_BYTE), /** * The PROXY command represents a connection that was established on behalf of another node, * and reflects the original connection endpoints. */ PROXY(HAProxyConstants.COMMAND_PROXY_BYTE); /** * The command is specified in the lowest 4 bits of the protocol version and command byte */ private static final byte COMMAND_MASK = 0x0f; private final byte byteValue; /** * Creates a new instance */ HAProxyCommand(byte byteValue) { this.byteValue = byteValue; } /** * Returns the {@link HAProxyCommand} represented by the lowest 4 bits of the specified byte. * * @param verCmdByte protocol version and command byte */ public static HAProxyCommand valueOf(byte verCmdByte) { int cmd = verCmdByte & COMMAND_MASK; switch ((byte) cmd) { case HAProxyConstants.COMMAND_PROXY_BYTE: return PROXY; case HAProxyConstants.COMMAND_LOCAL_BYTE: return LOCAL; default: throw new IllegalArgumentException("unknown command: " + cmd); } } /** * Returns the byte value of this command. */ public byte byteValue() { return byteValue; } }
1,482
Java
.java
RezxisNetwork/MinecraftTransport-Client
9
4
1
2020-12-23T08:32:18Z
2021-07-31T14:09:19Z
ProxiedConnection.java
/FileExtraction/Java_unseen/RezxisNetwork_MinecraftTransport-Client/src/main/java/net/rezxis/mctp/client/proxied/ProxiedConnection.java
package net.rezxis.mctp.client.proxied; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import net.rezxis.mctp.client.ChannelMirror; import net.rezxis.mctp.client.MCTPVars; import net.rezxis.mctp.client.MinecraftTransport; import net.rezxis.mctp.client.util.PacketEncoder; import java.util.ArrayList; @ChannelHandler.Sharable public class ProxiedConnection extends ChannelInboundHandlerAdapter implements Runnable { private long secret; private long id; private Channel mctp; private Channel minecraft; public ProxiedConnection(long secret, long id) { this.secret = secret; this.id = id; } @Override public void run() { Bootstrap bs1 = new Bootstrap(); Bootstrap bs2 = new Bootstrap(); EventLoopGroup worker = new NioEventLoopGroup(); try{ bs1.channel(NioSocketChannel.class) .group(worker) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new PacketEncoder()); ch.pipeline().addLast(ProxiedConnection.this); } }); mctp = bs1.connect(MinecraftTransport.config.host, MinecraftTransport.config.port).sync().channel(); sendUpgradePacket(secret,id); mctp.pipeline().remove(PacketEncoder.class); bs2.channel(NioSocketChannel.class) .group(worker) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new ChannelMirror(mctp)); } }); minecraft = bs2.connect("127.0.0.1", MinecraftTransport.instance.getServer().getPort()).sync().channel(); mctp.pipeline().remove(ProxiedConnection.class); for (ByteBuf buf : mctp.attr(MCTPVars.PACKET_STACK).get()) { minecraft.writeAndFlush(buf); } mctp.pipeline().addLast(new ChannelMirror(minecraft)); } catch(Exception e) { e.printStackTrace(); return; } } private void sendUpgradePacket(long secret, long id) { int size = 17; ByteBuf packet = Unpooled.buffer(size,size); packet.writeByte(MCTPVars.CODE_UPGRADE); packet.writeLong(secret); packet.writeLong(id); mctp.writeAndFlush(packet); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.attr(MCTPVars.PACKET_STACK).set(new ArrayList<>()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.attr(MCTPVars.PACKET_STACK).get().add((ByteBuf)msg); } }
3,335
Java
.java
RezxisNetwork/MinecraftTransport-Client
9
4
1
2020-12-23T08:32:18Z
2021-07-31T14:09:19Z
Main.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/Main.java
package de.mas.wiiu.jnus.fuse_wiiu; import de.mas.wiiu.jnus.fuse_wiiu.implementation.GroupFuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.implementation.GroupFuseContainerDefault; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.utils.FuseContainerWrapper; import de.mas.wiiu.jnus.utils.HashUtil; import de.mas.wiiu.jnus.utils.Utils; import org.apache.commons.cli.*; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; public class Main { private static final String DEV_COMMON_KEY = "devcommon.key"; private static final String COMMON_KEY = "common.key"; private final static String OPTION_HELP = "help"; private final static String OPTION_MOUNTPATH = "mountpath"; private final static String OPTION_INPUT = "in"; private final static String OPTION_DISCKEYS = "disckeypath"; private final static String OPTION_TITLEKEYS = "titlekeypath"; private static final String OPTION_COMMON_KEY = "commonkey"; private static final String OPTION_DEV_COMMON_KEY = "devcommonkey"; private static final String HOMEPATH = System.getProperty("user.home") + File.separator + ".wiiu"; private static final String DISC_KEY_PATH = "discKeys"; private static final String TITLE_KEY_PATH = "titleKeys"; private static Optional<byte[]> readKey(File file) { if (file.isFile()) { byte[] key; try { key = Files.readAllBytes(file.toPath()); if (key != null && key.length == 16) { return Optional.of(key); } } catch (IOException e) { } } return Optional.empty(); } private static void checkKeysForFolder(File folder) { if (folder.exists()) { File commonkeyFile = new File(folder.getAbsolutePath() + File.separator + COMMON_KEY); File commonkeyDevFile = new File(folder.getAbsolutePath() + File.separator + DEV_COMMON_KEY); if (commonkeyFile.exists()) { readKey(commonkeyFile).ifPresent(key -> Settings.retailCommonKey = key); } if (commonkeyDevFile.exists()) { readKey(commonkeyDevFile).ifPresent(key -> Settings.devCommonKey = key); } } } public static void main(String[] args) throws Exception { if (!Charset.defaultCharset().toString().equals("UTF-8")) { System.err.println("This application needs to be started with the \"UTF-8\" charset."); System.out.println("Use the jvm argument \"-Dfile.encoding=UTF-8\"."); System.exit(-1); } File homewiiufolder = new File(HOMEPATH); checkKeysForFolder(homewiiufolder); checkKeysForFolder(new File(".")); Options options = getOptions(); if (args.length == 0) { showHelp(options); return; } Settings.disckeyPath = new File(HOMEPATH + File.separator + DISC_KEY_PATH); Settings.titlekeyPath = new File(HOMEPATH + File.separator + TITLE_KEY_PATH); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; String mountPath = ""; cmd = parser.parse(options, args); String inputPath = ""; if (cmd.hasOption(OPTION_MOUNTPATH)) { mountPath = cmd.getOptionValue(OPTION_MOUNTPATH); } if (cmd.hasOption(OPTION_INPUT)) { inputPath = cmd.getOptionValue(OPTION_INPUT); } if (cmd.hasOption(OPTION_COMMON_KEY)) { String commonKey = cmd.getOptionValue(OPTION_COMMON_KEY); byte[] key = Utils.StringToByteArray(commonKey); if (key != null && key.length == 0x10) { Settings.retailCommonKey = key; System.out.println("Common key was set from command line."); } } if (cmd.hasOption(OPTION_DEV_COMMON_KEY)) { String devCommonKey = cmd.getOptionValue(OPTION_DEV_COMMON_KEY); byte[] key = Utils.StringToByteArray(devCommonKey); if (key != null && key.length == 0x10) { Settings.devCommonKey = key; System.out.println("Dev common key was set from command line."); } } if (cmd.hasOption(OPTION_DISCKEYS)) { Settings.disckeyPath = new File(cmd.getOptionValue(OPTION_DISCKEYS)); } if (cmd.hasOption(OPTION_TITLEKEYS)) { Settings.titlekeyPath = new File(cmd.getOptionValue(OPTION_TITLEKEYS)); } File mount = new File(mountPath); File mountparent = mount.getParentFile(); if (mountparent != null && !mountparent.exists()) { System.err.println("Mounting to " + mount + " is not possible." + mountparent + " does not exist"); return; } else if (mount.exists() && System.getProperty("os.name").contains("Windows")) { System.err.println("Mounting to " + mount + " is not possible. It's already mounted or in use"); return; } if (!Arrays.equals(HashUtil.hashSHA1(Settings.retailCommonKey), Settings.retailCommonKeyHash)) { System.err.println("WARNING: Retail common key is not as expected"); } else { System.out.println("retail common key is okay"); } if (!Arrays.equals(HashUtil.hashSHA1(Settings.devCommonKey), Settings.devCommonKeyHash)) { System.err.println("WARNING: Dev common key is not as expected"); } else { System.out.println("dev common key is okay"); } System.out.println("disc key path is: " + Settings.disckeyPath.getAbsolutePath()); System.out.println("title key path is: " + Settings.titlekeyPath.getAbsolutePath()); GroupFuseContainer root = new GroupFuseContainerDefault(Optional.empty()); File input = new File(inputPath); Map<String, FuseContainer> containers = FuseContainerWrapper.createFuseContainer(Optional.of(root), input); for (Entry<String, FuseContainer> c : containers.entrySet()) { String name = c.getKey(); if (name.isEmpty()) { name = input.getAbsolutePath().replaceAll("[\\\\/:*?\"<>|]", ""); } root.addFuseContainer(name, c.getValue()); } RootFuseFS stub = new RootFuseFS(root); try { System.out.println("Mounting " + new File(inputPath).getAbsolutePath() + " to " + mount.getAbsolutePath()); stub.mount(mount.toPath(), true, false); } finally { stub.umount(); } } private static Options getOptions() { Options options = new Options(); options.addOption(Option.builder(OPTION_MOUNTPATH).required().hasArg() .desc("The target mount path.").build()); options.addOption(Option.builder(OPTION_INPUT).required().hasArg().desc("input path").build()); options.addOption(Option.builder(OPTION_DISCKEYS).optionalArg(true).hasArg() .desc("Path of .key files used to decrypt WUD/WUX. If not set \"" + HOMEPATH + File.separator + DISC_KEY_PATH + "\" will be used.").build()); options.addOption(Option.builder(OPTION_TITLEKEYS).optionalArg(true).hasArg() .desc("Path of [TITLTEID].key files used to decrypt encrypted titles (.app,.tmd etc.). If not set \"" + HOMEPATH + File.separator + TITLE_KEY_PATH + "\" will be used.") .build()); options.addOption(Option.builder(OPTION_COMMON_KEY).optionalArg(true).hasArg() .desc("Wii U retail common key as binary string. Will be used even if a key is specified in \"" + HOMEPATH + File.separator + COMMON_KEY + "\" or \"" + HOMEPATH + File.separator + COMMON_KEY + "\"") .build()); options.addOption(Option.builder(OPTION_DEV_COMMON_KEY).optionalArg(true).hasArg() .desc("Wii U dev common key as binary string. Will be used even if a key is specified in \"" + HOMEPATH + File.separator + DEV_COMMON_KEY + "\" or \"" + HOMEPATH + File.separator + DEV_COMMON_KEY + "\"") .build()); options.addOption(OPTION_HELP, false, "shows this text"); return options; } private static void showHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp(" ", options); } }
8,714
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
RootFuseFS.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/RootFuseFS.java
package de.mas.wiiu.jnus.fuse_wiiu; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import jnr.ffi.Pointer; import jnr.ffi.types.off_t; import jnr.ffi.types.size_t; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.FuseStubFS; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; public class RootFuseFS extends FuseStubFS { private final FuseContainer root; public RootFuseFS(FuseContainer root) { this.root = root; } @Override public int getattr(String path, FileStat stat) { int res = root.getattr(path, stat); // System.out.println("getattr " + res + " for " + path); return res; } @Override public int open(String path, FuseFileInfo fi) { int res = root.open(path, fi); // System.out.println("readdir " + res + " for " + path); return res; } @Override public int readdir(String path, Pointer buf, FuseFillDir filter, @off_t long offset, FuseFileInfo fi) { int res = root.readdir(path, buf, filter, offset, fi); // System.out.println("readdir " + res + " for " + path); return res; } @Override public int read(String path, Pointer buf, @size_t long size, @off_t long offset, FuseFileInfo fi) { int res = root.read(path, buf, size, offset, fi); // System.out.println("read " + res + " for " + path); return res; } }
1,447
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
Settings.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/Settings.java
package de.mas.wiiu.jnus.fuse_wiiu; import de.mas.wiiu.jnus.utils.Utils; import java.io.File; public class Settings { public static final byte[] retailCommonKeyHash = Utils.StringToByteArray("6A0B87FC98B306AE3366F0E0A88D0B06A2813313"); public static final byte[] devCommonKeyHash = Utils.StringToByteArray("E191BFDB1232537D7DADEAD81F2A48FD6F188E02"); public static File disckeyPath = null; public static File titlekeyPath = null; public static byte[] retailCommonKey = new byte[16]; public static byte[] devCommonKey = new byte[16]; }
562
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
NUSTitleEncryptedFuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/NUSTitleEncryptedFuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitle; import de.mas.wiiu.jnus.entities.TMD.Content; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import jnr.ffi.Pointer; import ru.serce.jnrfuse.ErrorCodes; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Supplier; public class NUSTitleEncryptedFuseContainer implements FuseContainer { private final Optional<FuseDirectory> parent; private final NUSTitle title; public NUSTitleEncryptedFuseContainer(Optional<FuseDirectory> parent, NUSTitle t) { this.parent = parent; this.title = t; } @Override public Optional<FuseDirectory> getParent() { return parent; } private Optional<Content> getContentForPath(String path) { if (!path.endsWith(".app") || path.length() != 12) { return Optional.empty(); } try { int contentID = Integer.parseInt(path.substring(0, 8), 16); Content c = title.getTMD().getContentByID(contentID); if (c != null) { return Optional.of(c); } } catch (NumberFormatException e) { } return Optional.empty(); } @SuppressWarnings("unused") private Optional<byte[]> getH3ForPath(String path) { if (!path.endsWith(".h3") || path.length() != 11) { return Optional.empty(); } return getContentForPath(path.substring(0, 8) + ".app").flatMap(c -> { if (c.isHashed()) { try { Optional<byte[]> hash = title.getDataProcessor().getDataProvider().getContentH3Hash(c); return hash; } catch (IOException e) { } } return Optional.empty(); }); } private Optional<byte[]> getTMDforPath(String path) { return getFileforPath(path, "title.tmd", () -> { try { return title.getDataProcessor().getDataProvider().getRawTMD(); } catch (IOException e) { return Optional.empty(); } }); } private Optional<byte[]> getTicketforPath(String path) { return getFileforPath(path, "title.tik", () -> { try { return title.getDataProcessor().getDataProvider().getRawTicket(); } catch (IOException e) { return Optional.empty(); } }); } private Optional<byte[]> getCertforPath(String path) { return getFileforPath(path, "title.cert", () -> { try { return title.getDataProcessor().getDataProvider().getRawCert(); } catch (IOException e) { return Optional.empty(); } }); } private Optional<byte[]> getFileforPath(String path, String expected, Supplier<Optional<byte[]>> func) { if (!path.equals(expected)) { return Optional.empty(); } return func.get(); } @Override public int open(String path, FuseFileInfo fi) { if (path.equals("/")) { return -ErrorCodes.EISDIR(); } return getattr(path, null); } @Override public int getattr(String path, FileStat stat) { if (path.equals("/")) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); return 0; } path = path.substring(1); Optional<Content> coOptional = getContentForPath(path); if (coOptional.isPresent()) { if (stat != null) { stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); stat.st_nlink.set(1); stat.st_size.set(coOptional.get().getEncryptedFileSize()); } return 0; } else { Optional<byte[]> h3Data = getH3ForPath(path); if (h3Data.isPresent()) { if (stat != null) { stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); stat.st_nlink.set(1); stat.st_size.set(h3Data.get().length); } return 0; } } List<Supplier<Optional<byte[]>>> functions = new ArrayList<>(); String pathcopy = path; functions.add(() -> getTMDforPath(pathcopy)); functions.add(() -> getTicketforPath(pathcopy)); functions.add(() -> getCertforPath(pathcopy)); for (Supplier<Optional<byte[]>> func : functions) { Optional<byte[]> data = func.get(); if (data.isPresent()) { if (stat != null) { stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); stat.st_nlink.set(1); stat.st_size.set(data.get().length); } return 0; } } return -ErrorCodes.ENOENT(); } @Override public int readdir(String path, Pointer buf, FuseFillDir filter, long offset, FuseFileInfo fi) { filter.apply(buf, ".", null, 0); if (getParent().isPresent()) { filter.apply(buf, "..", null, 0); } for (Content e : title.getTMD().getAllContents().values()) { filter.apply(buf, e.getFilename(), null, 0); if (e.isHashed()) { filter.apply(buf, String.format("%08X.h3", e.getID()), null, 0); } } if (getTMDforPath("title.tmd").isPresent()) { filter.apply(buf, "title.tmd", null, 0); } if (getTicketforPath("title.tik").isPresent()) { filter.apply(buf, "title.tik", null, 0); } if (getCertforPath("title.cert").isPresent()) { filter.apply(buf, "title.cert", null, 0); } return 0; } @Override public int read(String path, Pointer buf, long size, long offset, FuseFileInfo fi) { if (path.equals("/")) { return -ErrorCodes.EISDIR(); } if(size > Integer.MAX_VALUE) { System.err.println("Request read size was too big."); return -ErrorCodes.EIO(); } path = path.substring(1); Optional<Content> coOptional = getContentForPath(path); if (coOptional.isPresent()) { Content c = coOptional.get(); if (offset >= c.getEncryptedFileSize()) { return -ErrorCodes.EIO(); } if (offset + size > c.getEncryptedFileSize()) { size = c.getEncryptedFileSize() - offset; } byte[] data; try { data = title.getDataProcessor().readContent(c, offset, (int) size); buf.put(0, data, 0, data.length); return data.length; } catch (Exception e) { e.printStackTrace(); return -ErrorCodes.ENOENT(); } } else { Optional<byte[]> h3Data = getH3ForPath(path); if (h3Data.isPresent()) { byte[] hash = h3Data.get(); if (offset >= hash.length) { return -ErrorCodes.EIO(); } if (offset + size > hash.length) { size = hash.length - offset; } buf.put(0, hash, (int) offset, (int) size); return (int) size; } } // Check if the tmd ticket or cert are request. List<Supplier<Optional<byte[]>>> functions = new ArrayList<>(); String pathcopy = path; functions.add(() -> getTMDforPath(pathcopy)); functions.add(() -> getTicketforPath(pathcopy)); functions.add(() -> getCertforPath(pathcopy)); for (Supplier<Optional<byte[]>> func : functions) { Optional<byte[]> dataOpt = func.get(); if (dataOpt.isPresent()) { byte[] data = dataOpt.get(); if (data == null || data.length == 0) { return -ErrorCodes.ENOENT(); } if (offset >= data.length) { return -ErrorCodes.ENOENT(); } if (offset + size > data.length) { size = data.length - offset; } buf.put(0, data, (int) offset, (int) size); return (int) size; } } return 0; } @Override public void init() { } @Override public void deinit() { } }
8,872
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
MultipleFSTDataProviderRecursiveFuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/MultipleFSTDataProviderRecursiveFuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitleLoaderFST; import de.mas.wiiu.jnus.entities.FST.nodeentry.DirectoryEntry; import de.mas.wiiu.jnus.entities.FST.nodeentry.FileEntry; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FSTDataProviderLoader; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.implementations.FSTDataProviderNUSTitle; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import de.mas.wiiu.jnus.interfaces.HasNUSTitle; import de.mas.wiiu.jnus.utils.FSTUtils; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.List; import java.util.Optional; public class MultipleFSTDataProviderRecursiveFuseContainer<T> extends MultipleFSTDataProviderFuseContainer<T> { public MultipleFSTDataProviderRecursiveFuseContainer(Optional<FuseDirectory> parent, File input, FSTDataProviderLoader<T> loader) { super(parent, input, loader); } @Override void parseContents(List<FSTDataProvider> dps) { try { for (FSTDataProvider dp : dps) { for (FileEntry tmd : FSTUtils.getFSTEntriesByRegEx(dp.getRoot(), ".*tmd")) { DirectoryEntry parent = tmd.getParent(); if (parent.getFileChildren().stream().filter(f -> f.getName().endsWith(".app")).findAny().isPresent()) { FSTDataProvider fdp = null; try { fdp = new FSTDataProviderNUSTitle(NUSTitleLoaderFST.loadNUSTitle(dp, parent, Settings.retailCommonKey)); } catch (IOException | ParseException e) { try { fdp = new FSTDataProviderNUSTitle(NUSTitleLoaderFST.loadNUSTitle(dp, parent, Settings.devCommonKey)); } catch (Exception e1) { System.out.println("Ignoring " + parent.getName() + " :" + e1.getClass().getName() + " " + e1.getMessage()); continue; } } catch (Exception e) { System.out.println("Ignoring " + parent.getName() + " :" + e.getClass().getName() + " " + e.getMessage()); continue; } FSTDataProvider fdpCpy = fdp; this.addFuseContainer("[DECRYPTED] [" + dp.getName() + "] " + parent.getName(), new FSTDataProviderContainer(getParent(), fdpCpy)); } } if (dp instanceof HasNUSTitle) { try { this.addFuseContainer("[ENCRYPTED] " + dp.getName(), new NUSTitleEncryptedFuseContainer(getParent(), ((HasNUSTitle) dp).getNUSTitle())); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } }
3,106
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
RemoteLocalBackupNUSTitleContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/RemoteLocalBackupNUSTitleContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitle; import de.mas.wiiu.jnus.NUSTitleLoaderRemoteLocal; import de.mas.wiiu.jnus.entities.Ticket; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.fuse_wiiu.utils.TicketUtils; import de.mas.wiiu.jnus.implementations.FSTDataProviderNUSTitle; import de.mas.wiiu.jnus.utils.Utils; import java.io.File; import java.io.IOException; import java.util.Optional; public class RemoteLocalBackupNUSTitleContainer extends GroupFuseContainer { private File folder; public RemoteLocalBackupNUSTitleContainer(Optional<FuseDirectory> parent, File folder) { super(parent); this.folder = folder; } @Override protected void doInit() { File[] wud = folder.listFiles(f -> f.getName().startsWith("tmd.")); for (File versionF : wud) { short version = Short.parseShort(versionF.getName().substring(4)); this.addFuseContainer(String.format("v%d", version), new FSTDataProviderContainer(Optional.of(this), () -> { long titleID = Utils.StringToLong(folder.getName()); NUSTitle t = null; Optional<Ticket> ticketOpt = TicketUtils.getTicket(folder, Settings.titlekeyPath, titleID, Settings.retailCommonKey); System.out.println(ticketOpt); if (!ticketOpt.isPresent()) { return null; } Ticket ticket = ticketOpt.get(); try { t = NUSTitleLoaderRemoteLocal.loadNUSTitle(folder.getAbsolutePath(), version, ticket); } catch (Exception e) { // Try dev ticket ticket = Ticket.createTicket(ticket.getEncryptedKey(), titleID, Settings.devCommonKey); try { t = NUSTitleLoaderRemoteLocal.loadNUSTitle(folder.getAbsolutePath(), version, ticket); } catch (Exception e1) { e.printStackTrace(); e1.printStackTrace(); } } try { return new FSTDataProviderNUSTitle(t); } catch (IOException e) { e.printStackTrace(); return null; } })); } } }
2,459
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FSFuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/FSFuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.fuse_wiiu.utils.FuseContainerWrapper; import lombok.val; import java.io.File; import java.util.*; import java.util.Map.Entry; /** * Representation of a directory on the OS filesystem. For every children of this directory the FuseContainerWrapper is used to create children if needed. * * @author Maschell * */ public class FSFuseContainer extends GroupFuseContainer { private final File curDir; private final Timer timer = new Timer(); public FSFuseContainer(Optional<FuseDirectory> parent, File input) { super(parent); this.curDir = input; // Check every 5 minutes if the children of this directory have been accessed in the last 5 minutes. timer.schedule(new TimerTask() { public void run() { removeUnused(5 * 60 * 1000); } }, 5 * 60 * 1000, 5 * 60 * 1000); } @Override public void deinit() { // Stop the timers so this can be collected by the GC. timer.cancel(); timer.purge(); } Map<File, Collection<String>> existingFiles = new HashMap<>(); /** * Add FuseContainer for the children of this directory, but only if they are missing. */ private void updateFolder() { for (File f : curDir.listFiles()) { Collection<String> t = existingFiles.get(f); if (t != null && !t.isEmpty()) { boolean missing = false; for (String cur : t) { if (!hasFuseContainer(cur)) { missing = true; break; } } if (missing) { for (String cur : t) { removeFuseContainer(cur); } existingFiles.remove(f); } else { continue; } } val fuseContainers = FuseContainerWrapper.createFuseContainer(Optional.of(this), f); for (Entry<String, FuseContainer> e : fuseContainers.entrySet()) { addFuseContainer(e.getKey(), e.getValue()); } existingFiles.put(f, fuseContainers.keySet()); } } @Override protected void doInit() { updateFolder(); } }
2,503
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
GroupFuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/GroupFuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import jnr.ffi.Pointer; import jnr.ffi.types.off_t; import jnr.ffi.types.size_t; import ru.serce.jnrfuse.ErrorCodes; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * Implementation of an FuseContainer which can hold serveral FuseContainers emulated as directories. * * @author Maschell */ public abstract class GroupFuseContainer implements FuseContainer { private final Map<String, FuseContainer> containerMap = new HashMap<>(); private final Map<String, Long> lastAccess = new HashMap<>(); private final Optional<FuseDirectory> parent; public GroupFuseContainer(Optional<FuseDirectory> parent) { this.parent = parent; } /** * Removing old container from the list that haven't been updated in a given time frame. * * @param duration * @return Number of elements that have been removed. */ protected int removeUnused(long duration) { int count = 0; for (Entry<String, Long> cur : lastAccess.entrySet().stream().filter(e -> System.currentTimeMillis() - e.getValue() > duration) .collect(Collectors.toList())) { lastAccess.remove(cur.getKey()); containerMap.remove(cur.getKey()).deinit(); System.out.println("Unmounting " + cur.getKey()); count++; } if (count > 0) { synchronized (initDone) { initDone = false; } } return count; } /** * * @param path * @param func * @param defaultValue * @return */ private int doForContainer(String path, BiFunction<String, FuseContainer, Integer> func, int defaultValue) { path.replace("\\", "/"); path = path.substring(1); String[] parts = path.split("/"); FuseContainer container = containerMap.get(parts[0]); if (container != null) { lastAccess.put(parts[0], System.currentTimeMillis()); container.init(); String newPath = path.substring(parts[0].length()); if (newPath.length() == 0) { newPath = "/"; } return func.apply(newPath, container); } return defaultValue; } @Override public int getattr(String path, FileStat stat) { path.replace("\\", "/"); if (path.equals("/")) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); return 0; } if (path.split("/").length == 2) { for (String container : containerMap.keySet()) { if (container.equals(path.split("/")[1])) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); return 0; } } } return doForContainer(path, (newPath, container) -> container.getattr(newPath, stat), -ErrorCodes.ENOENT()); } @Override public int readdir(String path, Pointer buf, FuseFillDir filter, @off_t long offset, FuseFileInfo fi) { path.replace("\\", "/"); if (path.equals("/")) { filter.apply(buf, ".", null, 0); if (getParent().isPresent()) { filter.apply(buf, "..", null, 0); } for (String container : containerMap.keySet()) { filter.apply(buf, container, null, 0); } return 0; } return doForContainer(path, (newPath, container) -> container.readdir(newPath, buf, filter, offset, fi), 0); } @Override public int read(String path, Pointer buf, @size_t long size, @off_t long offset, FuseFileInfo fi) { path.replace("\\", "/"); if (path.length() <= 1) { return -ErrorCodes.EISDIR(); } return doForContainer(path, (newPath, container) -> container.read(newPath, buf, size, offset, fi), 0); } @Override public int open(String path, FuseFileInfo fi) { path.replace("\\", "/"); if (path.length() <= 1) { return -ErrorCodes.EISDIR(); } return doForContainer(path, (newPath, container) -> container.open(newPath, fi), 0); } @Override public Optional<FuseDirectory> getParent() { return parent; } public FuseContainer addFuseContainer(String name, FuseContainer container) { return containerMap.put(name, container); } public void clearFuseContainer() { containerMap.clear(); } public FuseContainer getFuseContainer(String name) { return containerMap.get(name); } public boolean hasFuseContainer(String name) { return containerMap.containsKey(name); } public FuseContainer removeFuseContainer(String name) { return containerMap.remove(name); } private Boolean initDone = false; @Override public void init() { synchronized (initDone) { if (!initDone) { doInit(); initDone = true; } } } /** * This function is used to add FuseContainers to this GroupFuseContainer and can be called because of two reason. 1. The GroupFuseContainer is access for * the first time and the list FuseContainers in this group need to be added to the map using "addFuseContainer". 2. Some of the children have been removed * (due to inactivity). In this case the functions should add them again. So it needs to either add the missing one (check by hasFuseContainer), or * completely wipe and start over. */ abstract protected void doInit(); @Override public void deinit() { // } }
6,121
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
LocalBackupNUSTitleContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/LocalBackupNUSTitleContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitle; import de.mas.wiiu.jnus.NUSTitleLoaderLocalBackup; import de.mas.wiiu.jnus.entities.Ticket; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.fuse_wiiu.utils.TicketUtils; import de.mas.wiiu.jnus.implementations.FSTDataProviderNUSTitle; import de.mas.wiiu.jnus.utils.Utils; import java.io.File; import java.io.IOException; import java.util.Optional; public class LocalBackupNUSTitleContainer extends GroupFuseContainer { private File folder; public LocalBackupNUSTitleContainer(Optional<FuseDirectory> parent, File folder) { super(parent); this.folder = folder; } @Override protected void doInit() { File[] wud = folder.listFiles(f -> f.getName().startsWith("tmd.")); for (File versionF : wud) { short version = Short.parseShort(versionF.getName().substring(4)); this.addFuseContainer(String.format("v%d", version), new FSTDataProviderContainer(Optional.of(this), () -> { long titleID = Utils.StringToLong(folder.getName()); NUSTitle t = null; Optional<Ticket> ticketOpt = TicketUtils.getTicket(folder, Settings.titlekeyPath, titleID, Settings.retailCommonKey); if (!ticketOpt.isPresent()) { return null; } Ticket ticket = ticketOpt.get(); try { t = NUSTitleLoaderLocalBackup.loadNUSTitle(folder.getAbsolutePath(), version, ticket); } catch (Exception e) { // Try dev ticket ticket = Ticket.createTicket(ticket.getEncryptedKey(), titleID, Settings.devCommonKey); try { t = NUSTitleLoaderLocalBackup.loadNUSTitle(folder.getAbsolutePath(), version, ticket); } catch (Exception e1) { e.printStackTrace(); e1.printStackTrace(); } } try { return new FSTDataProviderNUSTitle(t); } catch (IOException e) { e.printStackTrace(); return null; } })); } } }
2,379
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
LocalNUSTitleContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/LocalNUSTitleContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitle; import de.mas.wiiu.jnus.NUSTitleLoaderLocal; import de.mas.wiiu.jnus.entities.TMD.TitleMetaData; import de.mas.wiiu.jnus.entities.Ticket; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.fuse_wiiu.utils.TicketUtils; import de.mas.wiiu.jnus.implementations.FSTDataProviderNUSTitle; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.Optional; public class LocalNUSTitleContainer extends GroupFuseContainer { private File folder; public LocalNUSTitleContainer(Optional<FuseDirectory> parent, File folder) { super(parent); this.folder = folder; } @Override protected void doInit() { long titleID = 0; short version = 0; try { TitleMetaData tmd = TitleMetaData.parseTMD(new File(folder.getAbsoluteFile() + File.separator + "title.tmd")); titleID = tmd.getTitleID(); version = tmd.getTitleVersion(); } catch (IOException | ParseException e2) { return; } long titleIDcpy = titleID; this.addFuseContainer(String.format("v%d", version), new FSTDataProviderContainer(Optional.of(this), () -> { NUSTitle t = null; Optional<Ticket> ticketOpt = TicketUtils.getTicket(folder, Settings.titlekeyPath, titleIDcpy, Settings.retailCommonKey); if (!ticketOpt.isPresent()) { return null; } Ticket ticket = ticketOpt.get(); try { t = NUSTitleLoaderLocal.loadNUSTitle(folder.getAbsolutePath(), ticket); } catch (Exception e) { ticket = Ticket.createTicket(ticket.getEncryptedKey(), titleIDcpy, Settings.devCommonKey); try { t = NUSTitleLoaderLocal.loadNUSTitle(folder.getAbsolutePath(), ticket); } catch (Exception e1) { e.printStackTrace(); e1.printStackTrace(); } } try { return new FSTDataProviderNUSTitle(t); } catch (IOException e) { e.printStackTrace(); return null; } })); } }
2,374
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FSTDataProviderContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/FSTDataProviderContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.entities.FST.nodeentry.DirectoryEntry; import de.mas.wiiu.jnus.entities.FST.nodeentry.FileEntry; import de.mas.wiiu.jnus.entities.FST.nodeentry.NodeEntry; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import de.mas.wiiu.jnus.utils.FSTUtils; import jnr.ffi.Pointer; import lombok.Getter; import ru.serce.jnrfuse.ErrorCodes; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; import java.util.Optional; import java.util.function.Supplier; /** * FuseContainer implementation based on a FSTDataProvider. * * @author Maschell * */ public class FSTDataProviderContainer implements FuseContainer { private final Optional<FuseDirectory> parent; @Getter(lazy = true) private final FSTDataProvider dataProvider = dataProviderSupplier.get(); private final Supplier<FSTDataProvider> dataProviderSupplier; public FSTDataProviderContainer(Optional<FuseDirectory> parent, FSTDataProvider dp) { this(parent, () -> dp); } public FSTDataProviderContainer(Optional<FuseDirectory> parent, Supplier<FSTDataProvider> dp) { this.parent = parent; this.dataProviderSupplier = dp; } @Override public Optional<FuseDirectory> getParent() { return parent; } @Override public int open(String path, FuseFileInfo fi) { Optional<NodeEntry> entryOpt = FSTUtils.getFSTEntryByFullPath(getDataProvider().getRoot(), path); if (entryOpt.isPresent()) { if (entryOpt.get().isDirectory()) { return -ErrorCodes.EISDIR(); } else if (!entryOpt.get().isLink()) { return 0; } } return -ErrorCodes.ENOENT(); } @Override public int getattr(String path, FileStat stat) { if (path.equals("/")) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); return 0; } Optional<NodeEntry> entryOpt = FSTUtils.getFSTEntryByFullPath(getDataProvider().getRoot(), path); int res = 0; if (entryOpt.isPresent()) { NodeEntry entry = entryOpt.get(); if (entry.isDirectory()) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); } else { stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); stat.st_nlink.set(1); stat.st_size.set(((FileEntry) entry).getSize()); } } else { System.out.println("error for " + path); return -ErrorCodes.ENOENT(); } return res; } @Override public int readdir(String path, Pointer buf, FuseFillDir filter, long offset, FuseFileInfo fi) { DirectoryEntry entry = getDataProvider().getRoot(); if (!path.equals("/")) { Optional<DirectoryEntry> entryOpt = FSTUtils.getFileEntryDir(entry, path); if (!entryOpt.isPresent()) { return -ErrorCodes.ENOENT(); } entry = entryOpt.get(); } filter.apply(buf, ".", null, 0); filter.apply(buf, "..", null, 0); for (NodeEntry e : entry.getChildren()) { if (!e.isLink()) { filter.apply(buf, e.getName(), null, 0); } } return 0; } @Override public int read(String path, Pointer buf, long size, long offset, FuseFileInfo fi) { Optional<NodeEntry> entryopt = FSTUtils.getFSTEntryByFullPath(getDataProvider().getRoot(), path); if (entryopt.isPresent() && !entryopt.get().isLink() && entryopt.get().isFile()) { FileEntry entry = (FileEntry) entryopt.get(); if (offset >= entry.getSize()) { return 0; } if (offset + size > entry.getSize()) { size = entry.getSize() - offset; } if (size > Integer.MAX_VALUE) { System.err.println("Request read size was too big."); return -ErrorCodes.EIO(); } try { byte[] data; if (offset % 16 > 0) { // make sure the offset is aligned to 0x10; // in worst case we read 15 additional bytes- long newOffset = (offset / 16) * 16; int diff = (int) (offset - newOffset); data = getDataProvider().readFile(entry, newOffset, size + diff); buf.put(0, data, diff, data.length - diff); return (int) (data.length > size ? size : data.length); } else { data = getDataProvider().readFile(entry, offset, size); buf.put(0, data, 0, data.length); return data.length; } } catch (Exception e) { e.printStackTrace(); return -ErrorCodes.ENOENT(); } } else { System.out.println("Path not found:" + path); return -ErrorCodes.ENOENT(); } } @Override public void init() { } @Override public void deinit() { } }
5,436
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
MultipleFSTDataProviderFuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/MultipleFSTDataProviderFuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FSTDataProviderLoader; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import lombok.val; import java.io.File; import java.util.List; import java.util.Optional; public class MultipleFSTDataProviderFuseContainer<T> extends GroupFuseContainer { private final File file; private final FSTDataProviderLoader<T> loader; private int i = 0; public MultipleFSTDataProviderFuseContainer(Optional<FuseDirectory> parent, File file, FSTDataProviderLoader<T> loader) { super(parent); this.file = file; this.loader = loader; } @Override protected void doInit() { Optional<T> infoOpt = loader.loadInfo(file); if (infoOpt.isPresent()) { parseContents(loader.getDataProvider(infoOpt.get())); } else { System.err.println("Failed to parse " + file.getAbsolutePath()); } } void parseContents(List<FSTDataProvider> dps) { for (val dp : dps) { this.addFuseContainer(dp.getName() + "_" + (++i), new FSTDataProviderContainer(getParent(), dp)); } } }
1,240
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
WoomyNUSTitleContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/WoomyNUSTitleContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.NUSTitleLoaderWoomy; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.implementations.FSTDataProviderNUSTitle; import java.io.File; import java.util.Optional; public class WoomyNUSTitleContainer extends GroupFuseContainer { private final File file; public WoomyNUSTitleContainer(Optional<FuseDirectory> parent, File file) { super(parent); this.file = file; } @Override protected void doInit() { this.addFuseContainer(file.getName(), new FSTDataProviderContainer(Optional.of(this), () -> { try { return new FSTDataProviderNUSTitle(NUSTitleLoaderWoomy.loadNUSTitle(file.getAbsolutePath())); } catch (Exception e1) { e1.printStackTrace(); return null; } })); } }
917
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
GroupFuseContainerDefault.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/GroupFuseContainerDefault.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import java.util.Optional; /** * Default GroupFuseContainer implementation * * @author Maschell */ public class GroupFuseContainerDefault extends GroupFuseContainer { public GroupFuseContainerDefault(Optional<FuseDirectory> parent) { super(parent); } @Override protected void doInit() { } }
440
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
WUDToWUDContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/WUDToWUDContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.fuse_wiiu.utils.WUDUtils; import de.mas.wiiu.jnus.implementations.wud.WUDImage; import de.mas.wiiu.jnus.implementations.wud.WiiUDisc; import jnr.ffi.Pointer; import ru.serce.jnrfuse.ErrorCodes; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; import java.io.File; import java.io.IOException; import java.util.Optional; public class WUDToWUDContainer implements FuseContainer { private final String filename; private final Optional<WiiUDisc> wudInfo; private final Optional<FuseDirectory> parent; public WUDToWUDContainer(Optional<FuseDirectory> parent, File c) { this.wudInfo = WUDUtils.loadWUDInfo(c); this.parent = parent; this.filename = c.getName().replace("_part1.", ".").replace(".wux", ".wud"); } @Override public Optional<FuseDirectory> getParent() { return parent; } @Override public int getattr(String path, FileStat stat) { if (path.equals("/")) { stat.st_mode.set(FileStat.S_IFDIR | 0755); stat.st_nlink.set(2); return 0; } if (path.equals("/" + filename)) { if (stat != null) { stat.st_mode.set(FileStat.S_IFREG | FileStat.ALL_READ); stat.st_nlink.set(1); stat.st_size.set(WUDImage.WUD_FILESIZE); } return 0; } return -ErrorCodes.ENOENT(); } @Override public int open(String path, FuseFileInfo fi) { if (path.equals("/")) { return -ErrorCodes.EISDIR(); } return getattr(path, null); } @Override public int readdir(String path, Pointer buf, FuseFillDir filter, long offset, FuseFileInfo fi) { filter.apply(buf, ".", null, 0); if (getParent().isPresent()) { filter.apply(buf, "..", null, 0); } if (wudInfo.isPresent()) { filter.apply(buf, filename, null, 0); } return 0; } @Override public int read(String path, Pointer buf, long size, long offset, FuseFileInfo fi) { if (path.equals("/")) { return -ErrorCodes.EISDIR(); } if (!path.equals("/" + filename)) { return -ErrorCodes.ENOENT(); } if (offset >= WUDImage.WUD_FILESIZE) { return -ErrorCodes.ENOENT(); } if (offset + size > WUDImage.WUD_FILESIZE) { size = WUDImage.WUD_FILESIZE - offset; } try { byte[] data; data = wudInfo.get().getReader().get().readEncryptedToByteArray(offset, 0, size); buf.put(0, data, 0, data.length); return data.length; } catch (IOException e) { e.printStackTrace(); return -ErrorCodes.ENOENT(); } } @Override public void init() { // Not used } @Override public void deinit() { // Not used } }
3,201
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
WUDFSTDataProviderLoader.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/loader/WUDFSTDataProviderLoader.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation.loader; import de.mas.wiiu.jnus.WUDLoader; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FSTDataProviderLoader; import de.mas.wiiu.jnus.fuse_wiiu.utils.WUDUtils; import de.mas.wiiu.jnus.implementations.wud.WiiUDisc; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import lombok.Getter; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class WUDFSTDataProviderLoader implements FSTDataProviderLoader<WiiUDisc> { @Getter private static final WUDFSTDataProviderLoader instance = new WUDFSTDataProviderLoader(); private WUDFSTDataProviderLoader() { } @Override public List<FSTDataProvider> getDataProvider(WiiUDisc info) { List<FSTDataProvider> dps = new ArrayList<>(); try { dps = WUDLoader.getPartitonsAsFSTDataProvider(info, Settings.retailCommonKey); } catch (Exception e) { try { dps = WUDLoader.getPartitonsAsFSTDataProvider(info, Settings.devCommonKey); } catch (IOException | ParseException e1) { return dps; } } return dps; } @Override public Optional<WiiUDisc> loadInfo(File input) { return WUDUtils.loadWUDInfo(input); } }
1,419
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
WumadFSTDataProviderLoader.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/implementation/loader/WumadFSTDataProviderLoader.java
package de.mas.wiiu.jnus.fuse_wiiu.implementation.loader; import de.mas.wiiu.jnus.WumadLoader; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FSTDataProviderLoader; import de.mas.wiiu.jnus.implementations.wud.wumad.WumadInfo; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import lombok.Getter; import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class WumadFSTDataProviderLoader implements FSTDataProviderLoader<WumadInfo> { @Getter private static final WumadFSTDataProviderLoader instance = new WumadFSTDataProviderLoader(); private WumadFSTDataProviderLoader() { } @Override public Optional<WumadInfo> loadInfo(File input) { if (input != null && input.exists()) { try { return Optional.of(WumadLoader.load(input)); } catch (Exception e) { e.printStackTrace(); } } return Optional.empty(); } @Override public List<FSTDataProvider> getDataProvider(WumadInfo info) { List<FSTDataProvider> dps = new ArrayList<>(); try { dps = WumadLoader.getPartitonsAsFSTDataProvider(info, Settings.retailCommonKey); } catch (Exception e) { try { dps = WumadLoader.getPartitonsAsFSTDataProvider(info, Settings.devCommonKey); } catch (IOException | ParseException e1) { return dps; } } return dps; } }
1,605
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FuseContainerWrapper.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/utils/FuseContainerWrapper.java
package de.mas.wiiu.jnus.fuse_wiiu.utils; import de.mas.wiiu.jnus.fuse_wiiu.implementation.*; import de.mas.wiiu.jnus.fuse_wiiu.implementation.loader.WUDFSTDataProviderLoader; import de.mas.wiiu.jnus.fuse_wiiu.implementation.loader.WumadFSTDataProviderLoader; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseContainer; import de.mas.wiiu.jnus.fuse_wiiu.interfaces.FuseDirectory; import de.mas.wiiu.jnus.implementations.wud.reader.WUDDiscReaderSplitted; import de.mas.wiiu.jnus.utils.Utils; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class FuseContainerWrapper { private final static String prefix = "[EMULATED] "; public static Map<String, FuseContainer> createFuseContainer(Optional<FuseDirectory> parent, File c) { System.out.println("Mounting " + c.getAbsolutePath()); Map<String, FuseContainer> result = new HashMap<>(); if (c.exists() && c.isDirectory()) { File[] tmd = c.listFiles(f -> f.isFile() && f.getName().startsWith("tmd")); File[] appFiles = c.listFiles(f -> f.isFile() && f.getName().startsWith("000") && f.getName().length() == 8); if (tmd != null && tmd.length > 0 && appFiles != null && appFiles.length > 0) { result.put(prefix + c.getName(), new RemoteLocalBackupNUSTitleContainer(parent, c)); return result; } } if (c.exists() && c.isDirectory()) { File[] tmd = c.listFiles(f -> f.isFile() && (f.getName().startsWith("tmd.") || f.getName().startsWith("title.tmd"))); if (tmd != null && tmd.length > 0) { // In case there is a tmd file // Checks if we have the local backup format File[] versions = c.listFiles(f -> f.getName().startsWith("tmd.")); if (versions != null && versions.length > 0 && c.getName().length() == 16 && Utils.StringToLong(c.getName()) > 0) { result.put(prefix + c.getName(), new LocalBackupNUSTitleContainer(parent, c)); return result; } // if not return normal title container. result.put(prefix + c.getName(), new LocalNUSTitleContainer(parent, c)); return result; } } if (c.exists() && c.getName().endsWith(".woomy")) { result.put(prefix + c.getName(), new WoomyNUSTitleContainer(parent, c)); return result; } if (c.exists() && c.getName().endsWith(".wumad")) { result.put(prefix + c.getName(), new MultipleFSTDataProviderFuseContainer<>(parent, c, WumadFSTDataProviderLoader.getInstance())); result.put(prefix + "[EXTRA] " + c.getName(), new MultipleFSTDataProviderRecursiveFuseContainer<>(parent, c, WumadFSTDataProviderLoader.getInstance())); return result; } if (checkWUD(result, parent, c)) { return result; } if (c.isDirectory()) { result.put(c.getName(), new FSFuseContainer(parent, c)); return result; } return result; } private static boolean checkWUD(Map<String, FuseContainer> result, Optional<FuseDirectory> parent, File c) { if (c.exists() && c.isFile() && (c.getName().endsWith(".wux") || c.getName().endsWith(".wud") || c.getName().endsWith(".ddi") || c.getName().endsWith(".wumada"))) { if (c.length() == WUDDiscReaderSplitted.WUD_SPLITTED_FILE_SIZE && !c.getName().endsWith("part1.wud")) { return false; } result.put(prefix + c.getName(), new MultipleFSTDataProviderFuseContainer<>(parent, c, WUDFSTDataProviderLoader.getInstance())); result.put(prefix + "[EXTRA] " + c.getName(), new MultipleFSTDataProviderRecursiveFuseContainer<>(parent, c, WUDFSTDataProviderLoader.getInstance())); if (c.getName().endsWith("part1.wud") || c.getName().endsWith(".wux")) { result.put(prefix + "[WUD] " + c.getName(), new WUDToWUDContainer(parent, c)); } return true; } return false; } }
4,177
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
WUDUtils.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/utils/WUDUtils.java
package de.mas.wiiu.jnus.fuse_wiiu.utils; import de.mas.wiiu.jnus.WUDLoader; import de.mas.wiiu.jnus.fuse_wiiu.Settings; import de.mas.wiiu.jnus.implementations.wud.WiiUDisc; import org.apache.commons.io.FilenameUtils; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Optional; public class WUDUtils { public static Optional<WiiUDisc> loadWUDInfo(File file) { String FSfilename = file.getName(); String basename = FilenameUtils.getBaseName(FSfilename); File keyFile = new File(file.getParent() + File.separator + basename + ".key"); if (!keyFile.exists() && Settings.disckeyPath != null) { System.out.println(".key not found at " + keyFile.getAbsolutePath()); keyFile = new File(Settings.disckeyPath.getAbsoluteFile() + File.separator + basename + ".key"); if (!keyFile.exists()) { System.out.println(".key not found at " + keyFile.getAbsolutePath()); } } try { if (keyFile.exists()) { return Optional.of(WUDLoader.load(file.getAbsolutePath(), keyFile)); } else { System.out.println("No .key was not found. Trying dev mode."); return Optional.of(WUDLoader.loadDev(file.getAbsolutePath())); } } catch (Exception e) { e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); System.err.println(errors); } return Optional.empty(); } }
1,610
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
TicketUtils.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/utils/TicketUtils.java
package de.mas.wiiu.jnus.fuse_wiiu.utils; import de.mas.wiiu.jnus.entities.Ticket; import de.mas.wiiu.jnus.utils.FileUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Optional; public class TicketUtils { public static Optional<Ticket> getTicket(File folder, File keyFolder, long titleID, byte[] commonKey) { File ticketFile = null; if (folder != null) { ticketFile = FileUtils.getFileIgnoringFilenameCases(folder.getAbsolutePath(), "title.tik"); } if (ticketFile == null) { ticketFile = FileUtils.getFileIgnoringFilenameCases(folder.getAbsolutePath(), "cetk"); } Ticket ticket = null; if (ticketFile != null && ticketFile.exists()) { try { ticket = Ticket.parseTicket(ticketFile, commonKey); } catch (IOException e) { } } if (ticket == null && keyFolder != null) { File keyFile = FileUtils.getFileIgnoringFilenameCases(keyFolder.getAbsolutePath(), String.format("%016X", titleID) + ".key"); if (keyFile != null && keyFile.exists()) { byte[] key; try { key = Files.readAllBytes(keyFile.toPath()); if (key != null && key.length == 16) { ticket = Ticket.createTicket(key, titleID, commonKey); } } catch (IOException e) { } } } if (ticket != null) { return Optional.of(ticket); } return Optional.empty(); } }
1,644
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FuseContainer.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/interfaces/FuseContainer.java
package de.mas.wiiu.jnus.fuse_wiiu.interfaces; import jnr.ffi.Pointer; import jnr.ffi.types.off_t; import jnr.ffi.types.size_t; import ru.serce.jnrfuse.FuseFillDir; import ru.serce.jnrfuse.struct.FileStat; import ru.serce.jnrfuse.struct.FuseFileInfo; /** * Simplified version of the FuseFS interface. * * @author Maschell */ public interface FuseContainer extends FuseDirectory { /** * Wrapper for the getattr function of the FuseFS interface. * When this function is called, the path will be relative to this FuseContainer * <p> * Get file attributes. * <p> * Similar to stat(). The 'st_dev' and 'st_blksize' fields are * ignored. The 'st_ino' field is ignored except if the 'use_ino' * mount option is given. */ int getattr(String path, FileStat stat); /** * Wrapper for the getattr function of the FuseFS interface. * When this function is called, the path will be relative to this FuseContainer * <p> * File open operation * <p> * No creation (O_CREAT, O_EXCL) and by default also no * truncation (O_TRUNC) flags will be passed to open(). If an * application specifies O_TRUNC, fuse first calls truncate() * and then open(). Only if 'atomic_o_trunc' has been * specified and kernel version is 2.6.24 or later, O_TRUNC is * passed on to open. * <p> * Unless the 'default_permissions' mount option is given, * open should check if the operation is permitted for the * given flags. Optionally open may also return an arbitrary * filehandle in the fuse_file_info structure, which will be * passed to all file operations. * * @see jnr.constants.platform.OpenFlags */ int open(String path, FuseFileInfo fi); /** * Wrapper for the readdir function of the FuseFS interface. * When this function is called, the path will be relative to this FuseContainer * <p> * Read directory * <p> * This supersedes the old getdir() interface. New applications * should use this. * <p> * The filesystem may choose between two modes of operation: * <p> * 1) The readdir implementation ignores the offset parameter, and * passes zero to the filler function's offset. The filler * function will not return '1' (unless an error happens), so the * whole directory is read in a single readdir operation. This * works just like the old getdir() method. * <p> * 2) The readdir implementation keeps track of the offsets of the * directory entries. It uses the offset parameter and always * passes non-zero offset to the filler function. When the buffer * is full (or an error happens) the filler function will return * '1'. */ int readdir(String path, Pointer buf, FuseFillDir filter, @off_t long offset, FuseFileInfo fi); /** * Wrapper for the getattr function of the FuseFS interface. * When this function is called, the path will be relative to this FuseContainer * <p> * Read data from an open file * <p> * Read should return exactly the number of bytes requested except * on EOF or error, otherwise the rest of the data will be * substituted with zeroes. An exception to this is when the * 'direct_io' mount option is specified, in which case the return * value of the read system call will reflect the return value of * this operation. */ int read(String path, Pointer buf, @size_t long size, @off_t long offset, FuseFileInfo fi); /** * This function will be called when ever the FuseContainer needs to update it's children. */ void init(); /** * This function will be called right before this FuseContainer won't be used anymore. */ void deinit(); }
3,833
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FSTDataProviderLoader.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/interfaces/FSTDataProviderLoader.java
package de.mas.wiiu.jnus.fuse_wiiu.interfaces; import de.mas.wiiu.jnus.interfaces.FSTDataProvider; import java.io.File; import java.util.List; import java.util.Optional; public interface FSTDataProviderLoader<T> { Optional<T> loadInfo(File input); List<FSTDataProvider> getDataProvider(T info); }
309
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
FuseDirectory.java
/FileExtraction/Java_unseen/Maschell_fuse-wiiu/src/main/java/de/mas/wiiu/jnus/fuse_wiiu/interfaces/FuseDirectory.java
package de.mas.wiiu.jnus.fuse_wiiu.interfaces; import java.util.Optional; /** * Representation of a directory. * * @author Maschell */ public interface FuseDirectory { /** * Returns the parent of this FuseDirectory. * * @return parent */ Optional<FuseDirectory> getParent(); }
312
Java
.java
Maschell/fuse-wiiu
41
1
1
2019-04-11T20:27:07Z
2022-02-01T23:22:46Z
AppTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/AppTest.java
package com.walle; import org.junit.Test; /** * Unit test for simple App. */ public class AppTest { @Test public void testApp() { App.main(null); } }
174
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
LocationUtilTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/http/LocationUtilTest.java
package com.walle.http; import com.alibaba.fastjson.JSONObject; import com.walle.util.LogUtil; import org.junit.Assert; import org.junit.Test; public class LocationUtilTest { @Test public void testGetLocation() { /* { "regionCode": "0", "regionNames": "", "proCode": "310000", "err": "", "city": "上海市", "cityCode": "310000", "ip": "101.229.196.154", "pro": "上海市", "region": "", "addr": "上海市 电信" } */ JSONObject ret = LocationUtil.getLocation(); LogUtil.info(ret); Assert.assertNotNull(ret); } }
708
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
HttpUtilTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/http/HttpUtilTest.java
package com.walle.http; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.walle.util.B64Util; import com.walle.util.LogUtil; import com.walle.util.StrUtil; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class HttpUtilTest { @Test public void testHttpGet() { String html = HttpUtil.sendHttpGet("https://blog.51cto.com/13851865"); String[] ret = StrUtil.parse(html, "<span>[1-9]\\d*</span>"); LogUtil.info(ret); Assert.assertNotNull(ret); } @Test public void testHttpForm() { String url = "https://openapi.baidu.com/oauth/2.0/token"; Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("grant_type", "client_credentials"); // 固定为“client_credentials” put("client_id", "kVcnfD9iW2XVZSMaLMrtLYIz"); // 应用的API Key put("client_secret", "O9o1O213UgG5LFn0bDGNtoRN3VWl2du6"); // 应用的Secret Key }}; JSONObject ret = HttpUtil.sendHttpForm(url, headers, params, new RespJsonObj()); LogUtil.info(ret); Assert.assertNotNull(ret); String token = ret.getString("access_token"); LogUtil.info(token); testBaiduTts(token); } public void testBaiduTts(final String token) { String url = "https://tsn.baidu.com/text2audio"; Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/x-www-form-urlencoded"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("tex", UrlUtil.encode("调用百度AI语音处理")); // 合成文本,UTF-8编码,2048个中文字或者英文数字 put("tok", token); // 调用鉴权认证接口获取到的access_token put("cuid", "walle_http_util"); // 用户唯一标识,用来计算UV值,长度为60字符,常用用户MAC地址或IMEI码 put("ctp", "1"); // 客户端类型选择,web端填写固定值1 put("lan", "zh"); // 语言选择,目前只有中英文混合模式,固定值zh put("spd", "6"); // 语速,取值0-15,默认为5中语速 put("pit", "5"); // 音调,取值0-15,默认为5中语调 put("vol", "5"); // 音量,取值0-15,默认为5中音量 put("per", "1"); // 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫 put("aue", "6"); // 3为mp3格式(默认); 4为pcm-16k;5为pcm-8k;6为wav(内容同pcm-16k) }}; RespData resp = new RespData(); byte[] ret = HttpUtil.sendHttpForm(url, headers, params, resp); Assert.assertNotNull(ret); String file = resp.saveFile(String.format("http_util_test.%s", resp.getFileExt())); LogUtil.info(file); long len = resp.getContentLength(); String b64Str = B64Util.encode(resp.getBytes()); String format = resp.getFileExt(); testBaiduAsr(token, format, b64Str, len); } public void testBaiduAsr(final String token, final String format, final String b64Data, final long len) { String url = "http://vop.baidu.com/server_api"; Map<String, String> headers = new HashMap<String, String>() {{ put("Content-Type", "application/json"); }}; Map<String, Object> params = new HashMap<String, Object>() {{ put("format", format); // 音频格式:pcm/wav/amr/m4a,推荐pcm put("rate", 16000); // 音频采样频率,固定值16000 put("dev_pid", 1537); // 语音模型,默认1537普通话,1737英语 put("channel", 1); // 声道数量,仅支持单声道1 put("cuid", "walle_http_util"); // 用户唯一标识,用来计算UV值,长度为60字符,常用用户MAC地址或IMEI码 put("token", token); // 调用鉴权认证接口获取到的access_token put("len", len); // 音频长度,base64前 put("speech", b64Data); // 音频数据,base64(FILE_CONTENT) }}; JSONObject ret = HttpUtil.sendHttpPost(url, headers, params, new RespJsonObj()); LogUtil.info(ret); Assert.assertNotNull(ret); JSONArray textArr = ret.getJSONArray("result"); LogUtil.info(textArr); Assert.assertNotNull(textArr); } }
4,608
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
PlayerTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/audio/PlayerTest.java
package com.walle.audio; import org.junit.Test; import java.net.URL; public class PlayerTest { static boolean isPlaying = true; @Test public void testPlayUrl() throws Exception { URL fileUrl = new URL("http://q671m4cqj.bkt.clouddn.com/a0cd7e78db4dcc2149e7a556531094828.wav"); Player.asyncPlay(fileUrl, new TimeListener() { public void timeUpdated(long seconds) { } public void stopped(long seconds) { System.out.printf("player stopped: %d\n", seconds); synchronized (Player.class) { isPlaying = false; } } }); isPlaying = true; while (true) { Thread.sleep(1000); synchronized (Player.class) { if (!isPlaying) { break; } } } } }
902
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
RecordHelperTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/audio/RecordHelperTest.java
package com.walle.audio; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.File; public class RecordHelperTest { static boolean isRecording = false; static boolean isPlaying = false; @Test public void testRecord() throws Exception { RecordHelper recordHelper = RecordHelper.getInst(); // Record recordHelper.record(new TimeListener() { public void timeUpdated(long seconds) { } public void stopped(long seconds) { System.out.printf("recorder stopped: %d\n", seconds); synchronized (Player.class) { isRecording = false; } } }, null); recordHelper.stop(5000); isRecording = true; while (true) { Thread.sleep(1000); synchronized (Player.class) { if (!isRecording) { break; } } } // save ByteArrayOutputStream ret = recordHelper.save(new ByteArrayOutputStream()); System.out.printf("data: %d\n", ret == null ? 0 : ret.size()); File file = recordHelper.save(new File("rec.wav")); System.out.println(file.getName()); // play recordHelper.play(new TimeListener() { public void timeUpdated(long seconds) { } public void stopped(long seconds) { System.out.printf("player stopped: %d\n", seconds); synchronized (Player.class) { isPlaying = false; } } }); isPlaying = true; while (true) { Thread.sleep(1000); synchronized (Player.class) { if (!isPlaying) { break; } } } } }
1,881
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
MacUtilTest.java
/FileExtraction/Java_unseen/jextop_aiChat/src/test/java/com/walle/util/MacUtilTest.java
package com.walle.util; import org.junit.Assert; import org.junit.Test; public class MacUtilTest { @Test public void testGetMacAddr() { String ret = MacUtil.gtMacAddr(); System.out.println(ret); Assert.assertNotNull(ret); } }
264
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
ChatFrame.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/ChatFrame.java
package com.walle; import com.walle.audio.ChatUtil; import com.walle.audio.RecordHelper; import com.walle.audio.TimeListener; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ChatFrame { private static final long MS_DURATION = 5000; private static final String RECORD = " 请讲话"; private static final String PLAY = " --------"; private static boolean isChatting = false; private static JButton recordBtn; private static JLabel recordLbl; private static TimeListener playerListener; private static TimeListener recorderListener; static { recordBtn = new JButton("开始聊天"); recordLbl = new JLabel(PLAY); recordBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { synchronized (ChatFrame.class) { isChatting = !isChatting; recordBtn.setText(isChatting ? "结束聊天" : "开始聊天"); RecordHelper recordHelper = RecordHelper.getInst(); if (isChatting) { recordHelper.record(recorderListener, MS_DURATION); } else { recordHelper.stop(); } } } }); recorderListener = new TimeListener() { @Override public void timeUpdated(long seconds) { recordLbl.setText(String.format("%s(%d)", RECORD, MS_DURATION / 1000 - seconds)); } @Override public void stopped(long seconds) { recordLbl.setText(PLAY); synchronized (ChatFrame.class) { if (isChatting) { ChatUtil.chat(playerListener); } } } }; playerListener = new TimeListener() { @Override public void timeUpdated(long seconds) { } @Override public void stopped(long seconds) { synchronized (ChatFrame.class) { if (isChatting) { recordLbl.setText(String.format("%s(%d)", RECORD, MS_DURATION / 1000)); RecordHelper recordHelper = RecordHelper.getInst(); recordHelper.record(recorderListener, MS_DURATION); } } } }; } public static JFrame showFrame() { // create frame final JFrame frame = new JFrame("aiChat - 智能语音聊天机器人"); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setResizable(false); Box chatBox = Box.createVerticalBox(); chatBox.add(recordBtn); chatBox.add(recordLbl); // create panel JPanel panel = new JPanel(); panel.add(Box.createVerticalStrut(150)); panel.add(chatBox); // show panel frame.setContentPane(panel); frame.setVisible(true); // do work frame.getRootPane().setDefaultButton(recordBtn); recordBtn.doClick(); return frame; } }
3,357
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
App.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/App.java
package com.walle; public class App { public static void main(String[] args) { ChatFrame.showFrame(); } }
123
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
UrlUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/UrlUtil.java
package com.walle.http; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class UrlUtil { public static String encode(String str) { if (str == null) { return null; } try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String decode(String str) { if (str == null) { return null; } try { return URLDecoder.decode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } }
745
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
RespJsonObj.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/RespJsonObj.java
package com.walle.http; import com.alibaba.fastjson.JSONObject; import com.walle.util.JsonUtil; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.Charset; public class RespJsonObj implements ResponseHandler<JSONObject> { @Override public JSONObject handleResponse(HttpResponse resp) throws IOException { HttpEntity entity = resp.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } // read content ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); String jsonStr = EntityUtils.toString(entity, charset == null ? Charset.forName("utf-8") : charset); // parse JSON object return JsonUtil.parseObj(jsonStr); } }
1,075
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
HttpUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/HttpUtil.java
package com.walle.http; import com.walle.util.JsonUtil; import com.walle.util.LogUtil; import com.walle.util.StrUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import java.io.File; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; public class HttpUtil { private static final String CHARSET_UTF_8 = "utf-8"; private static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8"; private static final String CONTENT_TYPE_JSON = "application/json;charset=utf-8"; private static final int MAX_TOTAL = 100; private static final int MAX_PER_ROUTE = 20; private static final int SOCKET_TIMEOUT = 10000; private static final int CONNECT_TIMEOUT = 10000; private static final int REQUEST_TIMEOUT = 10000; private static PoolingHttpClientConnectionManager connectionPool; private static RequestConfig requestConfig; static { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); connectionPool = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionPool.setMaxTotal(MAX_TOTAL); connectionPool.setDefaultMaxPerRoute(MAX_PER_ROUTE); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } requestConfig = RequestConfig.custom() .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(CONNECT_TIMEOUT) .setConnectionRequestTimeout(REQUEST_TIMEOUT) .build(); } private static CloseableHttpClient getHttpClient() { return HttpClients.custom() .setConnectionManager(connectionPool) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .build(); } private static <T> T sendHttpRequest(HttpRequestBase httpRequest, ResponseHandler<T> handler) { try { return getHttpClient().execute(httpRequest, handler); } catch (ClientProtocolException e) { LogUtil.error("Error when sendHttpRequest", e.getMessage()); } catch (IOException e) { LogUtil.error("Error when sendHttpRequest", e.getMessage()); } return null; } public static <T> T sendHttpGet(String httpUrl, ResponseHandler<T> handler) { HttpGet httpGet = new HttpGet(httpUrl); return sendHttpRequest(httpGet, handler); } public static String sendHttpGet(String httpUrl) { return sendHttpGet(httpUrl, new RespStr()); } public static <T> T sendHttpGet(String httpUrl, Map<String, String> headers, ResponseHandler<T> handler) { HttpGet httpGet = new HttpGet(httpUrl); fillHeaders(httpGet, headers); return sendHttpRequest(httpGet, handler); } public static String sendHttpGet(String httpUrl, Map<String, String> headers) { HttpGet httpGet = new HttpGet(httpUrl); fillHeaders(httpGet, headers); return sendHttpRequest(httpGet, new RespStr()); } public static <T> T sendHttpGet(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { if (!MapUtils.isEmpty(params)) { List<String> paramList = new ArrayList<String>(); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { paramList.add(String.format("%s=%s", param.getKey(), UrlUtil.encode(String.valueOf(value)))); } } String paramStr = StrUtil.join(paramList, "&"); httpUrl = String.format("%s%s%s", httpUrl, httpUrl.indexOf("?") > 0 ? "&" : "?", paramStr); } return sendHttpGet(httpUrl, headers, handler); } public static String sendHttpGet(String httpUrl, Map<String, String> headers, Map<String, Object> params) { return sendHttpGet(httpUrl, headers, params, new RespStr()); } public static <T> T sendHttpPost(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (!MapUtils.isEmpty(params)) { String jsonStr = JsonUtil.toStr(params); StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); stringEntity.setContentType(CONTENT_TYPE_JSON); httpPost.setEntity(stringEntity); } return sendHttpRequest(httpPost, handler); } public static String sendHttpPost(String httpUrl, Map<String, String> headers, Map<String, Object> params) { return sendHttpPost(httpUrl, headers, params, new RespStr()); } public static <T> T sendHttpPost(String httpUrl, Map<String, String> headers, Map<String, Object> params, File file, ResponseHandler<T> handler) { File[] files = new File[]{file}; return sendHttpPost(httpUrl, headers, params, Arrays.asList(files), handler); } public static <T> T sendHttpPost(String httpUrl, Map<String, String> headers, Map<String, Object> params, Collection<File> files, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); if (!MapUtils.isEmpty(params)) { for (String key : params.keySet()) { Object value = params.get(key); if (value != null) { meBuilder.addPart(key, new StringBody(String.valueOf(value), ContentType.TEXT_PLAIN)); } } } if (!CollectionUtils.isEmpty(files)) { for (File file : files) { meBuilder.addBinaryBody("file", file); } } HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpRequest(httpPost, handler); } public static <T> T sendHttpForm(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPost httpPost = new HttpPost(httpUrl); fillHeaders(httpPost, headers); if (!MapUtils.isEmpty(params)) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> param : params.entrySet()) { Object value = param.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(value))); } } try { httpPost.setEntity(new UrlEncodedFormEntity(pairs)); } catch (Exception e) { LogUtil.error("Error when sendHttpSubmit", e.getMessage()); } } return sendHttpRequest(httpPost, handler); } public static <T> T sendHttpPut(String httpUrl, Map<String, String> headers, Map<String, Object> params, ResponseHandler<T> handler) { HttpPut httpPut = new HttpPut(httpUrl); fillHeaders(httpPut, headers); if (!MapUtils.isEmpty(params)) { String jsonStr = JsonUtil.toStr(params); StringEntity stringEntity = new StringEntity(jsonStr, "UTF-8"); stringEntity.setContentType(CONTENT_TYPE_JSON); httpPut.setEntity(stringEntity); } return sendHttpRequest(httpPut, handler); } public static <T> T sendHttpDelete(String httpUrl, Map<String, String> headers, ResponseHandler<T> handler) { HttpDelete httpDelete = new HttpDelete(httpUrl); fillHeaders(httpDelete, headers); return sendHttpRequest(httpDelete, handler); } private static void fillHeaders(HttpRequestBase request, Map<String, String> headers) { if (request == null || MapUtils.isEmpty(headers)) { return; } for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } }
10,473
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
RespStr.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/RespStr.java
package com.walle.http; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.entity.ContentType; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.Charset; public class RespStr implements ResponseHandler<String> { @Override public String handleResponse(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } // 读取返回内容 ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); return EntityUtils.toString(entity, charset == null ? Charset.forName("utf-8") : charset); } }
930
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
LocationUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/LocationUtil.java
package com.walle.http; import com.alibaba.fastjson.JSONObject; import com.walle.util.JsonUtil; import com.walle.util.StrUtil; import org.apache.commons.lang3.ArrayUtils; public class LocationUtil { private static JSONObject location = null; public static JSONObject getLocation() { if (location == null) { synchronized (LocationUtil.class) { if (location == null) { location = getLoc(); } } } return location; } private static JSONObject getLoc() { String address = HttpUtil.sendHttpGet("http://whois.pconline.com.cn/ipJson.jsp"); if (StrUtil.isEmpty(address)) { return null; } String[] jsonStrArr = StrUtil.parse(address, "\\{\"\\S*\\s*\\S*\"\\}"); return ArrayUtils.isEmpty(jsonStrArr) ? null : JsonUtil.parseObj(jsonStrArr[0]); } }
913
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
RespData.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/http/RespData.java
package com.walle.http; import com.walle.util.LogUtil; import com.walle.util.StrUtil; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class RespData implements ResponseHandler<byte[]> { private byte[] bytes; private String fileName; private String fileExt; private String contentType; private String contentLength; public byte[] getBytes() { return bytes; } public String getFileName() { return fileName; } public String getFileExt() { return fileExt; } public String getContentType() { return contentType; } public int getContentLength() { return StrUtil.isEmpty(contentLength) ? 0 : Integer.valueOf(contentLength); } public String saveFile(String filePath) { if (StrUtil.isEmpty(filePath)) { filePath = fileName; } if (StrUtil.isEmpty(filePath) || bytes == null || bytes.length <= 0) { return null; } // Check path File file = new File(filePath); String fileName = file.getName(); filePath = file.getParent(); file = new File(filePath == null ? "tmp" : filePath); if (!file.exists() && !file.mkdirs()) { return null; } // Write to disc Path path = Paths.get(file.getPath(), fileName); try { Files.write(path, bytes); } catch (IOException e) { LogUtil.error("Fail to save file: %s, %s\n", path.toString(), e.getMessage()); return null; } return path.toString(); } private String getHeader(HttpResponse response, String header) { return response.containsHeader(header) ? response.getFirstHeader(header).getValue() : null; } @Override public byte[] handleResponse(HttpResponse response) throws IOException { // 判断响应状态 if (response.getStatusLine().getStatusCode() >= 300) { throw new IOException("HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode()); } // 读取文件名称,Header: Content-Disposition: attachment;fileName=abc.txt String disposition = getHeader(response, "Content-Disposition"); if (!StrUtil.isEmpty(disposition) && disposition.contains("=")) { fileName = disposition.split("=")[1]; } // 读取ContentType: audio/mp3 contentType = getHeader(response, "Content-Type"); if (!StrUtil.isEmpty(contentType) && contentType.contains("/")) { fileExt = contentType.split("/")[1]; } contentLength = getHeader(response, "Content-Length"); // 读取返回内容 HttpEntity entity = response.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } bytes = EntityUtils.toByteArray(entity); return bytes; } }
3,272
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
ChatUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/ChatUtil.java
package com.walle.audio; import com.alibaba.fastjson.JSONObject; import com.walle.http.HttpUtil; import com.walle.http.LocationUtil; import com.walle.http.RespData; import com.walle.util.B64Util; import com.walle.util.MacUtil; import java.io.ByteArrayOutputStream; import java.util.HashMap; public class ChatUtil { public static void chat(TimeListener listener) { RecordHelper recordHelper = RecordHelper.getInst(); final ByteArrayOutputStream data = recordHelper.save(new ByteArrayOutputStream()); final JSONObject location = LocationUtil.getLocation(); RespData resp = new RespData(); byte[] ret = HttpUtil.sendHttpPost( "http://localhost:8011/speech/walle", null, new HashMap<String, Object>() {{ put("size", data.size()); put("format", "wav"); put("uid", MacUtil.gtMacAddr()); put("audio", B64Util.encode(data.toByteArray())); put("ip", location == null ? "" : location.getString("ip")); }}, resp ); System.out.printf("%s, %s, %s, %d, %d\n", resp.getContentType(), resp.getFileName(), resp.getFileExt(), resp.getContentLength(), ret == null ? 0 : ret.length ); if (ret != null && ret.length > 0) { Player.asyncPlay(ret, listener); } else { // 播放自己的声音吧 recordHelper.play(listener); } } }
1,524
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
Recorder.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/Recorder.java
package com.walle.audio; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.TargetDataLine; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; class Recorder implements Runnable { private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( 4, new BasicThreadFactory.Builder().namingPattern("audio-player-pool-%d").daemon(true).build() ); private static Long msDuration = null; private static Boolean isRecording = false; public static void record(ByteArrayOutputStream outputStream, TimeListener timeListener, Long millis) { System.out.println("Record thread"); synchronized (Recorder.class) { msDuration = millis; isRecording = true; } // 创建录音线程 Recorder recorder = new Recorder(outputStream, timeListener); executorService.execute(recorder); } public static void stop() { stop(0); } public static void stop(long millis) { synchronized (Recorder.class) { msDuration = millis; } } public static boolean isRecording() { synchronized (Recorder.class) { return isRecording; } } private ByteArrayOutputStream byteOutputStream; private TimeListener timeListener; private Recorder(ByteArrayOutputStream outputStream, TimeListener timeListener) { this.byteOutputStream = outputStream; this.timeListener = timeListener; } @Override public void run() { long msStart = System.currentTimeMillis(); System.out.printf("Record start, %s\n", new Date(msStart).toString()); TargetDataLine targetDataLine = null; try { AudioFormat audioFormat = FormatUtil.getAudioFormat(); DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); targetDataLine = (TargetDataLine) (AudioSystem.getLine(info)); targetDataLine.open(audioFormat); targetDataLine.start(); byte[] bytes = new byte[1024 * 8]; while (true) { int count = targetDataLine.read(bytes, 0, bytes.length); if (count > 0) { byteOutputStream.write(bytes, 0, count); } long ms = (System.currentTimeMillis() - msStart); System.out.printf("Record %d, seconds: %d, stopped: %s\n", count, ms / 1000, String.valueOf(msDuration)); if (timeListener != null) { timeListener.timeUpdated(ms / 1000); } synchronized (Recorder.class) { if (msDuration != null && ms >= msDuration) { break; } } } } catch (LineUnavailableException e) { System.err.println(e.getMessage()); } finally { if (targetDataLine != null) { targetDataLine.close(); } try { byteOutputStream.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } synchronized (Recorder.class) { isRecording = false; } long seconds = (System.currentTimeMillis() - msStart) / 1000; System.out.printf("Record stop, %s, seconds: %d\n", new Date().toString(), seconds); if (timeListener != null) { timeListener.stopped(seconds); } } }
3,908
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
RecordHelper.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/RecordHelper.java
package com.walle.audio; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; /** * @author Ding */ public class RecordHelper { private static RecordHelper inst = null; public static RecordHelper getInst() { if (inst == null) { synchronized (RecordHelper.class) { if (inst == null) { inst = new RecordHelper(); } } } return inst; } private ByteArrayOutputStream byteOutputStream = null; private RecordHelper() { } public void record(TimeListener timeListener, Long msDuration) { stop(); byteOutputStream = new ByteArrayOutputStream(); Recorder.record(byteOutputStream, timeListener, msDuration); } public void stop() { Recorder.stop(); } public void stop(long millis) { Recorder.stop(millis); } public boolean isRecording() { return Recorder.isRecording(); } public void play(TimeListener timeListener) { Player.asyncPlay(byteOutputStream, timeListener); } public <T> T save(T fileOrStream) { if (byteOutputStream == null || fileOrStream == null) { return fileOrStream; } // 录音输入流 byte[] audioBytes = byteOutputStream.toByteArray(); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(audioBytes); AudioFormat audioFormat = FormatUtil.getAudioFormat(); AudioInputStream audioInputStream = new AudioInputStream(byteInputStream, audioFormat, audioBytes.length / audioFormat.getFrameSize()); // 写入文件或OutputStream try { if (fileOrStream instanceof File) { AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, (File) fileOrStream); } else if (fileOrStream instanceof OutputStream) { AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, (OutputStream) fileOrStream); } } catch (IOException e) { System.err.println(e.getMessage()); } finally { try { audioInputStream.close(); byteInputStream.close(); } catch (Exception e) { System.err.println(e.getMessage()); } } return fileOrStream; } }
2,629
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
FormatUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/FormatUtil.java
package com.walle.audio; import javax.sound.sampled.AudioFormat; public class FormatUtil { public static AudioFormat getAudioFormat() { AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED; float rate = 16000f; int sampleSize = 16; int channels = 1; boolean bigEndian = true; return new AudioFormat(encoding, rate, sampleSize, channels, (sampleSize / 8) * channels, rate, bigEndian); } }
457
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
Player.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/Player.java
package com.walle.audio; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; class Player implements Runnable { private static ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor( 4, new BasicThreadFactory.Builder().namingPattern("audio-player-pool-%d").daemon(true).build() ); public static void asyncPlay(byte[] audioBytes, TimeListener listener) { if (audioBytes == null || audioBytes.length <= 0) { return; } ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); // 播放进程 Player player = new Player(); player.listener = listener; try { player.audioStream = AudioSystem.getAudioInputStream(audioStream); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } if (player.audioStream != null) { executorService.execute(player); } else { listener.stopped(0); } } public static void asyncPlay(URL fileUrl, TimeListener listener) { if (fileUrl == null) { return; } // 播放进程 Player player = new Player(); player.listener = listener; try { player.audioStream = AudioSystem.getAudioInputStream(fileUrl); } catch (UnsupportedAudioFileException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } executorService.execute(player); } public static void asyncPlay(ByteArrayOutputStream byteOutputStream, TimeListener listener) { if (byteOutputStream == null || byteOutputStream.size() <= 0) { return; } // 输入流 byte[] audioBytes = byteOutputStream.toByteArray(); int len = audioBytes.length; ByteArrayInputStream audioStream = new ByteArrayInputStream(audioBytes); AudioFormat audioFormat = FormatUtil.getAudioFormat(); // 播放进程 Player player = new Player(); player.listener = listener; player.audioFormat = audioFormat; player.audioStream = new AudioInputStream(audioStream, audioFormat, len / audioFormat.getFrameSize()); executorService.execute(player); } private AudioFormat audioFormat; private AudioInputStream audioStream; private TimeListener listener; private Player(){ } @Override public void run() { try { play(audioStream, audioFormat, listener); } catch (LineUnavailableException e) { System.err.println(e.getMessage()); } catch (IOException e) { System.err.println(e.getMessage()); } finally { if (audioStream != null) { try { audioStream.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } } } public static void play(AudioInputStream audioStream, AudioFormat audioFormat, TimeListener listener) throws IOException, LineUnavailableException { if (audioStream == null) { return; } if (audioFormat == null) { audioFormat = audioStream.getFormat(); } DataLine.Info lineInfo = new DataLine.Info(SourceDataLine.class, audioFormat); SourceDataLine dataLine = (SourceDataLine) AudioSystem.getLine(lineInfo); dataLine.open(audioFormat, 1024); dataLine.start(); long startTime = System.currentTimeMillis(); byte[] bytes = new byte[1024]; int count; while ((count = audioStream.read(bytes)) > 0) { dataLine.write(bytes, 0, count); if (listener != null) { listener.timeUpdated((System.currentTimeMillis() - startTime) / 1000); } } dataLine.drain(); dataLine.close(); if (listener != null) { listener.stopped((System.currentTimeMillis() - startTime) / 1000); } } }
4,817
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
TimeListener.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/audio/TimeListener.java
package com.walle.audio; public interface TimeListener { void timeUpdated(long seconds); void stopped(long seconds); }
128
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
LogUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/util/LogUtil.java
package com.walle.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogUtil { private static final Logger log = LoggerFactory.getLogger(LogUtil.class); public static void debug(Object... msg) { debug(log, msg); } public static void debug(Logger log, Object... msg) { log.debug(StrUtil.joinObj(msg, ", ")); } public static void info(Object... msg) { info(log, msg); } public static void info(Logger log, Object... msg) { log.info(StrUtil.joinObj(msg, ", ")); } public static void warn(Object... msg) { warn(log, msg); } public static void warn(Logger log, Object... msg) { log.warn(StrUtil.joinObj(msg, ", ")); } public static void error(Object... msg) { error(log, msg); } public static void error(Logger log, Object... msg) { log.error(StrUtil.joinObj(msg, ", ")); } }
938
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
B64Util.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/util/B64Util.java
package com.walle.util; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; public class B64Util { public static String encode(String str) { if (str == null) { return null; } try { return encode(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String encode(byte[] bytes) { return bytes == null ? null : Base64.encodeBase64String(bytes); } public static String decode(String str) { if (str == null) { return null; } byte[] bytes = decodeForBytes(str); try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static byte[] decodeForBytes(String str) { return str == null ? null : Base64.decodeBase64(str); } }
1,024
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
MacUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/util/MacUtil.java
package com.walle.util; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class MacUtil { private static String macAddress = null; public static String gtMacAddr() { if (macAddress == null) { synchronized (MacUtil.class) { if (macAddress == null) { try { Set<String> macSet = getMacSet(); Iterator<String> iterator = macSet.iterator(); if (iterator.hasNext()) { macAddress = iterator.next(); } } catch (SocketException e) { System.err.println(e.getMessage()); } } } } return macAddress; } private static Set<String> getMacSet() throws SocketException { Set<String> macSet = new HashSet<String>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); List<InterfaceAddress> addresses = networkInterface.getInterfaceAddresses(); for (InterfaceAddress address : addresses) { InetAddress ip = address.getAddress(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { continue; } byte[] mac = network.getHardwareAddress(); if (mac == null) { continue; } // 字节转成字符 StringBuilder sb = new StringBuilder(); for (int i = 0; i < mac.length; i++) { sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); } macSet.add(sb.toString()); } } return macSet; } }
2,219
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
StrUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/util/StrUtil.java
package com.walle.util; import org.apache.commons.collections4.CollectionUtils; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StrUtil { /** * String is null or empty */ public static boolean isEmpty(String str) { return isEmpty(str, true); } public static boolean isEmpty(String str, boolean trim) { return str == null || str.isEmpty() || (trim && str.trim().isEmpty()); } public static boolean chkLen(String str, int minLen, int maxLen) { return str != null && str.length() >= Math.max(minLen, 0) && str.length() <= Math.min(Math.max(maxLen, 0), 1024); } public static String mask(String str) { return mask(str, 1, 12); } public static String mask(String str, int minLen, int maxLen) { if (isEmpty(str)) { return ""; } str = str.trim().replace(" ", "") .replace("-", "") .replace("_", ""); if (str.length() <= minLen && minLen > 0) { return str; } // Remove the middle part if it's too long if (maxLen > 0) { if (maxLen % 2 != 0) { maxLen++; } if (str.length() > maxLen) { str = String.format("%s%s", str.substring(0, maxLen / 2), str.substring(str.length() - maxLen / 2, str.length()) ); } } // Divide 3 parts: str+mask+str final int len = str.length(); final int maskLen = len > 3 ? len / 3 : 1; StringBuilder sb = new StringBuilder(maskLen); for (int i = 0; i < maskLen; i++) { sb.append("*"); } int startLen = (len - maskLen) / 2; return String.format("%s%s%s", str.substring(0, startLen), sb.toString(), str.substring(startLen + maskLen, len) ); } public static boolean matches(String str, String pattern) { if (isEmpty(str) || isEmpty(pattern)) { return false; } Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(str); return m.matches(); } public static String[] parse(String str, String pattern) { if (isEmpty(str) || isEmpty(pattern)) { return null; } List<String> list = new ArrayList<String>(); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(str); while (m.find()) { list.add(m.group()); } if (list.size() <= 0) { return null; } String[] arr = new String[list.size()]; list.toArray(arr); return arr; } public static boolean contains(String str, String subStr) { return contains(str, subStr, ","); } public static boolean contains(String str, String subStr, String separator) { if (isEmpty(str) || isEmpty(subStr)) { return false; } if (subStr.equalsIgnoreCase(str)) { return true; } String[] strArray = split(str, separator); if (strArray == null) { return false; } for (String tmpStr : strArray) { if (tmpStr.trim().length() == 0 && subStr.trim().length() == 0) { return true; } if (tmpStr.trim().equalsIgnoreCase(subStr.trim())) { return true; } } return false; } public static String[] split(String str, String separator) { if (isEmpty(str) || isEmpty(separator)) { return null; } return str.split(separator); } public static String joinObj(Object[] objArr, String separator) { return objArr == null ? null : joinObj(Arrays.asList(objArr), separator); } public static String joinObj(Collection<Object> objList, String separator) { if (CollectionUtils.isEmpty(objList)) { return null; } List<String> strList = new ArrayList<String>(); for (Object obj : objList) { strList.add(obj == null ? "" : obj.toString()); } return join(strList, separator); } public static String join(String[] strArr, String separator) { return strArr == null ? null : join(Arrays.asList(strArr), separator); } public static String join(Collection<String> strList, String separator) { if (CollectionUtils.isEmpty(strList) || separator == null) { return null; } StringBuilder sb = new StringBuilder(); for (String str : strList) { sb.append(separator); sb.append(str); } return sb.substring(separator.length()); } /** * Get the bytes with UTF-8 */ public static byte[] getBytes(String str) { if (str == null) { return null; } try { return str.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String trimChinese(String str) { return isEmpty(str) ? "" : str.replaceAll("[\u4e00-\u9fa5]+", ""); } }
5,455
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
JsonUtil.java
/FileExtraction/Java_unseen/jextop_aiChat/src/main/java/com/walle/util/JsonUtil.java
package com.walle.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.List; public class JsonUtil { public static String toStr(Object javaObj) { return javaObj == null ? null : JSONObject.toJSONString(javaObj); } public static JSONObject parseObj(String jsonStr) { if (StrUtil.isEmpty(jsonStr)) { return null; } try { return JSONObject.parseObject(jsonStr); } catch (Exception e) { String msg = e.getMessage(); if (msg != null && msg.length() > 100) { msg = msg.substring(0, 100); } LogUtil.warn("Exception when parseJson", msg); } return null; } public static <T> T parseObj(String jsonStr, Class<T> clazz) { if (StrUtil.isEmpty(jsonStr)) { return null; } try { return JSONObject.parseObject(jsonStr, clazz); } catch (Exception e) { String msg = e.getMessage(); if (msg != null && msg.length() > 100) { msg = msg.substring(0, 100); } LogUtil.warn("Exception when parseObj", msg); } return null; } public static JSONArray parseArr(String jsonStr) { if (StrUtil.isEmpty(jsonStr)) { return null; } try { return JSONObject.parseArray(jsonStr); } catch (Exception e) { String msg = e.getMessage(); if (msg != null && msg.length() > 100) { msg = msg.substring(0, 100); } LogUtil.warn("Exception when parseJson", msg); } return null; } public static <T> List<T> parseArr(String jsonStr, Class<T> clazz) { if (StrUtil.isEmpty(jsonStr)) { return null; } try { return JSONObject.parseArray(jsonStr, clazz); } catch (Exception e) { String msg = e.getMessage(); if (msg != null && msg.length() > 100) { msg = msg.substring(0, 100); } LogUtil.warn("Exception when parseObj", msg); } return null; } }
2,241
Java
.java
jextop/aiChat
11
4
5
2019-12-08T02:53:28Z
2022-06-17T02:58:11Z
MainTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/MainTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class MainTest extends Main { @Test void shouldGetSafeLuaClassName() { registerClassOverride("Vector2", "JVector2"); Assertions.assertEquals("JVector2", getSafeLuaClassName("Vector2")); Assertions.assertEquals("JVector2[]", getSafeLuaClassName("Vector2[]")); // class names that are not overriden should return same name Assertions.assertEquals("MainTest", getSafeLuaClassName("MainTest")); } @TestOnly public static void registerClassOverride(String key, String value) { CLASS_OVERRIDES.put(key, value); } }
1,440
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
TestWorkspace.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/TestWorkspace.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.io.TempDir; import org.junit.platform.commons.util.StringUtils; @SuppressWarnings({ "WeakerAccess", "unused" }) public abstract class TestWorkspace { protected final String filename; protected File dir, file; public TestWorkspace(String filename) { this.filename = filename; } public TestWorkspace() { this.filename = "test.file"; } @BeforeEach void createTempFile(@TempDir Path dir) throws IOException { this.dir = dir.toFile(); file = dir.resolve(filename).toFile(); if (!StringUtils.isBlank(filename)) { Assertions.assertTrue(file.createNewFile()); } } protected List<String> readFile() throws IOException { return FileUtils.readLines(file, Main.CHARSET); } }
1,730
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaClassUtils.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/JavaClassUtils.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import java.util.ArrayList; import java.util.Map; import org.jetbrains.annotations.TestOnly; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.element.java.JavaClass; @TestOnly public class JavaClassUtils { public static final JavaClass CLASS = new JavaClass(Class.class, 1); public static JavaClass getList(Class<?> parameterType) { return new JavaClass(ArrayList.class, new JavaClass(parameterType)); } public static JavaClass getList(JavaClass parameterType) { return new JavaClass(ArrayList.class, parameterType); } public static JavaClass getMap(Class<?> key, Class<?> value) { return new JavaClass(Map.class, ImmutableList.of(new JavaClass(key), new JavaClass(value))); } public static JavaClass getMap(JavaClass key, Class<?> value) { return new JavaClass(Map.class, ImmutableList.of(key, new JavaClass(value))); } public static JavaClass getMap(Class<?> key, JavaClass value) { return new JavaClass(Map.class, ImmutableList.of(new JavaClass(key), value)); } }
1,805
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaParameterTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/java/JavaParameterTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings({ "unused", "EmptyMethod" }) class JavaParameterTest { @Test void shouldConstructValidJavaParameterFromParameterObject() throws NoSuchMethodException { JavaParameter javaParam = new JavaParameter(JavaParameterTest.class.getDeclaredMethod( "testMethodWithParameter", Integer.class).getParameters()[0]); String paramName = javaParam.getName(); Assertions.assertTrue(paramName.equals("arg0") || paramName.equals("param")); Assertions.assertEquals("java.lang.Integer", javaParam.getType().toString()); } @Test void shouldConstructValidJavaParameterFromClassObject() { JavaParameter javaParam = new JavaParameter(Object.class, "param"); Assertions.assertEquals("java.lang.Object", javaParam.getType().getName()); Assertions.assertEquals("param", javaParam.getName()); } @Test void whenComparingJavaParameterWithEqualsShouldCompareInternalDetails() { JavaParameter javaParam = new JavaParameter(Object.class, "param"); Assertions.assertEquals(javaParam, new JavaParameter(Object.class, "param")); Assertions.assertNotEquals(javaParam, new JavaParameter(String.class, "param")); Assertions.assertNotEquals(javaParam, new JavaParameter(Object.class, "param1")); } @TestOnly private void testMethodWithParameter(Integer param) { } }
2,204
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaFieldTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/java/JavaFieldTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Field; import java.util.Arrays; import java.util.List; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.base.Splitter; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; @SuppressWarnings("unused") class JavaFieldTest { private static final Object staticFinalField = null; private static Object staticField; public Object publicField; Object defaultField; private Object privateField; @TestOnly private static Field getDeclaredField(String name) { return Arrays.stream(JavaFieldTest.class.getDeclaredFields()) .filter(f -> f.getName().equals(name)).findFirst() .orElseThrow(RuntimeException::new); } @Test void shouldConstructJavaFieldWithValidNameFromFieldObject() { for (Field declaredField : JavaFieldTest.class.getDeclaredFields()) { Assertions.assertEquals(declaredField.getName(), new JavaField(declaredField).getName()); } } @Test void shouldConstructJavaFieldWithValidNameFromClassObject() { for (Field declaredField : JavaFieldTest.class.getDeclaredFields()) { Assertions.assertEquals(declaredField.getName(), new JavaField(declaredField.getType(), declaredField.getName(), new MemberModifier(declaredField.getModifiers())).getName()); } } @Test void shouldConstructJavaFieldWithValidReadableForm() { String[] fieldData = new String[]{ "publicField", "public java.lang.Object", "privateField", "private java.lang.Object", "defaultField", "java.lang.Object", "staticField", "private static java.lang.Object", "staticFinalField", "private static final java.lang.Object" }; for (int i = 0; i < fieldData.length; i += 2) { String expected = fieldData[i + 1] + ' ' + fieldData[i]; Field declaredField = getDeclaredField(fieldData[i]); Assertions.assertEquals(expected, new JavaField(declaredField).toString()); try { List<String> elements = Splitter.onPattern("\\s+").splitToList(fieldData[i + 1]); Class<?> clazz = Class.forName(elements.get(elements.size() - 1)); MemberModifier modifier = new MemberModifier(declaredField.getModifiers()); Assertions.assertEquals(expected, new JavaField(clazz, fieldData[i], modifier).toString()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } }
3,164
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaMethodTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/java/JavaMethodTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.HashSetValuedHashMap; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; @SuppressWarnings("unused") class JavaMethodTest { private static final ImmutableList<JavaParameter> DUMMY_PARAMS = ImmutableList.of(new JavaParameter(Object.class, "param1")); private static final JavaMethod METHOD_WITH_PARAMETERS = new JavaMethod(getDeclaredMethod("testMethodWithParameters")); private static final JavaMethod METHOD_WITHOUT_PARAMETERS = new JavaMethod(getDeclaredMethod("testMethodWithoutParametersOrReturnType")); private static final JavaMethod METHOD_WITH_RETURN_TYPE = new JavaMethod(getDeclaredMethod("testMethodWithReturnType")); private static final JavaMethod METHOD_WITHOUT_RETURN_TYPE = new JavaMethod(getDeclaredMethod("testMethodWithoutParametersOrReturnType")); @TestOnly private static void assertReadableForm(String form, JavaMethod method) { Assertions.assertEquals(form, method.toString()); } @TestOnly private static Method getDeclaredMethod(String name) { return Arrays.stream(JavaMethodTest.InnerTest.class.getDeclaredMethods()) .filter(m -> m.getName().equals(name)).findFirst() .orElseThrow(RuntimeException::new); } @Test void shouldCreateJavaMethodWithValidName() { String methodName = "testMethodWithParameters"; Assertions.assertEquals(methodName, METHOD_WITH_PARAMETERS.getName()); Assertions.assertEquals(methodName, JavaMethod.Builder.create(methodName) .withReturnType(void.class).withParams(DUMMY_PARAMS).build().getName()); } @Test void shouldCreateJavaMethodWithValidReadableForm() { assertReadableForm("public void " + "testMethodWithParameters(int arg0, java.lang.String arg1)", METHOD_WITH_PARAMETERS); assertReadableForm("void " + "testMethodWithoutParametersOrReturnType()", METHOD_WITHOUT_PARAMETERS); assertReadableForm("private java.lang.Integer " + "testMethodWithReturnType()", METHOD_WITH_RETURN_TYPE); } @Test void shouldCreateVarArgJavaMethodWithValidReadableForm() { JavaClass returnType = new JavaClass(void.class); MemberModifier modifier = MemberModifier.UNDECLARED; List<JavaMethod> javaMethodsList = ImmutableList.of( JavaMethod.Builder.create("varArgMethod1").withReturnType(returnType) .withModifier(modifier).withVarArgs(true) .withParams(new JavaParameter(String.class, "params")) .build(), JavaMethod.Builder.create("varArgMethod2").withReturnType(returnType) .withModifier(modifier).withVarArgs(true) .withParams( new JavaParameter(Integer.class, "param0"), new JavaParameter(String.class, "params") ).build(), JavaMethod.Builder.create("varArgMethod3").withReturnType(returnType) .withModifier(modifier).withVarArgs(true) .withParams( new JavaParameter(Integer.class, "param0"), new JavaParameter(Object.class, "param1"), new JavaParameter(String.class, "params") ).build() ); List<String> expectedReadableForm = ImmutableList.of( "void varArgMethod1(java.lang.String... params)", "void varArgMethod2(java.lang.Integer param0, java.lang.String... params)", "void varArgMethod3(java.lang.Integer param0, " + "java.lang.Object param1, java.lang.String... params)" ); for (int i = 0; i < javaMethodsList.size(); i++) { assertReadableForm(expectedReadableForm.get(i), javaMethodsList.get(i)); } } @Test void shouldCreateJavaMethodWithValidParameters() { List<JavaParameter> params = METHOD_WITH_PARAMETERS.getParams(); Assertions.assertEquals(2, params.size()); JavaParameter firstParam = params.get(0); JavaParameter secondParam = params.get(1); Assertions.assertEquals("int", firstParam.getType().toString()); Assertions.assertEquals("arg0", firstParam.getName()); Assertions.assertEquals("java.lang.String", secondParam.getType().getName()); Assertions.assertEquals("arg1", secondParam.getName()); Assertions.assertEquals(0, METHOD_WITHOUT_PARAMETERS.getParams().size()); } @Test void shouldCreateJavaMethodWithValidReturnType() { MultiValuedMap<JavaMethod, String> map = new HashSetValuedHashMap<>(); map.put(METHOD_WITH_RETURN_TYPE, "java.lang.Integer"); map.put(METHOD_WITHOUT_RETURN_TYPE, "void"); for (Map.Entry<JavaMethod, String> entry : map.entries()) { Assertions.assertEquals(entry.getValue(), entry.getKey().getReturnType().getName()); } } @Test void shouldMatchMethodsWithVarArgAndArrayParameter() { MemberModifier modifier = MemberModifier.UNDECLARED; JavaMethod method1 = JavaMethod.Builder.create("method1") .withReturnType(Object.class).withModifier(modifier).withVarArgs(true) .withParams( new JavaParameter(new JavaClass(String.class), "param"), new JavaParameter(new JavaClass(Integer.class), "params") ).build(); JavaMethod method2 = JavaMethod.Builder.create("method1") .withReturnType(Object.class).withModifier(modifier).withVarArgs(true) .withParams( new JavaParameter(new JavaClass(String.class), "param"), new JavaParameter(new JavaClass(Integer[].class), "params") ).build(); Assertions.assertEquals(method1, method2); } @Test void shouldIgnoreJavaMethodHasVarArgWhenEmptyParamList() { JavaClass returnType = new JavaClass(Object.class); List<JavaParameter> params = new ArrayList<>(); Assertions.assertFalse(JavaMethod.Builder.create("test").withReturnType(returnType) .withVarArgs(true).withParams(params).build().hasVarArg()); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingJavaMethodParameters() { Assertions.assertThrows(UnsupportedOperationException.class, () -> METHOD_WITH_PARAMETERS.getParams().addAll(DUMMY_PARAMS)); } @SuppressWarnings({ "WeakerAccess", "RedundantSuppression", "EmptyMethod" }) private static class InnerTest { @TestOnly public void testMethodWithParameters(int param1, String param2) { } @TestOnly void testMethodWithoutParametersOrReturnType() { } @TestOnly @SuppressWarnings("SameReturnValue") private Integer testMethodWithReturnType() { return 0; } } }
7,307
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaClassTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/java/JavaClassTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Method; import java.util.List; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; @SuppressWarnings({ "SameReturnValue", "unused", "EmptyMethod" }) class JavaClassTest { @TestOnly private static void methodWithVoidReturnType() { } @TestOnly private static int methodWithPrimitiveReturnType() { return 0; } @TestOnly private static boolean methodWithBooleanReturnType() { return true; } @Test void shouldParseValidJavaClassFromClassObject() { JavaClass jClass = new JavaClass(JavaClassTest.class); String classPath = "io/cocolabs/pz/zdoc/element/java/JavaClassTest"; Assertions.assertEquals(classPath, JavaClass.getPathForClass(JavaClassTest.class)); Assertions.assertEquals(JavaClassTest.class.getName(), jClass.getName()); } @Test void shouldParseValidJavaClassFromInnerClassObject() { JavaClass jClass = new JavaClass(InnerClass.class); String classPath = "io/cocolabs/pz/zdoc/element/java/JavaClassTest.InnerClass"; Assertions.assertEquals(classPath, JavaClass.getPathForClass(InnerClass.class)); Assertions.assertEquals(InnerClass.class.getTypeName(), jClass.getName()); } @Test void shouldReturnNullPathWhenJavaClassHasNoPackage() throws NoSuchMethodException { Method[] methods = new Method[]{ JavaClassTest.class.getDeclaredMethod("methodWithVoidReturnType"), JavaClassTest.class.getDeclaredMethod("methodWithPrimitiveReturnType"), JavaClassTest.class.getDeclaredMethod("methodWithBooleanReturnType"), }; for (Method method : methods) { Assertions.assertEquals("", JavaClass.getPathForClass(method.getReturnType())); } } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingJavaClassTypeParameterList() { JavaClass jClass = new JavaClass(String.class); Assertions.assertThrows(UnsupportedOperationException.class, () -> jClass.getTypeParameters().add(new JavaClass(Object.class))); } @Test void whenComparingJavaClassWithEqualsShouldCompareInternalDetails() { // compare classes with same clazz field objects Assertions.assertEquals(new JavaClass(Object.class), new JavaClass(Object.class)); Assertions.assertNotEquals(new JavaClass(Object.class), new JavaClass(String.class)); List<JavaClass> simpleTypeParameters = ImmutableList.of( new JavaClass(String.class), new JavaClass(Boolean.class) ); // compare classes with same type parameter objects JavaClass jClassWithSimpleTypeParameters = new JavaClass(Object.class, simpleTypeParameters); Assertions.assertEquals( jClassWithSimpleTypeParameters, new JavaClass(Object.class, simpleTypeParameters) ); // compare classes with different type parameters Assertions.assertNotEquals( jClassWithSimpleTypeParameters, new JavaClass(Object.class, ImmutableList.of( new JavaClass(String.class), new JavaClass(Integer.class) )) ); // compare classes with different number of type parameters Assertions.assertNotEquals( jClassWithSimpleTypeParameters, new JavaClass(Object.class, new JavaClass(String.class)) ); Assertions.assertNotEquals( jClassWithSimpleTypeParameters, new JavaClass(Object.class) ); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingUnknownTypeParameterList() { Assertions.assertThrows(UnsupportedOperationException.class, () -> JavaClass.getUnknownTypeParameterList(1).add(null)); } @Test void shouldGetCorrectUnknownTypeParameterListForValidSize() { for (int i = 1; i < 3; i++) { List<JavaClass> typeParameterList = JavaClass.getUnknownTypeParameterList(i); Assertions.assertEquals(i, typeParameterList.size()); typeParameterList.forEach(Assertions::assertNull); } } private static class InnerClass {} }
4,671
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaFieldTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/lua/LuaFieldTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; class LuaFieldTest { @Test void shouldCreateLuaFieldWithSafeLuaName() { Assertions.assertEquals("_break", new LuaField(new LuaType("Boolean"), "break", MemberModifier.UNDECLARED).getName()); Assertions.assertNotEquals("_test", new LuaField(new LuaType("Boolean"), "test", MemberModifier.UNDECLARED).getName()); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaFieldAnnotations() { LuaField field = new LuaField(new LuaType("test"), "type", MemberModifier.UNDECLARED); Assertions.assertThrows(UnsupportedOperationException.class, () -> field.getAnnotations().add(new EmmyLuaClass("TestType", null))); } }
1,652
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaMethodTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/lua/LuaMethodTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import java.util.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.lang.lua.EmmyLua; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaOverload; class LuaMethodTest { private static final LuaParameter DUMMY_PARAM = new LuaParameter(new LuaType("dummy"), "param1"); private static final LuaMethod TEST_METHOD = LuaMethod.Builder.create("test") .withOwner(new LuaClass("TestClass")).withParams(ImmutableList.of( DUMMY_PARAM, new LuaParameter(new LuaType("dummy"), "param2"))).build(); @Test void shouldCreateLuaMethodWithSafeLuaName() { LuaType type = new LuaType("Boolean"); List<LuaParameter> params = new ArrayList<>(); LuaMethod method = LuaMethod.Builder.create("break").withReturnType(type).withParams(params).build(); Assertions.assertEquals("_break", method.getName()); method = LuaMethod.Builder.create("test").withReturnType(type).withParams(params).build(); Assertions.assertNotEquals("_test", method.getName()); } @Test void shouldCorrectlyConvertLuaMethodToString() { Assertions.assertEquals("TestClass:test(param1, param2)", TEST_METHOD.toString()); List<LuaParameter> params = ImmutableList.of( new LuaParameter(new LuaType("String"), "param1"), new LuaParameter(new LuaType("Integer"), "param2") ); LuaMethod varArgMethod = LuaMethod.Builder.create("test").withOwner(new LuaClass("TestClass")) .withReturnType(new LuaType("Object")).withParams(params).withVarArg(true).build(); Assertions.assertEquals("TestClass:test(param1, ...)", varArgMethod.toString()); } @Test void shouldIgnoreLuaMethodHasVarArgWhenEmptyParamList() { Assertions.assertFalse(LuaMethod.Builder.create("test") .withReturnType(new LuaType("Boolean")).withVarArg(true).build().hasVarArg() ); } @Test void shouldCreateMethodWithOverloadProperties() { Set<LuaMethod> overloadMethods = Sets.newHashSet( LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0") ).build(), LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1") ).build(), LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1"), new LuaParameter(new LuaType("String"), "arg2") ).build() ); LuaMethod method = LuaMethod.Builder.create("testMethod").withOverloads(overloadMethods).build(); List<EmmyLua> annotations = method.getAnnotations(); Set<EmmyLuaOverload> overloadAnnotations = new HashSet<>(); annotations.stream().filter(a -> a instanceof EmmyLuaOverload) .forEach(a -> overloadAnnotations.add((EmmyLuaOverload) a)); Assertions.assertEquals(overloadMethods.size(), overloadAnnotations.size()); for (LuaMethod overloadMethod : overloadMethods) { EmmyLuaOverload annotation = new EmmyLuaOverload(overloadMethod.getParams()); Assertions.assertEquals(1, annotations.stream() .filter(a -> a.toString().equals(annotation.toString())).count()); } } @Test void shouldCompareOverloadMethodsAccordingToParamSize() { Comparator<LuaMethod> comparator = new LuaMethod.OverloadMethodComparator(); // identical to luaMethods[1] array entry LuaMethod luaMethod = LuaMethod.Builder.create("method").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("String"), "arg1") ).build(); LuaMethod[] luaMethods = new LuaMethod[] { LuaMethod.Builder.create("method").withParams( new LuaParameter(new LuaType("Object"), "arg0") ).build(), LuaMethod.Builder.create("method").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("String"), "arg1") ).build(), LuaMethod.Builder.create("method").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1"), new LuaParameter(new LuaType("Number"), "arg2") ).build(), LuaMethod.Builder.create("method").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("String"), "arg2"), new LuaParameter(new LuaType("Number"), "arg3"), new LuaParameter(new LuaType("Object"), "arg4") ).build() }; Assertions.assertEquals(-1, comparator.compare(luaMethods[0], luaMethods[1])); Assertions.assertEquals(-1, comparator.compare(luaMethods[1], luaMethods[2])); Assertions.assertEquals(0, comparator.compare(luaMethods[1], luaMethod)); Assertions.assertEquals(1, comparator.compare(luaMethods[3], luaMethods[2])); SortedSet<LuaMethod> sortedSet = new TreeSet<>(comparator); sortedSet.addAll(Arrays.asList(luaMethods)); Iterator<LuaMethod> iter = sortedSet.iterator(); for (int i = 0; i < sortedSet.size(); i++) { Assertions.assertEquals(luaMethods[i], iter.next()); } } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaMethodAnnotations() { Assertions.assertThrows(UnsupportedOperationException.class, () -> TEST_METHOD.getAnnotations().add(new EmmyLuaClass("TestType", null))); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaMethodParameters() { Assertions.assertThrows(UnsupportedOperationException.class, () -> TEST_METHOD.getParams().add(DUMMY_PARAM)); } }
6,389
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaClassTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/lua/LuaClassTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; class LuaClassTest { @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaClassAnnotations() { LuaClass luaClass = new LuaClass("test", "type"); Assertions.assertThrows(UnsupportedOperationException.class, () -> luaClass.getAnnotations().add(new EmmyLuaClass("TestType", null))); } }
1,253
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaTypeTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/lua/LuaTypeTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class LuaTypeTest { @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaTypeTypeParametersImmutableList() { LuaType type = new LuaType("test1", new LuaType("test2")); Assertions.assertThrows(UnsupportedOperationException.class, () -> type.getTypeParameters().add(new LuaType("test3")) ); } }
1,213
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaParameterTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/lua/LuaParameterTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaClass; class LuaParameterTest { @Test void shouldCreateLuaParameterWithSafeLuaName() { LuaParameter param = new LuaParameter(new LuaType("test"), "end"); Assertions.assertEquals("_end", param.getName()); param = new LuaParameter(new LuaType("testType"), "test"); Assertions.assertNotEquals("_test", param.getName()); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingLuaParameterAnnotations() { LuaParameter param = new LuaParameter(new LuaType("string"), "test"); Assertions.assertThrows(UnsupportedOperationException.class, () -> param.getAnnotations().add(new EmmyLuaClass("TestType", null))); } }
1,579
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MemberModifierTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/element/mod/MemberModifierTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.mod; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.collections4.list.SetUniqueList; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings({ "unused", "EmptyMethod" }) class MemberModifierTest { private static final AccessModifierKey PUBLIC = AccessModifierKey.PUBLIC; private static final ModifierKey UNDECLARED = ModifierKey.UNDECLARED; private static final TestMember STATIC_FINAL_MEMBER = new TestMember( AccessModifierKey.PUBLIC, ModifierKey.STATIC, ModifierKey.FINAL ); private static final Object staticFinalField = null; private static Object staticField; public Object publicField; protected Object protectedField; Object defaultField; private Object privateField; @TestOnly private static Field getDeclaredField(String name) { return Arrays.stream(MemberModifierTest.class.getDeclaredFields()) .filter(f -> f.getName().equals(name)).findFirst() .orElseThrow(RuntimeException::new); } @TestOnly private static Method getDeclaredMethod(String name) { return Arrays.stream(TestMember.class.getDeclaredMethods()) .filter(f -> f.getName().equals(name)).findFirst() .orElseThrow(RuntimeException::new); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingModifierList() { Assertions.assertThrows(UnsupportedOperationException.class, () -> STATIC_FINAL_MEMBER.getModifiers().add(UNDECLARED)); } @Test void shouldCreateMemberModifierWithValidReadableForm() { Assertions.assertEquals("public static final", STATIC_FINAL_MEMBER.toString()); } @Test void shouldNotCreateMemberModifierWithKeysContainingUndeclaredKey() { TestMember undeclaredMember = new TestMember(PUBLIC, UNDECLARED); Assertions.assertTrue(undeclaredMember.isModifierUndeclared()); TestMember finalMember = new TestMember(PUBLIC, UNDECLARED, ModifierKey.FINAL); Assertions.assertFalse(finalMember.isModifierUndeclared()); } @Test void shouldCreateMemberModifierAsUndeclaredWhenNoModifiersPresent() { TestMember undeclaredMember = new TestMember(PUBLIC); Assertions.assertEquals(1, undeclaredMember.getModifiers().size()); Assertions.assertTrue(undeclaredMember.isModifierUndeclared()); } @Test void shouldCreateMemberModifierWithSpecifiedAccess() { Assertions.assertTrue(new TestMember(PUBLIC).hasAccess(PUBLIC)); } @Test void shouldGetCorrectMemberModifierKeysByName() { for (AccessModifierKey key : AccessModifierKey.values()) { Assertions.assertEquals(key, AccessModifierKey.get(key.name)); } ModifierKey[] keys = Arrays.stream(ModifierKey.values()) .filter(k -> k != ModifierKey.UNDECLARED).toArray(ModifierKey[]::new); for (ModifierKey key : keys) { SetUniqueList<ModifierKey> foundKeys = ModifierKey.get(key.name); Assertions.assertEquals(1, foundKeys.size()); Assertions.assertEquals(key, foundKeys.get(0)); } List<String> keyNames = new ArrayList<>(keys.length); Arrays.stream(keys).forEach(k -> keyNames.add(k.name)); String[] keyArray = keyNames.toArray(new String[]{}); SetUniqueList<ModifierKey> modifierKeys = ModifierKey.get(keyArray); Assertions.assertEquals(keyArray.length, modifierKeys.size()); for (int i = 0; i < modifierKeys.size(); i++) { Assertions.assertEquals(keys[i], modifierKeys.get(i)); } } @Test void shouldGetCorrectMemberModifierKeysByModifiersValue() { for (AccessModifierKey key : AccessModifierKey.values()) { Assertions.assertEquals(key, AccessModifierKey.get(key.value)); } for (ModifierKey key : ModifierKey.values()) { SetUniqueList<ModifierKey> foundKeys = ModifierKey.get(key.value); Assertions.assertEquals(1, foundKeys.size()); Assertions.assertEquals(key, foundKeys.get(0)); } } @Test void shouldCorrectlyReadJavaFieldModifier() { TestMember staticMod = new TestMember(getDeclaredField("staticField")); Assertions.assertEquals(1, staticMod.getModifiers().size()); Assertions.assertEquals("static", staticMod.getModifiers().get(0).toString()); TestMember staticFinalMod = new TestMember(getDeclaredField("staticFinalField")); Assertions.assertEquals(2, staticFinalMod.getModifiers().size()); Assertions.assertEquals("private static final", staticFinalMod.toString()); } @Test void shouldCorrectlyReadJavaFieldAccessModifier() { String[] fieldData = new String[]{ "public", "publicField", "protected", "protectedField", "private", "privateField", "", "defaultField" }; for (int i = 0; i < fieldData.length; i += 2) { TestMember modifier = new TestMember(getDeclaredField(fieldData[i + 1])); Assertions.assertEquals(fieldData[i], modifier.getAccess().toString()); } } @Test void shouldCorrectlyReadJavaMethodAccessModifier() { String[] methodData = new String[]{ "public", "publicMethod", "protected", "protectedMethod", "private", "privateMethod", "", "defaultMethod" }; for (int i = 0; i < methodData.length; i += 2) { TestMember modifier = new TestMember(getDeclaredMethod(methodData[i + 1])); Assertions.assertEquals(methodData[i], modifier.getAccess().toString()); } } @Test void whenComparingMemberModifierWithEqualsShouldCompareInternalDetails() { // compare modifiers with same access Assertions.assertEquals( new MemberModifier(AccessModifierKey.PUBLIC), new MemberModifier(AccessModifierKey.PUBLIC) ); Assertions.assertNotEquals( new MemberModifier(AccessModifierKey.PUBLIC), new MemberModifier(AccessModifierKey.PRIVATE) ); // compare modifiers with different number of keys ModifierKey[] keys = new ModifierKey[]{ ModifierKey.FINAL, ModifierKey.STATIC }; MemberModifier modifier = new MemberModifier(AccessModifierKey.DEFAULT, keys); Assertions.assertEquals( new MemberModifier(AccessModifierKey.DEFAULT, keys), modifier ); Assertions.assertNotEquals( MemberModifier.UNDECLARED, modifier ); // compare modifiers with different key ordering Assertions.assertNotEquals( modifier, new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC, ModifierKey.FINAL) ); } @SuppressWarnings({ "WeakerAccess", "RedundantSuppression" }) private static class TestMember extends MemberModifier { private TestMember(Member member) { super(member.getModifiers()); } private TestMember(AccessModifierKey accessKey, ModifierKey... modifierKeys) { super(accessKey, modifierKeys); } @TestOnly public void publicMethod() { } @TestOnly protected void protectedMethod() { } @TestOnly private void privateMethod() { } @TestOnly void defaultMethod() { } } }
7,606
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
DocTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/DocTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.util.Objects; import org.junit.jupiter.api.Tag; @Tag("doc") public abstract class DocTest { protected static final ZomboidAPIDoc DOCUMENT; protected static final Path DOCUMENT_PATH; static { try { URL resource = DocTest.class.getClassLoader().getResource("Test.html"); DOCUMENT_PATH = new File(Objects.requireNonNull(resource).toURI()).toPath(); DOCUMENT = ZomboidAPIDoc.getLocalPage(DOCUMENT_PATH); DOCUMENT.getDocument().setBaseUri(ZomboidAPIDoc.resolveURL("zombie/Test.html").toString()); } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } } }
1,538
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidAPIDocTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/ZomboidAPIDocTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.util.Utils; class ZomboidAPIDocTest extends DocTest { @Test void shouldCorrectlyResolveZomboidDocApiURL() { String expected = "https://projectzomboid.com/modding/zombie/inventory/InventoryItem.html"; URL actual = ZomboidAPIDoc.resolveURL("zombie/inventory/InventoryItem.html"); Assertions.assertEquals(expected, actual.toString()); } @Test void shouldThrowExceptionWhenResolvingZomboidDocNonApiUrl() { Assertions.assertThrows(IllegalArgumentException.class, () -> ZomboidAPIDoc.resolveURL("https://nonapiwebsite.com")); } @Test void shouldCorrectlyResolveZomboidDocApiURLFromOtherURL() { String link = "https://projectzomboid.com/"; Assertions.assertEquals(link, ZomboidAPIDoc.resolveURL(link).toString()); } @Test void shouldThrowExceptionWhenResolvingZomboidDocApiURLWithInvalidArgument() { Assertions.assertThrows(IllegalArgumentException.class, () -> ZomboidAPIDoc.resolveURL('\u0000' + "/p*!h")); } @Test void shouldAttachMissingHTMLFileExtensionWhenParsingZomboidDocApiURL() { URL url = Utils.getURL("https://projectzomboid.com/modding/zombie/Class.html"); Assertions.assertEquals(url, ZomboidAPIDoc.resolveURL("zombie/Class")); } @Test void shouldCorrectlyValidateApiURL() { // absolute url to api html page URL url = Utils.getURL("https://projectzomboid.com/modding/zombie/Class.html"); Assertions.assertTrue(ZomboidAPIDoc.isValidURL(url)); // absolute url to api directory url = Utils.getURL("https://projectzomboid.com/modding/zombie/"); Assertions.assertTrue(ZomboidAPIDoc.isValidURL(url)); url = Utils.getURL("https://projectzomboid.com/modding/"); Assertions.assertTrue(ZomboidAPIDoc.isValidURL(url)); // url containing only protocol and host url = Utils.getURL("https://projectzomboid.com/"); Assertions.assertTrue(ZomboidAPIDoc.isValidURL(url)); url = Utils.getURL("https://project.com/"); Assertions.assertFalse(ZomboidAPIDoc.isValidURL(url)); url = Utils.getURL("https://project.com/test"); Assertions.assertFalse(ZomboidAPIDoc.isValidURL(url)); } @Test void shouldCorrectlyResolveApiURLPath() { assertValidResolvedApiURLPath( "https://projectzomboid.com/modding/zombie/Class.html", "zombie/Class.html" ); assertValidResolvedApiURLPath( "https://projectzomboid.com/modding/zombie/", "zombie/" ); assertValidResolvedApiURLPath( "https://projectzomboid.com/modding/", "" ); assertValidResolvedApiURLPath( "https://projectzomboid.com/", "../" ); Assertions.assertThrows(RuntimeException.class, () -> assertValidResolvedApiURLPath("https://test.io/", "") ); } @Test void shouldConstructValidZomboidDocFromLocalAPIPage() { ZomboidAPIDoc doc = DocTest.DOCUMENT; Assertions.assertNotNull(doc.getDocument()); Assertions.assertEquals("Test.html", doc.getName()); } @TestOnly private void assertValidResolvedApiURLPath(String actualUrl, String expectedUrl) { String sActual = Utils.getURL(actualUrl).toString(); Path pActual = Paths.get(ZomboidAPIDoc.resolveURLPath(sActual).toString()); Assertions.assertEquals(Paths.get(expectedUrl), pActual); } }
4,142
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ZomboidLuaDocTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/ZomboidLuaDocTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc; import java.io.IOException; import java.util.*; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.TestWorkspace; import io.cocolabs.pz.zdoc.compile.JavaCompiler; import io.cocolabs.pz.zdoc.element.lua.*; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.lang.lua.EmmyLuaOverload; class ZomboidLuaDocTest extends TestWorkspace { private static final LuaType LUA_ARRAY_LIST_OBJECT = new LuaType( "ArrayList", new LuaType("Object") ); private static final LuaType LUA_ARRAY_LIST_STRING_OBJECT = new LuaType( "ArrayList", ImmutableList.of(new LuaType("String"), new LuaType("Object")) ); private static final LuaType LUA_ARRAY_LIST_INNER_CLASS = new LuaType( "ArrayList", new LuaType("ZomboidLuaDocTest.InnerClass") ); private static final LuaType LUA_ARRAY_LIST_UNKNOWN = new LuaType( "ArrayList", new LuaType("Unknown") ); private static final LuaClass TEST_LUA_CLASS = new LuaClass( ZomboidLuaDocTest.class.getSimpleName(), ZomboidLuaDocTest.class.getName() ); ZomboidLuaDocTest() { super("zomboidDoc.lua"); } @Test void shouldWriteZomboidLuaDocClassNameToFile() throws IOException { List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}" ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc(TEST_LUA_CLASS); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocFieldsToFile() throws IOException { List<LuaField> luaFields = ImmutableList.of( new LuaField(new LuaType(Object.class.getSimpleName()), "object", new MemberModifier(AccessModifierKey.PUBLIC) ), new LuaField(new LuaType(String.class.getSimpleName()), "text", new MemberModifier(AccessModifierKey.PRIVATE) ), new LuaField(new LuaType(Integer.class.getSimpleName()), "number", new MemberModifier(AccessModifierKey.PROTECTED) ), new LuaField(new LuaType(Class.class.getSimpleName()), "clazz", new MemberModifier(AccessModifierKey.DEFAULT) ) ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, luaFields, new HashSet<>() ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "---@field public object Object", "---@field private text String", "---@field protected _number Integer", "---@field clazz Class", "ZomboidLuaDocTest = {}" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocParameterizedFieldsToFile() throws IOException { List<LuaField> luaFields = ImmutableList.of( new LuaField(LUA_ARRAY_LIST_OBJECT, "object", new MemberModifier(AccessModifierKey.PUBLIC) ), new LuaField(LUA_ARRAY_LIST_STRING_OBJECT, "text", new MemberModifier(AccessModifierKey.PRIVATE) ), new LuaField(LUA_ARRAY_LIST_INNER_CLASS, "inner", new MemberModifier(AccessModifierKey.PROTECTED) ), new LuaField(LUA_ARRAY_LIST_UNKNOWN, "anything", new MemberModifier(AccessModifierKey.DEFAULT) ) ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, luaFields, new HashSet<>() ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "---@field public object ArrayList|Object", "---@field private text ArrayList|String|Object", "---@field protected inner ArrayList|ZomboidLuaDocTest.InnerClass", "---@field anything ArrayList|Unknown", "ZomboidLuaDocTest = {}" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocMethodsToFile() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getText").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withReturnType(new LuaType("String")).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param0"))).build() ); luaMethods.add(LuaMethod.Builder.create("getNumber").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PROTECTED)) .withReturnType(new LuaType("Integer")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(new LuaType("int"), "param2"))).build() ); luaMethods.add(LuaMethod.Builder.create("getInnerClass").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PRIVATE)) .withReturnType(new LuaType("ZomboidLuaDocTest.InnerClass")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(new LuaType("boolean"), "param2"), new LuaParameter(new LuaType("Object[]"), "param3"))).build() ); luaMethods.add(LuaMethod.Builder.create("getArray").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT)) .withReturnType(new LuaType("Object[]")).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---@public", "---@param param0 Object", "---@return String", "function ZomboidLuaDocTest:getText(param0) end", "", "---@protected", "---@param param1 Object", "---@param param2 int", "---@return Integer", "function ZomboidLuaDocTest:getNumber(param1, param2) end", "", "---@private", "---@param param1 Object", "---@param param2 boolean", "---@param param3 Object[]", "---@return ZomboidLuaDocTest.InnerClass", "function ZomboidLuaDocTest:getInnerClass(param1, param2, param3) end", "", "---@return Object[]", "function ZomboidLuaDocTest:getArray() end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocMethodsWithCommentsToFile() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getText").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("String")) .withParams(ImmutableList.of(new LuaParameter(new LuaType("Object"), "param0"))) .withComment("this method has a single-line comment").build() ); luaMethods.add(LuaMethod.Builder.create("getNumber").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Integer")).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(new LuaType("int"), "param2")) ).withComment("this method has a\nmulti-line comment").build() ); luaMethods.add(LuaMethod.Builder.create("getInnerClass").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("ZomboidLuaDocTest.InnerClass")) .withParams(ImmutableList.of(new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(new LuaType("boolean"), "param2"), new LuaParameter(new LuaType("Object[]"), "param3")) ).withComment("this method has a\rmulti-line comment").build() ); luaMethods.add(LuaMethod.Builder.create("getArray").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT)) .withReturnType(new LuaType("Object[]")) .withComment("this method has a\r\nmulti-line comment").build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---this method has a single-line comment", "---@param param0 Object", "---@return String", "function ZomboidLuaDocTest:getText(param0) end", "", "---this method has a", "---", "---multi-line comment", "---@param param1 Object", "---@param param2 int", "---@return Integer", "function ZomboidLuaDocTest:getNumber(param1, param2) end", "", "---this method has a", "---", "---multi-line comment", "---@param param1 Object", "---@param param2 boolean", "---@param param3 Object[]", "---@return ZomboidLuaDocTest.InnerClass", "function ZomboidLuaDocTest:getInnerClass(param1, param2, param3) end", "", "---this method has a", "---", "---multi-line comment", "---@return Object[]", "function ZomboidLuaDocTest:getArray() end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocMethodsWithParameterizedTypesToFile() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getObjectList").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withReturnType(LUA_ARRAY_LIST_OBJECT).withParams(ImmutableList.of( new LuaParameter(LUA_ARRAY_LIST_STRING_OBJECT, "param"))).build() ); luaMethods.add(LuaMethod.Builder.create("getStringObjectList").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PROTECTED)) .withReturnType(LUA_ARRAY_LIST_STRING_OBJECT).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(LUA_ARRAY_LIST_OBJECT, "param2"))).build() ); luaMethods.add(LuaMethod.Builder.create("getInnerClassList").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.PRIVATE)) .withReturnType(LUA_ARRAY_LIST_INNER_CLASS).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(LUA_ARRAY_LIST_STRING_OBJECT, "param2"), new LuaParameter(new LuaType("Object[]"), "param3"))).build() ); luaMethods.add(LuaMethod.Builder.create("getUnknownList").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT)) .withReturnType(LUA_ARRAY_LIST_UNKNOWN).withParams(ImmutableList.of( new LuaParameter(LUA_ARRAY_LIST_UNKNOWN, "param1"))).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---@public", "---@param param ArrayList|String|Object", "---@return ArrayList|Object", "function ZomboidLuaDocTest:getObjectList(param) end", "", "---@protected", "---@param param1 Object", "---@param param2 ArrayList|Object", "---@return ArrayList|String|Object", "function ZomboidLuaDocTest:getStringObjectList(param1, param2) end", "", "---@private", "---@param param1 Object", "---@param param2 ArrayList|String|Object", "---@param param3 Object[]", "---@return ArrayList|ZomboidLuaDocTest.InnerClass", "function ZomboidLuaDocTest:getInnerClassList(param1, param2, param3) end", "", "---@param param1 ArrayList|Unknown", "---@return ArrayList|Unknown", "function ZomboidLuaDocTest:getUnknownList(param1) end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocMethodsWithVariadicArgumentsToFile() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getObject").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Object")).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getText").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("String")).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object[]"), "param"), new LuaParameter(new LuaType("String"), "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getNumber").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Integer")).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param0"), new LuaParameter(new LuaType("Integer"), "param1"), new LuaParameter(new LuaType("String"), "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getObjectList").withOwner(TEST_LUA_CLASS) .withReturnType(LUA_ARRAY_LIST_OBJECT).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(LUA_ARRAY_LIST_STRING_OBJECT, "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getStringObjectList").withOwner(TEST_LUA_CLASS) .withReturnType(LUA_ARRAY_LIST_STRING_OBJECT).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(LUA_ARRAY_LIST_OBJECT, "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getInnerClassList").withOwner(TEST_LUA_CLASS) .withReturnType(LUA_ARRAY_LIST_INNER_CLASS).withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param1"), new LuaParameter(LUA_ARRAY_LIST_STRING_OBJECT, "param2"), new LuaParameter(new LuaType("Object[]"), "varargs"))).build() ); luaMethods.add(LuaMethod.Builder.create("getUnknownList").withOwner(TEST_LUA_CLASS) .withReturnType(LUA_ARRAY_LIST_UNKNOWN).withVarArg(true).withParams( ImmutableList.of(new LuaParameter(LUA_ARRAY_LIST_UNKNOWN, "varargs"))).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---@vararg Object", "---@return Object", "function ZomboidLuaDocTest:getObject(...) end", "", "---@param param Object[]", "---@vararg String", "---@return String", "function ZomboidLuaDocTest:getText(param, ...) end", "", "---@param param0 Object", "---@param param1 Integer", "---@vararg String", "---@return Integer", "function ZomboidLuaDocTest:getNumber(param0, param1, ...) end", "", "---@vararg ArrayList", "---@return ArrayList|Object", "function ZomboidLuaDocTest:getObjectList(...) end", "", "---@param param1 Object", "---@vararg ArrayList", "---@return ArrayList|String|Object", "function ZomboidLuaDocTest:getStringObjectList(param1, ...) end", "", "---@param param1 Object", "---@param param2 ArrayList|String|Object", "---@vararg Object[]", "---@return ArrayList|ZomboidLuaDocTest.InnerClass", "function ZomboidLuaDocTest:getInnerClassList(param1, param2, ...) end", "", "---@vararg ArrayList", "---@return ArrayList|Unknown", "function ZomboidLuaDocTest:getUnknownList(...) end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldNotWriteGlobalZomboidLuaDocMethodsAsPartOfTableToFile() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("firstMethod").build() ); luaMethods.add(LuaMethod.Builder.create("secondMethod") .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)).build() ); luaMethods.add(LuaMethod.Builder.create("thirdMethod") .withModifier(new MemberModifier(AccessModifierKey.PRIVATE)) .withReturnType(new LuaType("String")).build() ); luaMethods.add(LuaMethod.Builder.create("fourthMethod").withOwner(TEST_LUA_CLASS) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT)) .withReturnType(new LuaType("Object")).withParams(ImmutableList.of( new LuaParameter(new LuaType("int"), "param1"), new LuaParameter(new LuaType("boolean"), "param2"))).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( new LuaClass("LuaManager_GlobalObject", JavaCompiler.GLOBAL_OBJECT_CLASS), new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class LuaManager_GlobalObject : " + JavaCompiler.GLOBAL_OBJECT_CLASS, "LuaManager_GlobalObject = {}", "", "---@return void", "function firstMethod() end", "", "---@public", "---@return void", "function secondMethod() end", "", "---@private", "---@return String", "function thirdMethod() end", "", "---@param param1 int", "---@param param2 boolean", "---@return Object", "function fourthMethod(param1, param2) end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test @SuppressWarnings("ConstantConditions") void shouldThrowExceptionWhenModifyingImmutableFields() { LuaType type = new LuaType(Object.class.getName()); ZomboidLuaDoc zDoc = new ZomboidLuaDoc(new LuaClass(type.getName())); Assertions.assertThrows(UnsupportedOperationException.class, () -> zDoc.getFields().add(new LuaField(type, "field", MemberModifier.UNDECLARED)) ); Assertions.assertThrows(UnsupportedOperationException.class, () -> zDoc.getMethods().add(LuaMethod.Builder.create("testMethod").withReturnType(type).build()) ); } @Test void shouldWriteZomboidLuaDocMethodsWithValidReturnTypeComments() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getObject").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Object"), "returns a simple object") .build() ); luaMethods.add(LuaMethod.Builder.create("getNumber").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Number"), "returns a simple number") .withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "param")) ).build() ); luaMethods.add(LuaMethod.Builder.create("getString").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("String"), "returns a simple string") .withVarArg(true).withParams(ImmutableList.of( new LuaParameter(new LuaType("Object"), "varargs")) ).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---@return Object @returns a simple object", "function ZomboidLuaDocTest:getObject() end", "", "---@param param Object", "---@return Number @returns a simple number", "function ZomboidLuaDocTest:getNumber(param) end", "", "---@vararg Object", "---@return String @returns a simple string", "function ZomboidLuaDocTest:getString(...) end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldWriteZomboidLuaDocMethodsWithValidParameterComments() throws IOException { Set<LuaMethod> luaMethods = new LinkedHashSet<>(); luaMethods.add(LuaMethod.Builder.create("getObject").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Object")) .withParams(new LuaParameter(new LuaType("Object"), "arg0", "object to get")) .build() ); luaMethods.add(LuaMethod.Builder.create("getNumber").withOwner(TEST_LUA_CLASS) .withReturnType(new LuaType("Number"), "returns a simple number") .withParams(ImmutableList.of( new LuaParameter(new LuaType("String"), "arg0", "some string param"), new LuaParameter(new LuaType("Number"), "arg1", "some number param") )).build() ); luaMethods.add(LuaMethod.Builder.create("getString").withOwner(TEST_LUA_CLASS).withVarArg(true) .withReturnType(new LuaType("String"), "returns a simple string") .withParams(ImmutableList.of( new LuaParameter(new LuaType("String"), "arg0", "some string param"), new LuaParameter(new LuaType("Number"), "arg1", "some number param"), new LuaParameter(new LuaType("Object"), "arg2", "variadic argument") )).build() ); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), luaMethods ); List<String> expectedResult = ImmutableList.of( "---@class ZomboidLuaDocTest : io.cocolabs.pz.zdoc.doc.ZomboidLuaDocTest", "ZomboidLuaDocTest = {}", "", "---@param arg0 Object @object to get", "---@return Object", "function ZomboidLuaDocTest:getObject(arg0) end", "", "---@param arg0 String @some string param", "---@param arg1 Number @some number param", "---@return Number @returns a simple number", "function ZomboidLuaDocTest:getNumber(arg0, arg1) end", "", "---@param arg0 String @some string param", "---@param arg1 Number @some number param", "---@vararg Object @variadic argument", "---@return String @returns a simple string", "function ZomboidLuaDocTest:getString(arg0, arg1, ...) end" ); Assertions.assertEquals(expectedResult, writeToFileAndRead(zDoc)); } @Test void shouldOverloadZomboidLuaDocMethods() { LuaMethod[] expectedMethodsOrdered = new LuaMethod[] { LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0")) .build(), LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1") ).build(), LuaMethod.Builder.create("testMethod").withParams( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1"), new LuaParameter(new LuaType("String"), "arg2") ).build(), LuaMethod.Builder.create("notOverloadedMethod").build() }; Set<LuaMethod> expectedMethodsUnordered = new HashSet<>(Arrays.asList(expectedMethodsOrdered)); ZomboidLuaDoc zDoc = new ZomboidLuaDoc( TEST_LUA_CLASS, new ArrayList<>(), expectedMethodsUnordered ); Set<LuaMethod> methods = zDoc.getMethods(); Assertions.assertEquals(expectedMethodsOrdered.length, methods.size()); Iterator<LuaMethod> iter = methods.iterator(); LuaMethod firstMethod = iter.next(); // assert that notOverloadedMethod is first or last method if (!firstMethod.equals(expectedMethodsOrdered[0])) { Assertions.assertEquals(expectedMethodsOrdered[3], firstMethod); // assert correct method order in sorted collection for (int i = 0; i < expectedMethodsOrdered.length - 1; i++) { Assertions.assertEquals(expectedMethodsOrdered[i], iter.next()); } } else { Assertions.assertEquals(expectedMethodsOrdered[0], firstMethod); // assert correct method order in sorted collection for (int i = 1; i < expectedMethodsOrdered.length; i++) { Assertions.assertEquals(expectedMethodsOrdered[i], iter.next()); } } EmmyLuaOverload[] expectedOverloadAnnotations = new EmmyLuaOverload[] { new EmmyLuaOverload(expectedMethodsOrdered[1].getParams()), new EmmyLuaOverload(expectedMethodsOrdered[2].getParams()) }; List<EmmyLuaOverload> actualOverloadAnnotations = new ArrayList<>(); firstMethod.getAnnotations().stream().filter(a -> a instanceof EmmyLuaOverload) .forEach(a -> actualOverloadAnnotations.add((EmmyLuaOverload) a)); for (int i = 0; i < actualOverloadAnnotations.size(); i++) { String expected = expectedOverloadAnnotations[i].toString(); Assertions.assertEquals(expected, actualOverloadAnnotations.get(i).toString()); } } @TestOnly private List<String> writeToFileAndRead(ZomboidLuaDoc zDoc) throws IOException { zDoc.writeToFile(file); return readFile(); } @TestOnly @SuppressWarnings("unused") private static class InnerClass { } }
24,641
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
TypeSignatureParserTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/TypeSignatureParserTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.element.java.JavaClass; class TypeSignatureParserTest { @Test void shouldParseUnknownClassAsNullElement() { Set<String> unknownClassSignatures = Sets.newHashSet( "io.cocolabs.unknownClass", "io.cocolabs.unknownClass<java.lang.Object>", "io.cocolabs.unknownClass<java.lang.Object, java.lang.String>" ); for (String signature : unknownClassSignatures) { Assertions.assertNull(TypeSignatureParser.parse(signature)); } } @Test void shouldParseJavaClassFromSignature() { Set<Class<?>> classSignatures = Sets.newHashSet( java.lang.String.class, java.lang.Object.class, java.lang.Integer[].class, int.class, int[].class ); for (Class<?> signature : classSignatures) { JavaClass result = TypeSignatureParser.parse(signature.getName()); List<JavaClass> typeParameters = Objects.requireNonNull(result).getTypeParameters(); Assertions.assertEquals(0, typeParameters.size()); Assertions.assertEquals(signature.getTypeName(), result.getName()); } } @Test void shouldParseJavaClassTypeParametersFromSignature() { Map<String, String[]> classTypeParametersFromSignature = ImmutableMap.<String, String[]>builder() .put("java.util.Map<java.lang.String>", new String[]{ "java.lang.String" }) .put("java.util.Map<java.lang.String, java.lang.Object>", new String[]{ "java.lang.String", "java.lang.Object" }) .put("java.util.Map<java.lang.String, java.lang.Class<?>>", new String[]{ "java.lang.String", "java.lang.Class<?>" }) .put("java.util.Map<java.lang.String, java.lang.Class<java.lang.Object>>", new String[]{ "java.lang.String", "java.lang.Class<java.lang.Object>" }) .put("java.util.Map<java.lang.String, java.lang.Class<java.lang.Object<?>>>", new String[]{ "java.lang.String", "java.lang.Class<java.lang.Object<?>>" }) .put("java.util.Map<java.lang.Class<java.lang.Object<?>>, " + "java.lang.Class<java.lang.Object<?>>>", new String[]{ "java.lang.Class<java.lang.Object<?>>", "java.lang.Class<java.lang.Object<?>>" }) .put("java.util.Map<java.lang.String, java.lang.Object, java.lang.Integer>", new String[]{ "java.lang.String", "java.lang.Object", "java.lang.Integer" }) .put("java.util.Map<java.lang.Class<java.lang.Class<?>>, " + "java.util.Map<java.lang.Class<?>, java.lang.Object>, " + "java.util.Map<java.lang.Object, java.lang.Class<?>>>", new String[]{ "java.lang.Class<java.lang.Class<?>>", "java.util.Map<java.lang.Class<?>, java.lang.Object>", "java.util.Map<java.lang.Object, java.lang.Class<?>>" }).build(); for (Map.Entry<String, String[]> entry : classTypeParametersFromSignature.entrySet()) { String signature = entry.getKey(); String[] expected = entry.getValue(); JavaClass result = TypeSignatureParser.parse(signature); List<JavaClass> typeParameters = Objects.requireNonNull(result).getTypeParameters(); Assertions.assertEquals(expected.length, typeParameters.size()); for (int i = 0; i < typeParameters.size(); i++) { Assertions.assertEquals(expected[i], typeParameters.get(i).toString()); } } } }
4,234
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
DetailTestFixture.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/DetailTestFixture.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.Set; import java.util.function.Supplier; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.TestInstance; import org.junit.platform.commons.util.StringUtils; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.doc.DocTest; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; @TestInstance(TestInstance.Lifecycle.PER_CLASS) abstract class DetailTestFixture<T extends Detail<?>> extends DocTest { static final String[] PRIMITIVE_TYPES = new String[]{ "boolean", "byte", "char", "short", "int", "long", "float", "double", "void" }; private static final Set<Set<ModifierKey>> MODIFIER_KEY_COMBINATIONS = Sets.powerSet(Sets.newHashSet(ModifierKey.values())); final T detail; DetailTestFixture(@NotNull T detail) { this.detail = detail; } @TestOnly static <T extends SignatureSupplier<?>> void assertMatchInSignature(String text, String expected, Class<T> supplier) { for (AccessModifierKey access : AccessModifierKey.values()) { for (Set<ModifierKey> modifierKeys : MODIFIER_KEY_COMBINATIONS) { ModifierKey[] keyArray = modifierKeys.toArray(new ModifierKey[0]); MemberModifier modifier = new MemberModifier(access, keyArray); String sModifier = modifier.toString(); String sSignature = (!StringUtils.isBlank(sModifier) ? sModifier + " " : "") + text; try { T signature = supplier.getDeclaredConstructor(String.class).newInstance(sSignature); Assertions.assertEquals(expected, signature.get()); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } } } static abstract class SignatureSupplier<T extends DetailSignature> implements Supplier<String> { final T signature; SignatureSupplier(T signature) { this.signature = signature; } } }
2,802
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
DetailTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/DetailTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.*; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.doc.DocTest; import io.cocolabs.pz.zdoc.element.IMember; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; class DetailTest extends DetailTestFixture<DetailTest.TestDetail> { DetailTest() throws DetailParsingException { super(new TestDetail()); } @Test void shouldGetValidParsedDetailObject() { String[] entryNames = new String[]{ "innerClass", "deepInnerClass", "getData" }; Elements detail = this.detail.getDetail(); Assertions.assertEquals(entryNames.length, detail.size()); for (int i = 0; i < detail.size(); i++) { Element blockList = detail.get(i); Element header = blockList.getElementsByTag("h4").first(); Assertions.assertEquals(entryNames[i], header.text()); } } @Test void shouldCorrectlyQualifyZomboidClassElements() throws DetailParsingException { LinkedHashMap<String, String> qualifiedNames = new LinkedHashMap<>(); qualifiedNames.put( "public Test.InnerClass innerClass", "public zombie.Test.InnerClass innerClass" ); qualifiedNames.put( "public Test.InnerClass.DeepInnerClass deepInnerClass", "public zombie.Test.InnerClass$DeepInnerClass deepInnerClass" ); qualifiedNames.put( "public float getData(TestData data)", "public float getData(zombie.TestData data)" ); Elements detail = this.detail.getDetail(); Assertions.assertEquals(qualifiedNames.size(), detail.size()); int i = -1; for (Map.Entry<String, String> entry : qualifiedNames.entrySet()) { Element blockList = detail.get(i += 1); Element pre = blockList.getElementsByTag("pre").first(); Assertions.assertEquals(entry.getKey(), DetailSignature.normalizeElement(pre)); Element signature = this.detail.qualifyZomboidClassElements(pre); Assertions.assertEquals(entry.getValue(), DetailSignature.normalizeElement(signature)); } } @Test void shouldThrowExceptionWhenModifyingDetailMembers() { Assertions.assertThrows(UnsupportedOperationException.class, () -> new TestDetail().getEntries().add(new TestMember())); } private static class TestMember implements IMember { @Override public String getName() { return null; } @Override public MemberModifier getModifier() { return null; } @Override public String getComment() { return null; } } static class TestDetail extends Detail<TestMember> { private TestDetail() throws DetailParsingException { super("test.detail", DocTest.DOCUMENT); } @Override public Set<TestMember> getEntries(String name) { return new HashSet<>(); } @Override protected List<TestMember> parse() { return ImmutableList.of(new TestMember()); } } }
3,662
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MethodSignatureParserTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/MethodSignatureParserTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.JavaClassUtils; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaParameter; class MethodSignatureParserTest { @Test void shouldThrowExceptionWhenParsingUnknownClasses() { Set<String> unknownMethodSignatures = Sets.newHashSet( "io.cocolabs.unknownClass param", "io.cocolabs.unknownClass<java.lang.Object> param", "io.cocolabs.unknownClass<java.lang.Object, java.lang.String> param", "java.lang.Object param0, io.cocolabs.unknownClass param1", "java.lang.Object param0, io.cocolabs.unknownClass<java.lang.Object> param", "java.lang.Object param0, io.cocolabs.unknownClass<java.lang.Object, java.lang.String> param" ); for (String signature : unknownMethodSignatures) { Assertions.assertThrows(SignatureParsingException.class, () -> new MethodSignatureParser(signature).parse()); } } @Test void shouldThrowExceptionWhenParsingMalformedSignature() { Set<String> malformedSignatures = Sets.newHashSet( "someParameterName", // missing parameter type "java.lang.Object", // missing parameter name " ," // missing parameter type and name ); for (String signature : malformedSignatures) { Assertions.assertThrows(SignatureParsingException.class, () -> new MethodSignatureParser(signature).parse()); } } @Test void shouldParseJavaParametersFromSignature() throws SignatureParsingException { List<String> parameterSignatures = ImmutableList.of( "java.lang.String param", "java.lang.String[] params", "java.lang.Object param0, java.lang.String param1", "java.lang.Object param0, java.lang.String param1, java.lang.Integer param2", "java.lang.Object[] param0, java.lang.String[] param1", "int[] params", "int param0, boolean param1", "int[] params0, boolean[] params1, char param2" ); List<List<JavaParameter>> expectedParameters = ImmutableList.of( Collections.singletonList( new JavaParameter(new JavaClass(String.class), "param") ), Collections.singletonList( new JavaParameter(new JavaClass(String[].class), "params") ), ImmutableList.of( new JavaParameter(new JavaClass(Object.class), "param0"), new JavaParameter(new JavaClass(String.class), "param1") ), ImmutableList.of( new JavaParameter(new JavaClass(Object.class), "param0"), new JavaParameter(new JavaClass(String.class), "param1"), new JavaParameter(new JavaClass(Integer.class), "param2") ), ImmutableList.of( new JavaParameter(new JavaClass(Object[].class), "param0"), new JavaParameter(new JavaClass(String[].class), "param1") ), Collections.singletonList( new JavaParameter(new JavaClass(int[].class), "params") ), ImmutableList.of( new JavaParameter(new JavaClass(int.class), "param0"), new JavaParameter(new JavaClass(boolean.class), "param1") ), ImmutableList.of( new JavaParameter(new JavaClass(int[].class), "params0"), new JavaParameter(new JavaClass(boolean[].class), "params1"), new JavaParameter(new JavaClass(char.class), "param2") ) ); for (int i = 0; i < parameterSignatures.size(); i++) { String signature = parameterSignatures.get(i); List<JavaParameter> actual = new MethodSignatureParser(signature).parse(); Assertions.assertEquals(expectedParameters.get(i), actual); } } @Test void shouldParseJavaParametersWithTypeParametersFromSignature() throws SignatureParsingException { List<String> parameterSignatures = ImmutableList.of( "java.util.ArrayList<java.lang.Object> param", "java.util.ArrayList<java.lang.Class<?>> param", "java.util.Map<java.lang.Object, java.lang.String>> param", "java.util.Map<java.lang.Integer, java.lang.Class<?>> param", "java.util.ArrayList<java.lang.Object> param0, " + "java.util.ArrayList<java.lang.Integer> param1", "java.util.ArrayList<java.lang.Class<?>> param0, " + "java.util.ArrayList<java.lang.Integer> param1", "java.util.Map<java.lang.Object, java.lang.String>> param0, " + "java.util.Map<java.lang.String, java.lang.Integer>> param1", "java.util.Map<java.lang.String, java.lang.Class<?>> param0, " + "java.util.Map<java.lang.Object, java.lang.Class<?>> param1" ); List<List<JavaParameter>> expectedParameters = ImmutableList.of( // java.util.ArrayList<java.lang.Object> param Collections.singletonList( new JavaParameter(JavaClassUtils.getList(Object.class), "param") ), // java.util.ArrayList<java.lang.Class<?>> param Collections.singletonList( new JavaParameter(JavaClassUtils.getList(JavaClassUtils.CLASS), "param") ), // java.util.Map<java.lang.Object, java.lang.String>> param ImmutableList.of( new JavaParameter(JavaClassUtils.getMap(Object.class, String.class), "param") ), // java.util.Map<java.lang.Integer, java.lang.Class<?>> param ImmutableList.of( new JavaParameter(JavaClassUtils.getMap( Integer.class, JavaClassUtils.CLASS), "param") ), // java.util.ArrayList<java.lang.Object> param0, // java.util.ArrayList<java.lang.Integer> param1 ImmutableList.of( new JavaParameter(JavaClassUtils.getList(Object.class), "param0"), new JavaParameter(JavaClassUtils.getList(Integer.class), "param1") ), // java.util.ArrayList<java.lang.Class<?>> param0, // java.util.ArrayList<java.lang.Integer> param1 ImmutableList.of( new JavaParameter(JavaClassUtils.getList(JavaClassUtils.CLASS), "param0"), new JavaParameter(JavaClassUtils.getList(Integer.class), "param1") ), // java.util.Map<java.lang.Object, java.lang.String>> param0, // java.util.Map<java.lang.String, java.lang.Integer>> param ImmutableList.of( new JavaParameter(JavaClassUtils.getMap(Object.class, String.class), "param0"), new JavaParameter(JavaClassUtils.getMap(String.class, Integer.class), "param1") ), // java.util.Map<java.lang.String, java.lang.Class<?>> param0, // java.util.Map<java.lang.Object, java.lang.Class<?>> param1 ImmutableList.of( new JavaParameter(JavaClassUtils.getMap( String.class, JavaClassUtils.CLASS), "param0" ), new JavaParameter(JavaClassUtils.getMap( Object.class, JavaClassUtils.CLASS), "param1") ) ); for (int i = 0; i < parameterSignatures.size(); i++) { String signature = parameterSignatures.get(i); List<JavaParameter> actual = new MethodSignatureParser(signature).parse(); Assertions.assertEquals(expectedParameters.get(i), actual); } } @Test void shouldParseJavaParametersWithVariadicArgumentsFromSignature() throws SignatureParsingException { List<String> parameterSignatures = ImmutableList.of( "java.lang.Object param, java.lang.String... varargs0", "java.lang.Object param, int... varargs1", "java.lang.Object param0, java.lang.String param1, boolean... varargs2", "java.util.ArrayList<java.lang.Class<?>> param0, char param1, java.lang.String... varargs3", "boolean[] param0, java.lang.String[] param1, " + "java.util.ArrayList<java.lang.Class<?>>... varargs4" ); List<List<JavaParameter>> expectedParameters = ImmutableList.of( // java.lang.Object param, java.lang.String... varargs ImmutableList.of( new JavaParameter(new JavaClass(Object.class), "param"), new JavaParameter(new JavaClass(String.class), "varargs0") ), // java.lang.Object param, int... varargs ImmutableList.of( new JavaParameter(new JavaClass(Object.class), "param"), new JavaParameter(new JavaClass(int.class), "varargs1") ), // java.lang.Object param0, java.lang.String param1, boolean... varargs ImmutableList.of( new JavaParameter(new JavaClass(Object.class), "param0"), new JavaParameter(new JavaClass(String.class), "param1"), new JavaParameter(new JavaClass(boolean.class), "varargs2") ), // java.util.ArrayList<java.lang.Class<?>> param0, char param1, java.lang.String... varargs ImmutableList.of( new JavaParameter(JavaClassUtils.getList(JavaClassUtils.CLASS), "param0"), new JavaParameter(new JavaClass(char.class), "param1"), new JavaParameter(new JavaClass(String.class), "varargs3") ), // boolean[] param0, java.lang.String[] param1, java.util.ArrayList<java.lang.Class<?>>... // varargs ImmutableList.of( new JavaParameter(new JavaClass(boolean[].class), "param0"), new JavaParameter(new JavaClass(String[].class), "param1"), new JavaParameter(JavaClassUtils.getList(JavaClassUtils.CLASS), "varargs4") ) ); for (int i = 0; i < parameterSignatures.size(); i++) { String signature = parameterSignatures.get(i); MethodSignatureParser parser = new MethodSignatureParser(signature); Assertions.assertEquals(expectedParameters.get(i), parser.parse()); Assertions.assertTrue(parser.isVarArg()); } } }
10,056
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MethodDetailTestFixture.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/MethodDetailTestFixture.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import io.cocolabs.pz.zdoc.doc.DocTest; class MethodDetailTestFixture extends DetailTestFixture<MethodDetail> { MethodDetailTestFixture() throws DetailParsingException { super(new MethodDetail(DocTest.DOCUMENT)); } abstract static class MethodSignatureSupplier extends SignatureSupplier<MethodDetail.Signature> { MethodSignatureSupplier(String signature) throws DetailParsingException { super(new MethodDetail.Signature(signature)); } } static class ReturnTypeSupplier extends MethodSignatureSupplier { ReturnTypeSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.returnType; } } static class NameSupplier extends MethodSignatureSupplier { NameSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.name; } } static class ParamsSupplier extends MethodSignatureSupplier { ParamsSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.params; } } static class CommentSupplier extends MethodSignatureSupplier { CommentSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.comment; } } }
2,173
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
FieldDetailTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/FieldDetailTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; import zombie.core.Color; @SuppressWarnings("SpellCheckingInspection") class FieldDetailTest extends FieldDetailTestFixture { FieldDetailTest() throws DetailParsingException { } @Test void shouldMatchAccessModifierInFieldSignature() throws DetailParsingException { Map<AccessModifierKey, String> fieldsWithAccessKeyword = ImmutableMap.of( AccessModifierKey.PUBLIC, "public int myField", AccessModifierKey.PRIVATE, "private boolean myField", AccessModifierKey.PROTECTED, "protected char myField", AccessModifierKey.DEFAULT, "java.lang.String myField" ); for (Map.Entry<AccessModifierKey, String> entry : fieldsWithAccessKeyword.entrySet()) { FieldDetail.Signature signature = new FieldDetail.Signature(entry.getValue()); Assertions.assertEquals(entry.getKey(), signature.modifier.getAccess()); } } @Test void shouldMatchNonAccessModifiersInFieldSignature() throws DetailParsingException { Map<ModifierKey, String> fieldsWithNonAccessModifier = ImmutableMap.of( ModifierKey.STATIC, "static int myField", ModifierKey.FINAL, "final char myField", ModifierKey.ABSTRACT, "abstract java.lang.Object myField" ); for (Map.Entry<ModifierKey, String> entry : fieldsWithNonAccessModifier.entrySet()) { FieldDetail.Signature signature = new FieldDetail.Signature(entry.getValue()); Assertions.assertTrue(signature.modifier.matchesModifiers(entry.getKey())); } } @Test void shouldMatchMixedModifiersInFieldSignature() throws DetailParsingException { Map<MemberModifier, String> fieldsWithMixedModifiers = ImmutableMap.of( new MemberModifier(AccessModifierKey.PUBLIC, ModifierKey.STATIC), "public static float myField", new MemberModifier(AccessModifierKey.PRIVATE, ModifierKey.STATIC, ModifierKey.FINAL), "private static final java.lang.Object myField", new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.ABSTRACT), "abstract int myField" ); for (Map.Entry<MemberModifier, String> entry : fieldsWithMixedModifiers.entrySet()) { FieldDetail.Signature signature = new FieldDetail.Signature(entry.getValue()); Assertions.assertEquals(entry.getKey(), signature.modifier); } } @Test void shouldMatchObjectTypeInFieldSignature() { Map<String, String> fieldsWithObjectType = ImmutableMap.of( "int", "int myField", "boolean[]", "boolean[] myField", "java.lang.String", "java.lang.String myField", "java.lang.Object[]", "final java.lang.Object[] myField" ); for (Map.Entry<String, String> entry : fieldsWithObjectType.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), TypeSupplier.class); } } @Test void shouldMatchParameterizedObjectTypeInFieldSignature() { Map<String, String> fieldsWithParameterizedObjectType = ImmutableMap.of( "java.util.ArrayList<java.lang.Class<?>,java.lang.Class<?>>", "java.util.ArrayList<java.lang.Class<?>,java.lang.Class<?>> myField", "java.util.ArrayList<java.lang.Class<?>>", "java.util.ArrayList<java.lang.Class<?>> myField", "java.util.ArrayList<java.lang.String>", "final java.util.ArrayList<java.lang.String> myField", "java.util.ArrayList<T>", "java.util.ArrayList<T> myField" ); for (Map.Entry<String, String> entry : fieldsWithParameterizedObjectType.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), TypeSupplier.class); } } @Test void shouldMatchPrimitiveReturnTypeInFieldSignature() { for (String type : PRIMITIVE_TYPES) { assertMatchInSignature(type + " myField", type, TypeSupplier.class); } } @Test void shouldMatchNameInFieldSignature() { Map<String, String> fieldsWithNames = ImmutableMap.of( "myField", "int myField", "my_field", "char my_field", "my$field", "java.lang.Integer my$field", "1myF13ld", "java.lang.Object[] 1myF13ld", "field", "my.Test<my_Class<?>> field" ); for (Map.Entry<String, String> entry : fieldsWithNames.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), NameSupplier.class); } } @Test void shouldMatchCommentInMethodSignature() { Map<String, String> methodsWithComment = ImmutableMap.of( "// comment", "void myField // comment", "onewordcomment", "int myField onewordcomment", "multi word comment", "java.lang.ArrayList<Class<?>> myField multi word comment", "!@# $%^&*_ {()comment", "char[] myField !@# $%^&*_ {()comment" ); for (Map.Entry<String, String> entry : methodsWithComment.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), CommentSupplier.class); } } @Test void shouldParseValidModifierKeyFromFieldDetail() { List<JavaField> entries = detail.getEntries(); ModifierKey[][] expectedFieldModifierKeys = new ModifierKey[][]{ new ModifierKey[]{ ModifierKey.UNDECLARED, // a }, new ModifierKey[]{ ModifierKey.FINAL // b }, new ModifierKey[]{ ModifierKey.STATIC, // black ModifierKey.FINAL }, new ModifierKey[]{ ModifierKey.STATIC, // blue }, new ModifierKey[]{ ModifierKey.UNDECLARED // cyan }, }; Assertions.assertEquals(expectedFieldModifierKeys.length, entries.size()); for (int i = 0; i < entries.size(); i++) { ModifierKey[] keys = expectedFieldModifierKeys[i]; Assertions.assertTrue(entries.get(i).getModifier().matchesModifiers(keys)); } } @Test void shouldParseValidAccessModifierFromFieldDetail() { List<JavaField> entries = detail.getEntries(); AccessModifierKey[] expectedModifiers = new AccessModifierKey[]{ AccessModifierKey.PUBLIC, // begin AccessModifierKey.PRIVATE, // doesInstantly AccessModifierKey.PROTECTED, // init AccessModifierKey.DEFAULT, // isFinished AccessModifierKey.PUBLIC, // update }; Assertions.assertEquals(expectedModifiers.length, entries.size()); for (int i = 0; i < entries.size(); i++) { Assertions.assertTrue(entries.get(i).getModifier().hasAccess(expectedModifiers[i])); } } @Test void shouldParseValidObjectTypesFromFieldDetail() { List<JavaField> entries = detail.getEntries(); JavaClass[] expectedTypes = new JavaClass[]{ new JavaClass(float.class), // a new JavaClass(Integer.class), // b new JavaClass(Color.class), // black new JavaClass(Color[].class), // blue new JavaClass(ArrayList.class, // cyan new JavaClass(Color.class)) }; Assertions.assertEquals(expectedTypes.length, entries.size()); for (int i = 0; i < expectedTypes.length; i++) { Assertions.assertEquals(expectedTypes[i], entries.get(i).getType()); } } @Test void shouldParseValidNamesFromFieldDetail() { List<JavaField> entries = detail.getEntries(); String[] expectedFieldNames = new String[]{ "a", "b", "black", "blue", "cyan" }; Assertions.assertEquals(expectedFieldNames.length, entries.size()); for (int i = 0; i < entries.size(); i++) { JavaField entry = entries.get(i); Assertions.assertEquals(expectedFieldNames[i], entry.getName()); } } @Test void shouldParseValidFieldDetailComments() { List<JavaField> entries = detail.getEntries(); String[] expectedComments = new String[]{ "The alpha component of the colour", "The blue component of the colour", "The fixed colour black", "The fixed colour blue", "The fixed colour cyan" }; Assertions.assertEquals(expectedComments.length, entries.size()); for (int i = 0; i < entries.size(); i++) { Assertions.assertEquals(expectedComments[i], entries.get(i).getComment()); } } @Test void shouldGetCorrectFieldDetailEntriesByName() { List<JavaField> expectedJavaFieldEntries = ImmutableList.of( new JavaField(float.class, "a", new MemberModifier( AccessModifierKey.PUBLIC, ModifierKey.UNDECLARED )), new JavaField(Integer.class, "b", new MemberModifier( AccessModifierKey.PRIVATE, ModifierKey.FINAL )), new JavaField(Color.class, "black", new MemberModifier( AccessModifierKey.PROTECTED, ModifierKey.STATIC, ModifierKey.FINAL )), new JavaField(Color[].class, "blue", new MemberModifier( AccessModifierKey.DEFAULT, ModifierKey.STATIC )), new JavaField(new JavaClass(ArrayList.class, new JavaClass(Color.class)), "cyan", new MemberModifier(AccessModifierKey.PUBLIC) ) ); Assertions.assertEquals(expectedJavaFieldEntries.size(), detail.getEntries().size()); for (JavaField field : expectedJavaFieldEntries) { Assertions.assertEquals(field, detail.getEntry(field.getName())); } } }
10,063
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
MethodDetailTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/MethodDetailTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import java.util.*; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.cocolabs.pz.zdoc.JavaClassUtils; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.java.JavaParameter; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; import zombie.characters.IsoPlayer; import zombie.core.Color; @SuppressWarnings("SpellCheckingInspection") class MethodDetailTest extends MethodDetailTestFixture { MethodDetailTest() throws DetailParsingException { } @Test void shouldMatchAccessModifierInMethodSignature() throws DetailParsingException { Map<AccessModifierKey, String> methodsWithAccessKeyword = ImmutableMap.of( AccessModifierKey.PUBLIC, "public void myMethod()", AccessModifierKey.PRIVATE, "private void myMethod()", AccessModifierKey.PROTECTED, "protected void myMethod()", AccessModifierKey.DEFAULT, "void myMethod()" ); for (Map.Entry<AccessModifierKey, String> entry : methodsWithAccessKeyword.entrySet()) { MethodDetail.Signature signature = new MethodDetail.Signature(entry.getValue()); Assertions.assertEquals(entry.getKey(), signature.modifier.getAccess()); } } @Test void shouldMatchNonAccessModifiersInMethodSignature() throws DetailParsingException { Map<ModifierKey, String> methodsWithNonAccessModifier = ImmutableMap.of( ModifierKey.STATIC, "static void myMethod()", ModifierKey.FINAL, "final void myMethod()", ModifierKey.ABSTRACT, "abstract void myMethod()" ); for (Map.Entry<ModifierKey, String> entry : methodsWithNonAccessModifier.entrySet()) { MethodDetail.Signature signature = new MethodDetail.Signature(entry.getValue()); Assertions.assertTrue(signature.modifier.matchesModifiers(entry.getKey())); } } @Test void shouldMatchMixedModifiersInMethodSignature() throws DetailParsingException { Map<MemberModifier, String> methodsWithMixedModifiers = ImmutableMap.of( new MemberModifier(AccessModifierKey.PUBLIC, ModifierKey.STATIC), "public static void myMethod()", new MemberModifier(AccessModifierKey.PRIVATE, ModifierKey.STATIC, ModifierKey.FINAL), "private static final void myMethod()", new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.ABSTRACT), "abstract void myMethod()" ); for (Map.Entry<MemberModifier, String> entry : methodsWithMixedModifiers.entrySet()) { MethodDetail.Signature signature = new MethodDetail.Signature(entry.getValue()); Assertions.assertEquals(entry.getKey(), signature.modifier); } } @Test void shouldMatchReturnTypeInMethodSignature() { Map<String, String> methodsWithReturnType = ImmutableMap.of( "void", "void myMethod()", "int[]", "int[] myMethod(boolean param)", "java.lang.String", "java.lang.String myMethod()", "java.lang.Object", "java.lang.Object myMethod()", "java.lang.Object[]", "java.lang.Object[] myMethod()" ); for (Map.Entry<String, String> entry : methodsWithReturnType.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), ReturnTypeSupplier.class); } } @Test void shouldMatchParameterizedReturnTypeInMethodSignature() { Map<String, String> methodsWithParameterizedReturnType = ImmutableMap.of( "java.util.ArrayList<java.lang.Class<?>>", "java.util.ArrayList<java.lang.Class<?>> myMethod()", "java.util.ArrayList<java.lang.String>", "java.util.ArrayList<java.lang.String> myMethod()", "java.util.ArrayList<T>", "java.util.ArrayList<T> myMethod()" ); for (Map.Entry<String, String> entry : methodsWithParameterizedReturnType.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), ReturnTypeSupplier.class); } } @Test void shouldMatchPrimitiveReturnTypeInMethodSignature() { for (String type : PRIMITIVE_TYPES) { assertMatchInSignature(type + " myMethod()", type, ReturnTypeSupplier.class); } } @Test void shouldMatchNameInMethodSignature() { Map<String, String> methodsWithNames = ImmutableMap.of( "myMethod", "void myMethod(java.lang.Object param)", "my_method", "void my_method(java.lang.Object param)", "my$method", "java.lang.Integer my$method(java.lang.Object param)", "1myM3thod", "void 1myM3thod(java.lang.Object param)", "method", "my.Test<my.Class<?>> method(java.lang.Object param)" ); for (Map.Entry<String, String> entry : methodsWithNames.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), NameSupplier.class); } } @Test void shouldMatchParametersInMethodSignature() { Map<String, String> methodsWithParameters = ImmutableMap.<String, String>builder() .put("java.lang.Object param", "void myMethod(java.lang.Object param)") .put("java.lang.Object param1, java.lang.Object param2", "void myMethod(java.lang.Object param1, java.lang.Object param2)") .put("java.lang.Object param1, java.lang.Object param2, java.lang.String param3", "java.lang.Integer myMethod(java.lang.Object param1," + " java.lang.Object param2, java.lang.String param3)") .put("java.lang.Object param1, java.lang.Object param2, java.lang.Integer param3", "void myMethod(java.lang.Object param1, java.lang.Object param2, " + "java.lang.Integer param3)") .put("java.lang.Object param0, java.lang.Object param1", "void myMethod(java.lang.Object param0, java.lang.Object param1)") .put("java.lang.Object param1", "void myMethod(java.lang.Object param1)") .put("java.lang.Object param0", "java.util.ArrayList<java.lang.Class<?>> myMethod(java.lang.Object param0)").build(); for (Map.Entry<String, String> entry : methodsWithParameters.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), ParamsSupplier.class); } } @Test void shouldMatchPrimitiveTypeParametersInMethodSignature() { Map<String, String> methodsWithPrimitiveTypeParameters = new HashMap<>(); for (String type : PRIMITIVE_TYPES) { String param1 = type + " param"; methodsWithPrimitiveTypeParameters.put( param1, String.format("void myMethod(%s)", param1) ); String param2 = type + " param1, " + type + " param2"; methodsWithPrimitiveTypeParameters.put( param2, String.format("void myMethod(%s)", param2) ); String param3 = String.format("%s param1, %s param2, %s param3", type, type, type); methodsWithPrimitiveTypeParameters.put( param3, String.format("java.lang.Integer myMethod(%s)", param3) ); methodsWithPrimitiveTypeParameters.put( param3, String.format("void myMethod(%s)", param3) ); methodsWithPrimitiveTypeParameters.put( param2, String.format("void myMethod(%s)", param2) ); methodsWithPrimitiveTypeParameters.put( param1, String.format("void myMethod(%s)", param1) ); for (Map.Entry<String, String> entry : methodsWithPrimitiveTypeParameters.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), ParamsSupplier.class); } } } @Test void shouldMatchVarArgParametersInMethodSignature() { Map<String, String> methodsWithVarArgParameters = ImmutableMap.<String, String>builder() .put("java.lang.Object...params0", "void myMethod(java.lang.Object...params0)") .put("java.lang.Object param1, java.lang.Object...params", "void myMethod(java.lang.Object param1, java.lang.Object...params)") .put("java.lang.Object param1, java.lang.Object param2, java.lang.String...params", "java.lang.Integer myMethod(java.lang.Object param1," + " java.lang.Object param2, java.lang.String...params)") .put("java.lang.Object param1, java.lang.Object param2, java.lang.Object...params", "void myMethod(java.lang.Object param1, java.lang.Object param2, " + "java.lang.Object...params)") .put("java.lang.Object param0, java.lang.Object...params", "void myMethod(java.lang.Object param0, java.lang.Object...params)") .put("java.lang.Object...params1", "void myMethod(java.lang.Object...params1)") .put("java.lang.Object...params2", "java.util.ArrayList<java.lang.Class<?>> myMethod(java.lang.Object...params2)").build(); for (Map.Entry<String, String> entry : methodsWithVarArgParameters.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), ParamsSupplier.class); } } @Test void shouldMatchCommentInMethodSignature() { Map<String, String> methodsWithComment = ImmutableMap.<String, String>builder() .put("// comment", "void myMethod() // comment") .put("onewordcomment", "void myMethod() onewordcomment") .put("multi word comment", "void myMethod()multi word comment") .put("samplecomment", "void myMethod(int param) samplecomment") .put("sample comment", "void myMethod(int param)sample comment") .put("!@# $%^&*_ {()comment", "void myMethod()!@# $%^&*_ {()comment").build(); for (Map.Entry<String, String> entry : methodsWithComment.entrySet()) { assertMatchInSignature(entry.getValue(), entry.getKey(), CommentSupplier.class); } } @Test void shouldIncludeAnnotationInMethodSignatureComment() throws SignatureParsingException { Map<String, String> annotatedMethods = ImmutableMap.<String, String>builder() .put("%s @Deprecated", "@Deprecated\nvoid myMethod()") .put("comment\n%s @Deprecated", "@Deprecated\rvoid myMethod() comment") .put("%s @Immutable", "@Immutable\r\njava.lang.Object myMethod()") .put("\\\\ comment\n%s @Immutable", "@Immutable int myMethod()\\\\ comment") .put("\\\\ some comment\n%s @TestOnly", "@TestOnly void myMethod() \\\\ some comment").build(); for (Map.Entry<String, String> entry : annotatedMethods.entrySet()) { String expected = String.format(entry.getKey(), "This method is annotated as"); String actual = new MethodDetail.Signature(entry.getValue()).comment; Assertions.assertEquals(actual, expected); } } @Test void shouldParseValidModifierKeyFromMethodDetail() { List<JavaMethod> entries = detail.getEntries(); ModifierKey[][] expectedMethodModifierKeys = new ModifierKey[][]{ new ModifierKey[]{ ModifierKey.UNDECLARED, // begin }, new ModifierKey[]{ ModifierKey.STATIC // doesInstantly }, new ModifierKey[]{ ModifierKey.STATIC, // init ModifierKey.FINAL }, new ModifierKey[]{ ModifierKey.UNDECLARED // isFinished }, new ModifierKey[]{ ModifierKey.STATIC // update }, new ModifierKey[]{ ModifierKey.STATIC // getActivatedMods }, new ModifierKey[]{ ModifierKey.UNDECLARED // getColor }, new ModifierKey[]{ ModifierKey.UNDECLARED // doTask } }; Assertions.assertEquals(expectedMethodModifierKeys.length, entries.size()); for (int i = 0; i < entries.size(); i++) { ModifierKey[] keys = expectedMethodModifierKeys[i]; Assertions.assertTrue(entries.get(i).getModifier().matchesModifiers(keys)); } } @Test void shouldParseValidAccessModifierFromMethodDetail() { List<JavaMethod> entries = detail.getEntries(); AccessModifierKey[] expectedMethodAccessModifiers = new AccessModifierKey[]{ AccessModifierKey.PUBLIC, // begin AccessModifierKey.PROTECTED, // doesInstantly AccessModifierKey.PRIVATE, // init AccessModifierKey.DEFAULT, // isFinished AccessModifierKey.DEFAULT, // update AccessModifierKey.DEFAULT, // getActivatedMods AccessModifierKey.PUBLIC, // getColor AccessModifierKey.PUBLIC // doTask }; Assertions.assertEquals(expectedMethodAccessModifiers.length, entries.size()); for (int i = 0; i < entries.size(); i++) { JavaMethod entry = entries.get(i); Assertions.assertTrue(entry.getModifier().hasAccess(expectedMethodAccessModifiers[i])); } } @Test void shouldParseValidMethodReturnTypeFromMethodDetail() { List<JavaMethod> entries = detail.getEntries(); JavaClass[] expectedMethodReturnTypes = new JavaClass[]{ new JavaClass(int.class), // begin new JavaClass(boolean.class), // doesInstantly new JavaClass(String.class), // init new JavaClass(Object[].class), // isFinished new JavaClass(void.class), // update new JavaClass(ArrayList.class, // getActivatedMods new JavaClass(String.class)), new JavaClass(Color[].class), // getColor new JavaClass(void.class), // doTask }; Assertions.assertEquals(expectedMethodReturnTypes.length, entries.size()); for (int i = 0; i < entries.size(); i++) { JavaMethod entry = entries.get(i); Assertions.assertEquals(expectedMethodReturnTypes[i], entry.getReturnType()); } } @Test void shouldParseValidMethodNamesFromMethodDetail() { List<JavaMethod> entries = detail.getEntries(); String[] expectedMethodNames = new String[]{ "begin", "DoesInstantly", "init", "IsFinished", "update", "getActivatedMods", "getColor", "doTask" }; Assertions.assertEquals(expectedMethodNames.length, entries.size()); for (int i = 0; i < entries.size(); i++) { JavaMethod entry = entries.get(i); Assertions.assertEquals(expectedMethodNames[i], entry.getName()); } } @Test void shouldParseValidMethodParamsFromMethodDetail() { List<JavaMethod> entries = detail.getEntries(); JavaParameter[][] expectedMethodParams = new JavaParameter[][]{ new JavaParameter[]{ // begin new JavaParameter(Object.class, "param") }, new JavaParameter[]{ // doesInstantly new JavaParameter(int.class, "number") }, new JavaParameter[]{ // init new JavaParameter(String.class, "object"), new JavaParameter(String[].class, "params") }, new JavaParameter[]{}, // isFinished new JavaParameter[]{ // update new JavaParameter(new JavaClass(ArrayList.class, new JavaClass(String.class)), "params"), }, new JavaParameter[]{}, // getActivatedMods new JavaParameter[]{ // getColor new JavaParameter(IsoPlayer.class, "player") }, new JavaParameter[]{ // getColor new JavaParameter(new JavaClass(Map.class, ImmutableList.of( new JavaClass(Map.class, ImmutableList.of( new JavaClass(Class.class, 1), new JavaClass(Object.class) )), new JavaClass(Object.class))), "map" ), new JavaParameter(new JavaClass(Object.class), "obj") } }; Assertions.assertEquals(expectedMethodParams.length, entries.size()); for (int i = 0; i < entries.size(); i++) { JavaMethod entry = entries.get(i); Assertions.assertEquals(Arrays.asList(expectedMethodParams[i]), entry.getParams()); } } @Test void shouldParseValidMethodDetailCommentBlocks() { List<JavaMethod> entries = detail.getEntries(); String[] expectedComments = new String[]{ "This is a single-line block comment\nSpecified by:\nbegin in class BaseCommand", "This is a multi\nline block comment\nSpecified by:\nDoesInstantly in class BaseCommand", "Specified by:\ninit in class BaseCommand", "Specified by:\nIsFinished in class BaseCommand", "Specified by:\nupdate in class BaseCommand", "", "Specified by:\ngetColor in class BaseCommand", "This method is annotated as @Deprecated" }; Assertions.assertEquals(expectedComments.length, entries.size()); for (int i = 0; i < entries.size(); i++) { Assertions.assertEquals(expectedComments[i], entries.get(i).getComment()); } } @Test void shouldParseValidMethodReturnTypeComment() { List<JavaMethod> entries = detail.getEntries(); String[] expectedComments = new String[]{ "some number", "true or false", "some text", "array of objects", "", "array of objects", "array of colors", "" }; Assertions.assertEquals(expectedComments.length, entries.size()); for (int i = 0; i < entries.size(); i++) { Assertions.assertEquals(expectedComments[i], entries.get(i).getReturnType().getComment()); } } @Test void shouldParseValidMethodParameterComments() { List<JavaMethod> entries = detail.getEntries(); Map<String, List<Pair<String, String>>> expectedComments = new LinkedHashMap<>(); expectedComments.put("begin", ImmutableList.of(Pair.of("param", "single parameter"))); expectedComments.put("DoesInstantly", ImmutableList.of(Pair.of("number", "integer parameter"))); expectedComments.put("init", ImmutableList.of( Pair.of("object", "string object"), Pair.of("params", "array of string objects") )); expectedComments.put("IsFinished", Collections.emptyList()); expectedComments.put("update", ImmutableList.of(Pair.of("params", "list of string objects"))); expectedComments.put("getActivatedMods", Collections.emptyList()); expectedComments.put("getColor", ImmutableList.of(Pair.of("player", "player parameter"))); expectedComments.put("doTask", ImmutableList.of( Pair.of("map", "map parameter"), Pair.of("obj", "object parameter") )); Assertions.assertEquals(expectedComments.size(), entries.size()); Iterator<Map.Entry<String, List<Pair<String, String>>>> iter = expectedComments.entrySet().iterator(); for (JavaMethod javaMethod : entries) { Map.Entry<String, List<Pair<String, String>>> entry = iter.next(); List<Pair<String, String>> expectedParams = entry.getValue(); List<JavaParameter> methodParams = javaMethod.getParams(); Assertions.assertEquals(methodParams.size(), expectedParams.size()); for (int i1 = 0; i1 < methodParams.size(); i1++) { JavaParameter param = methodParams.get(i1); Pair<String, String> expectedParam = expectedParams.get(i1); Assertions.assertEquals(expectedParam.getKey(), param.getName()); Assertions.assertEquals(expectedParam.getValue(), param.getComment()); } } } @Test void shouldGetCorrectMethodDetailEntriesByName() { List<JavaMethod> expectedJavaMethodEntries = ImmutableList.of( JavaMethod.Builder.create("begin").withReturnType(int.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(Object.class, "param")) .build(), JavaMethod.Builder.create("DoesInstantly").withReturnType(boolean.class) .withModifier(new MemberModifier(AccessModifierKey.PROTECTED, ModifierKey.STATIC)) .withParams(new JavaParameter(int.class, "number")) .build(), JavaMethod.Builder.create("init").withReturnType(String.class) .withModifier(new MemberModifier( AccessModifierKey.PRIVATE, ModifierKey.STATIC, ModifierKey.FINAL) ).withParams( new JavaParameter(String.class, "object"), new JavaParameter(String[].class, "params") ).build(), JavaMethod.Builder.create("IsFinished").withReturnType(Object[].class).build(), JavaMethod.Builder.create("update").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .withParams(new JavaParameter( new JavaClass(ArrayList.class, new JavaClass(String.class)), "params") ).build(), JavaMethod.Builder.create("getActivatedMods") .withReturnType(new JavaClass(ArrayList.class, new JavaClass(String.class))) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .build(), JavaMethod.Builder.create("getColor").withReturnType(Color[].class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(new JavaClass(IsoPlayer.class), "player")) .build(), JavaMethod.Builder.create("doTask").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams( new JavaParameter(JavaClassUtils.getMap(JavaClassUtils.getMap( JavaClassUtils.CLASS, Object.class), Object.class), "map"), new JavaParameter(Object.class, "obj") ).build() ); Assertions.assertEquals(expectedJavaMethodEntries.size(), detail.getEntries().size()); for (JavaMethod field : expectedJavaMethodEntries) { Assertions.assertTrue(detail.getEntries(field.getName()).contains(field)); } } }
21,714
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
FieldDetailTestFixture.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/doc/detail/FieldDetailTestFixture.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.doc.detail; import io.cocolabs.pz.zdoc.doc.DocTest; class FieldDetailTestFixture extends DetailTestFixture<FieldDetail> { FieldDetailTestFixture() throws DetailParsingException { super(new FieldDetail(DocTest.DOCUMENT)); } abstract static class FieldSignatureSupplier extends SignatureSupplier<FieldDetail.Signature> { FieldSignatureSupplier(String signature) throws DetailParsingException { super(new FieldDetail.Signature(signature)); } } static class TypeSupplier extends FieldSignatureSupplier { TypeSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.type; } } static class NameSupplier extends FieldSignatureSupplier { NameSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.name; } } static class CommentSupplier extends FieldSignatureSupplier { CommentSupplier(String signature) throws DetailParsingException { super(signature); } @Override public String get() { return signature.comment; } } }
1,915
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CommandLineTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/cmd/CommandLineTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.nio.file.InvalidPathException; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.apache.commons.cli.ParseException; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class CommandLineTest { private static final Command[] COMMANDS = Arrays.stream(Command.values()) .filter(c -> c != Command.HELP && c != Command.VERSION) .collect(Collectors.toSet()).toArray(new Command[]{}); @TestOnly private static String[] formatAppArgs(String command, String input, String output) { List<String> args = new java.util.ArrayList<>(); args.add(command); if (!input.isEmpty()) { args.add("-i"); args.add(input); } if (!output.isEmpty()) { args.add("-o"); args.add(output); } return args.toArray(new String[]{}); } @TestOnly private static String[] formatAppArgs(Command command, String input, String output) { return formatAppArgs(command.getName(), input, output); } @Test void shouldProperlyParseCommandInputPath() throws ParseException { String path = Paths.get("input/path").toString(); for (Command command : COMMANDS) { String[] args = formatAppArgs(command, path, "output/path"); CommandLine cmdLIne = CommandLine.parse(command.options, args); Assertions.assertEquals(path, cmdLIne.getInputPath().toString()); } } @Test void shouldProperlyParseCommandOutputPath() throws ParseException { String path = Paths.get("output/path").toString(); for (Command command : COMMANDS) { String[] args = formatAppArgs(command, "input/path", path); CommandLine cmdLIne = CommandLine.parse(command.options, args); Object outputPath = Objects.requireNonNull(cmdLIne.getOutputPath()); Assertions.assertEquals(path, outputPath.toString()); } } @Test void shouldThrowExceptionWhenParsingMalformedCommandPath() { String path = '\u0000' + "/p*!h"; for (Command command : COMMANDS) { final String[] args1 = formatAppArgs(command, path, "output/path"); Assertions.assertThrows(InvalidPathException.class, () -> CommandLine.parse(command.options, args1).getInputPath()); final String[] args2 = formatAppArgs(command, "input/path", path); Assertions.assertThrows(InvalidPathException.class, () -> CommandLine.parse(command.options, args2).getOutputPath()); } } }
3,228
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
CommandTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/cmd/CommandTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.cmd; import java.util.Arrays; import java.util.stream.Collectors; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.ArrayUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class CommandTest { private static final Command[] COMMANDS = Arrays.stream(Command.values()) .filter(c -> c != Command.HELP && c != Command.VERSION) .collect(Collectors.toSet()).toArray(new Command[]{}); @Test void shouldReturnAllMatchingCommands() { Arrays.stream(Command.values()).forEach(c -> Assertions.assertNotNull(Command.parse(new String[]{ c.name })) ); Assertions.assertNull(Command.parse(new String[]{ "t" })); Assertions.assertNull(Command.parse(new String[]{ "t", "lua" })); Assertions.assertNull(Command.parse(new String[]{ "t", "java" })); } @Test void shouldRecognizeAllCommands() { Arrays.stream(Command.values()).forEach(c -> Assertions.assertNotNull(Command.get(c.name)) ); Assertions.assertNull(Command.get("")); Assertions.assertNull(Command.get("invalid")); } @Test void shouldDetectAllCommandLineOptions() throws ParseException { String[][] argArrays = new String[][]{ new String[]{ "-i", "input/path", "-o", "output/path" }, new String[]{ "-o", "output/path", "-i", "input/path", } }; for (Command command : COMMANDS) { for (String[] args : argArrays) { CommandLine cmd = CommandLine.parse(command.options, ArrayUtils.addFirst(args, command.name)); command.options.getOptions().forEach(opt -> Assertions.assertTrue( !opt.isRequired() || cmd.hasOption(opt.getOpt())) ); } } } @Test void shouldThrowExceptionWhenMissingCommandArguments() { String[][] missingArgs = new String[][]{ new String[]{ "-i", "input/path" }, // missing output path new String[]{ "-o", "output/path" } // missing input path }; for (String[] args : missingArgs) { Arrays.stream(COMMANDS).forEach(c -> Assertions.assertThrows(ParseException.class, () -> CommandLine.parse(c.options, ArrayUtils.addFirst(args, c.name)))); } String[][] correctArgs = new String[][]{ new String[]{ "-i", "input/path", "-o", "output/path" }, new String[]{ "-o", "output/path", "-i", "input/path", } }; for (String[] args : correctArgs) { Arrays.stream(COMMANDS).forEach(c -> Assertions.assertDoesNotThrow(() -> CommandLine.parse(c.options, ArrayUtils.addFirst(args, c.name)))); } } }
3,234
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaAnnotatorTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/LuaAnnotatorTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.util.*; import java.util.regex.Matcher; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import io.cocolabs.pz.zdoc.Main; import io.cocolabs.pz.zdoc.TestWorkspace; class LuaAnnotatorTest extends TestWorkspace { private static final ClassLoader CL = LuaAnnotatorTest.class.getClassLoader(); private static final File INCLUSION_TEST, NO_MATCH_TEST, EXPECTED_INCLUSION; static { try { INCLUSION_TEST = new File( Objects.requireNonNull(CL.getResource("LuaInclusionTest.lua")).toURI() ); NO_MATCH_TEST = new File( Objects.requireNonNull(CL.getResource("LuaNoMatchTest.lua")).toURI() ); EXPECTED_INCLUSION = new File( Objects.requireNonNull(CL.getResource("LuaExpectedInclusion.lua")).toURI() ); } catch (URISyntaxException e) { throw new RuntimeException(e); } } @Test void shouldMatchLuaTableDeclarationIndentationWithRegex() { Map<String, String> luaTableDeclarations = ImmutableMap.of( " ", " NewTestTable1 = ISTestTable:new(\"TestTable\")", " ", " NewTestTable1 = ISTestTable:new(\"TestTable\")" ); for (Map.Entry<String, String> entry : luaTableDeclarations.entrySet()) { Matcher matcher = LuaAnnotator.LUA_TABLE_DECLARATION.matcher(entry.getValue()); Assertions.assertTrue(matcher.find()); Assertions.assertEquals(entry.getKey(), matcher.group(1)); } String declarationWithNoIndentation = "NewTestTable1 = ISTestTable:new(\"TestTable\")"; Matcher matcher = LuaAnnotator.LUA_TABLE_DECLARATION.matcher(declarationWithNoIndentation); Assertions.assertTrue(matcher.find()); Assertions.assertNull(matcher.group(1)); } @Test void shouldMatchLuaTableDeclarationWithRegex() { Map<String, String> luaTableDeclarations = ImmutableMap.<String, String>builder() .put("NewTestTable0", "NewTestTable0 = ISTestTable:new()") .put("NewTestTable1", "NewTestTable1 = ISTestTable:new(\"TestTable\")") .put("NewTestTable2", "NewTestTable2=ISTestTable:new(\"TestTable\")") .put("DerivedTestTable0", "DerivedTestTable0 = ISTestTable:derive()") .put("DerivedTestTable1", "DerivedTestTable1 = ISTestTable:derive(\"TestTable\")") .put("DerivedTestTable2", "DerivedTestTable2=ISTestTable:derive(\"TestTable\")") .put("DeclaredTestTable0", "DeclaredTestTable0 = ISTestTable or {}") .put("DeclaredTestTable1", "DeclaredTestTable1 = {}") .put("DeclaredTestTable2", "DeclaredTestTable2={ }").build(); for (Map.Entry<String, String> entry : luaTableDeclarations.entrySet()) { Matcher matcher = LuaAnnotator.LUA_TABLE_DECLARATION.matcher(entry.getValue()); Assertions.assertTrue(matcher.find()); Assertions.assertEquals(entry.getKey(), matcher.group(2)); } } @Test void shouldMatchLuaNewOrDerivedClassDeclarationWithRegex() { Map<String, String> luaTableDeclarations = ImmutableMap.of( "new", "NewTestTable = ISTestTable:new(\"TestTable\")", "derive", "DerivedTestTable = ISTestTable:derive(\"TestTable\")" ); for (Map.Entry<String, String> entry : luaTableDeclarations.entrySet()) { Matcher matcher = LuaAnnotator.LUA_TABLE_DECLARATION.matcher(entry.getValue()); Assertions.assertTrue(matcher.find()); Assertions.assertEquals("ISTestTable", matcher.group(3)); Assertions.assertEquals(entry.getKey(), matcher.group(4)); } Map<String, String> badLuaTableDeclarations = ImmutableMap.of( "new", "NewTestTable = ISTestTable:newly(\"TestTable\")", "derive", "DerivedTestTable = ISTestTable:derived(\"TestTable\")" ); for (Map.Entry<String, String> entry : badLuaTableDeclarations.entrySet()) { Matcher matcher = LuaAnnotator.LUA_TABLE_DECLARATION.matcher(entry.getValue()); Assertions.assertTrue(matcher.find()); Assertions.assertNull(matcher.group(4)); } } @Test void shouldThrowExceptionWhenTryingToAnnotateNonExistingFile() { Assertions.assertThrows(FileNotFoundException.class, () -> LuaAnnotator.annotate(new File("nonExistingFile"), new ArrayList<>()) ); } @Test void shouldThrowExceptionWhenTryingToAnnotateWithImmutableExcludeRules() { LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(ImmutableSet.of()); Assertions.assertThrows(UnsupportedOperationException.class, () -> LuaAnnotator.annotate(INCLUSION_TEST, new ArrayList<>(), rules) ); } @Test void shouldSkipAnnotatingWhenTyringToAnnotateEmptyFile() throws IOException { List<String> content = new ArrayList<>(); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(file, content); Assertions.assertEquals(LuaAnnotator.AnnotateResult.SKIPPED_FILE_EMPTY, result); Assertions.assertTrue(content.isEmpty()); } @Test void shouldSkipAnnotatingElementsWhenMatchedExcludeRules() throws IOException { List<String> content = new ArrayList<>(); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(ImmutableSet.of("LuaInclusionTest")); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(INCLUSION_TEST, content, rules); Assertions.assertEquals(LuaAnnotator.AnnotateResult.ALL_EXCLUDED, result); Assertions.assertEquals(content, FileUtils.readLines(INCLUSION_TEST, Main.CHARSET)); } @Test void shouldSkipAnnotatingElementsWhenFileIgnoredByRules() throws IOException { List<String> content = new ArrayList<>(); Properties properties = new Properties(); properties.put("LuaInclusionTest", ""); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(properties); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(INCLUSION_TEST, content, rules); Assertions.assertEquals(LuaAnnotator.AnnotateResult.SKIPPED_FILE_IGNORED, result); Assertions.assertTrue(content.isEmpty()); } @Test void shouldAnnotateAllElementsWhenMatchedIncludeRules() throws IOException { List<String> content = new ArrayList<>(); Properties properties = new Properties(); properties.put("LuaInclusionTest", "LuaInclusionTest,DerivedTest"); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(properties); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(INCLUSION_TEST, content, rules); Assertions.assertEquals(LuaAnnotator.AnnotateResult.ALL_INCLUDED, result); List<String> expected = FileUtils.readLines(EXPECTED_INCLUSION, Main.CHARSET); Assertions.assertEquals(content, expected); } @Test void shouldAnnotateSomeElementsWhenPartialMatchedRules() throws IOException { List<String> content = new ArrayList<>(); Properties properties = new Properties(); properties.put("LuaInclusionTest", "LuaInclusionTest,DerivedTest"); Set<String> exclude = new HashSet<>(); exclude.add("DerivedTest"); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(properties, exclude); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(INCLUSION_TEST, content, rules); Assertions.assertEquals(LuaAnnotator.AnnotateResult.PARTIAL_INCLUSION, result); } @Test void shouldAnnotateFileWithUndeclaredLuaClass() throws IOException { List<String> content = new ArrayList<>(); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(NO_MATCH_TEST, content, rules); Assertions.assertEquals(LuaAnnotator.AnnotateResult.NO_MATCH, result); } }
8,319
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
LuaCompilerTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/LuaCompilerTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.util.*; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.*; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.doc.ZomboidJavaDoc; import io.cocolabs.pz.zdoc.doc.ZomboidLuaDoc; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.java.JavaParameter; import io.cocolabs.pz.zdoc.element.lua.*; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; @SuppressWarnings("JavaLangClash") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class LuaCompilerTest { private static final LuaClass OWNER_CLASS = new LuaClass( LuaCompilerTest.class.getSimpleName(), LuaCompilerTest.class.getName() ); private static final MemberModifier MODIFIER = new MemberModifier( AccessModifierKey.PUBLIC, ModifierKey.FINAL ); private static final JavaClass JAVA_ARRAY_LIST_OBJECT = new JavaClass( ArrayList.class, ImmutableList.of(new JavaClass(java.lang.Object.class)) ); private static final JavaClass JAVA_ARRAY_LIST_STRING_OBJECT = new JavaClass( ArrayList.class, ImmutableList.of(new JavaClass(java.lang.String.class), new JavaClass(java.lang.Object.class)) ); private static final JavaClass JAVA_ARRAY_LIST_OBJECT_STRING = new JavaClass( ArrayList.class, ImmutableList.of(new JavaClass(Object.class), new JavaClass(String.class)) ); private static final LuaType LUA_ARRAY_LIST_OBJECT = new LuaType( "ArrayList", ImmutableList.of(new LuaType("Object")) ); private static final LuaType LUA_ARRAY_LIST_STRING_OBJECT = new LuaType( "ArrayList", ImmutableList.of(new LuaType("String"), new LuaType("Object")) ); private static final LuaType LUA_ARRAY_LIST_OBJECT_STRING = new LuaType( "ArrayList", ImmutableList.of( new LuaType("LuaCompilerTest.Object"), new LuaType("LuaCompilerTest.String")) ); private static final LuaType LUA_ARRAY_LIST_UNKNOWN = new LuaType( "ArrayList", ImmutableList.of(new LuaType("Unknown")) ); private static final JavaClass JAVA_ARRAY_LIST_NULL; static { List<JavaClass> noTypeParams = new ArrayList<>(); noTypeParams.add(null); JAVA_ARRAY_LIST_NULL = new JavaClass(ArrayList.class, noTypeParams); } @TestOnly private static Set<ZomboidLuaDoc> compileLua(Set<ZomboidJavaDoc> zJavaDocs) throws CompilerException { return new LuaCompiler(zJavaDocs).compile(); } @TestOnly private static Set<ZomboidLuaDoc> compileLua(ZomboidJavaDoc zDoc) throws CompilerException { return compileLua(Collections.singleton(zDoc)); } @Test @Order(1) void shouldCorrectlyFormatInnerClassNamesWhenCompilingLua() throws CompilerException { final Class<?>[] classObjects = { Object.class, String.class, Integer.class }; Set<ZomboidJavaDoc> zJavaDocs = new LinkedHashSet<>(); for (Class<?> c : classObjects) { zJavaDocs.add(new ZomboidJavaDoc(new JavaClass(c), new ArrayList<>(), new HashSet<>())); } Map<java.lang.String, java.lang.String> classData = ImmutableMap.of( "LuaCompilerTest.Object", "io.cocolabs.pz.zdoc.compile.LuaCompilerTest.Object", "LuaCompilerTest.String", "io.cocolabs.pz.zdoc.compile.LuaCompilerTest.String", "LuaCompilerTest.Integer", "io.cocolabs.pz.zdoc.compile.LuaCompilerTest.Integer" ); Set<LuaClass> expectedLuaClasses = new LinkedHashSet<>(); classData.forEach((k, v) -> expectedLuaClasses.add(new LuaClass(k, v))); Set<LuaClass> actualLuaClasses = new HashSet<>(); compileLua(zJavaDocs).forEach(doc -> actualLuaClasses.add(doc.getClazz())); Assertions.assertEquals(expectedLuaClasses, actualLuaClasses); } @Test @Order(2) void shouldCompileLuaDocsWithValidClassFromZomboidJavaDocs() throws CompilerException { LuaClass expectedClass = new LuaClass( LuaCompilerTest.class.getSimpleName(), LuaCompilerTest.class.getName() ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), new ArrayList<>(), new HashSet<>() ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); Assertions.assertEquals(expectedClass, zLuaDocs.iterator().next().getClazz()); } @Test @Order(3) void shouldCompileValidLuaFieldsFromZomboidJavaDocs() throws CompilerException { List<JavaField> javaFields = ImmutableList.of( new JavaField(java.lang.Object.class, "object", MODIFIER), new JavaField(java.lang.String.class, "text", MODIFIER), new JavaField(java.lang.Integer.class, "num", MODIFIER) ); List<LuaField> expectedFields = ImmutableList.of( new LuaField(new LuaType("Object"), "object", MODIFIER), new LuaField(new LuaType("String"), "text", MODIFIER), new LuaField(new LuaType("Integer"), "num", MODIFIER) ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), javaFields, new HashSet<>() ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); Assertions.assertEquals(expectedFields, zLuaDoc.getFields()); } @Test @Order(4) void shouldCompileValidLuaArrayFieldsFromZomboidJavaDocs() throws CompilerException { List<JavaField> javaFields = ImmutableList.of( new JavaField(java.lang.Object[].class, "objectArray1", MODIFIER), new JavaField(java.lang.String[].class, "textArray1", MODIFIER), new JavaField(java.lang.Integer[].class, "numArray1", MODIFIER), new JavaField(java.lang.Object[][].class, "objectArray2", MODIFIER), new JavaField(java.lang.String[][][].class, "textArray2", MODIFIER), new JavaField(java.lang.Integer[][][][].class, "numArray2", MODIFIER), new JavaField(int[].class, "intArray1", MODIFIER), new JavaField(boolean[].class, "booleanArray1", MODIFIER), new JavaField(char[].class, "charArray1", MODIFIER), new JavaField(int[][].class, "intArray2", MODIFIER), new JavaField(boolean[][][].class, "booleanArray2", MODIFIER), new JavaField(char[][][][].class, "charArray2", MODIFIER) ); List<LuaField> expectedFields = ImmutableList.of( new LuaField(new LuaType("Object[]"), "objectArray1", MODIFIER), new LuaField(new LuaType("String[]"), "textArray1", MODIFIER), new LuaField(new LuaType("Integer[]"), "numArray1", MODIFIER), new LuaField(new LuaType("Object[][]"), "objectArray2", MODIFIER), new LuaField(new LuaType("String[][][]"), "textArray2", MODIFIER), new LuaField(new LuaType("Integer[][][][]"), "numArray2", MODIFIER), new LuaField(new LuaType("int[]"), "intArray1", MODIFIER), new LuaField(new LuaType("boolean[]"), "booleanArray1", MODIFIER), new LuaField(new LuaType("char[]"), "charArray1", MODIFIER), new LuaField(new LuaType("int[][]"), "intArray2", MODIFIER), new LuaField(new LuaType("boolean[][][]"), "booleanArray2", MODIFIER), new LuaField(new LuaType("char[][][][]"), "charArray2", MODIFIER) ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), javaFields, new HashSet<>() ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); Assertions.assertEquals(expectedFields, zLuaDoc.getFields()); } @Test @Order(5) void shouldCompileValidLuaParameterizedTypeFieldsFromZomboidJavaDocs() throws CompilerException { List<JavaField> javaFields = ImmutableList.of( new JavaField(JAVA_ARRAY_LIST_OBJECT, "object", MODIFIER), new JavaField(JAVA_ARRAY_LIST_STRING_OBJECT, "text", MODIFIER), new JavaField(JAVA_ARRAY_LIST_OBJECT_STRING, "text", MODIFIER), new JavaField(JAVA_ARRAY_LIST_NULL, "num", MODIFIER) ); List<LuaField> expectedFields = ImmutableList.of( new LuaField(LUA_ARRAY_LIST_OBJECT, "object", MODIFIER), new LuaField(LUA_ARRAY_LIST_STRING_OBJECT, "text", MODIFIER), new LuaField(LUA_ARRAY_LIST_OBJECT_STRING, "text", MODIFIER), new LuaField(LUA_ARRAY_LIST_UNKNOWN, "num", MODIFIER) ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), javaFields, new HashSet<>() ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); List<LuaField> actualFields = zLuaDocs.iterator().next().getFields(); Assertions.assertEquals(expectedFields, actualFields); } @Test @Order(6) void shouldCompileValidLuaMethodsFromZomboidJavaDocs() throws CompilerException { Set<JavaMethod> javaMethods = ImmutableSet.of( JavaMethod.Builder.create("getText") .withReturnType(java.lang.String.class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.Integer.class, "iParam")) .build(), JavaMethod.Builder.create("getNumber") .withReturnType(java.lang.Integer.class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.Object.class, "oParam")) .build(), JavaMethod.Builder.create("getObject") .withReturnType(java.lang.Object.class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.String.class, "sParam")) .build() ); Set<LuaMethod> expectedMethods = ImmutableSet.of( LuaMethod.Builder.create("getText").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("String")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Integer"), "iParam"))).build(), LuaMethod.Builder.create("getNumber").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("Integer")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Object"), "oParam"))).build(), LuaMethod.Builder.create("getObject").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("Object")).withParams( ImmutableList.of(new LuaParameter(new LuaType("String"), "sParam"))).build() ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), new ArrayList<>(), javaMethods ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); Assertions.assertEquals(expectedMethods, zLuaDoc.getMethods()); } @Test @Order(7) void shouldCompileValidLuaMethodsWithArraysFromZomboidJavaDocs() throws CompilerException { Set<JavaMethod> javaMethods = ImmutableSet.of( JavaMethod.Builder.create("getFloat") .withReturnType(java.lang.Float[].class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.Integer[].class, "iParam")) .build(), JavaMethod.Builder.create("getDouble") .withReturnType(java.lang.Double[].class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.Object[].class, "oParam")) .build(), JavaMethod.Builder.create("getByte") .withReturnType(java.lang.Byte[].class).withModifier(MODIFIER) .withParams(new JavaParameter(java.lang.String[].class, "sParam")) .build() ); Set<LuaMethod> expectedMethods = ImmutableSet.of( LuaMethod.Builder.create("getFloat").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("Float[]")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Integer[]"), "iParam"))).build(), LuaMethod.Builder.create("getDouble").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("Double[]")).withParams( ImmutableList.of(new LuaParameter(new LuaType("Object[]"), "oParam"))).build(), LuaMethod.Builder.create("getByte").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(new LuaType("Byte[]")).withParams( ImmutableList.of(new LuaParameter(new LuaType("String[]"), "sParam"))).build() ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), new ArrayList<>(), javaMethods ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); Assertions.assertEquals(expectedMethods, zLuaDoc.getMethods()); } @Test @Order(8) void shouldNotRegisterArrayGlobalTypesWhenCompilingLuaMethodsFromZomboidJavaDocs() { for (LuaClass globalType : LuaCompiler.getGlobalTypes()) { Assertions.assertFalse(globalType.getName().contains("[]")); } } @Test @Order(9) void shouldCompileValidLuaMethodsWithParameterizedTypesFromZomboidJavaDocs() throws CompilerException { Set<JavaMethod> javaMethods = ImmutableSet.of( JavaMethod.Builder.create("getText") .withReturnType(JAVA_ARRAY_LIST_OBJECT).withModifier(MODIFIER) .withParams(new JavaParameter(JAVA_ARRAY_LIST_STRING_OBJECT, "sParam")) .build(), JavaMethod.Builder.create("getNumber") .withReturnType(JAVA_ARRAY_LIST_STRING_OBJECT).withModifier(MODIFIER) .withParams(new JavaParameter(JAVA_ARRAY_LIST_OBJECT_STRING, "nParam")) .build(), JavaMethod.Builder.create("getObject") .withReturnType(JAVA_ARRAY_LIST_OBJECT_STRING).withModifier(MODIFIER) .withParams(new JavaParameter(JAVA_ARRAY_LIST_NULL, "oParam")) .build() ); Set<LuaMethod> expectedMethods = ImmutableSet.of( LuaMethod.Builder.create("getText").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(LUA_ARRAY_LIST_OBJECT).withParams( ImmutableList.of(new LuaParameter(LUA_ARRAY_LIST_STRING_OBJECT, "sParam"))).build(), LuaMethod.Builder.create("getNumber").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(LUA_ARRAY_LIST_STRING_OBJECT).withParams( ImmutableList.of(new LuaParameter(LUA_ARRAY_LIST_OBJECT_STRING, "nParam"))).build(), LuaMethod.Builder.create("getObject").withOwner(OWNER_CLASS) .withModifier(MODIFIER).withReturnType(LUA_ARRAY_LIST_OBJECT_STRING).withParams( ImmutableList.of(new LuaParameter(LUA_ARRAY_LIST_UNKNOWN, "oParam"))).build() ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), new ArrayList<>(), javaMethods ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); Assertions.assertEquals(expectedMethods, zLuaDoc.getMethods()); } @Test @Order(10) void shouldIncludeCommentsWhenCompilingLua() throws CompilerException { List<JavaField> fieldsWithComment = ImmutableList.of( new JavaField(new JavaClass(java.lang.Object.class), "object", MODIFIER, "this field has a comment") ); Set<JavaMethod> methodsWithComment = ImmutableSet.of( JavaMethod.Builder.create("getText") .withReturnType(java.lang.String.class).withModifier(MODIFIER) .withParams(new JavaParameter(JAVA_ARRAY_LIST_NULL, "oParam")) .withComment("this method has a comment").build() ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), fieldsWithComment, methodsWithComment ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); ZomboidLuaDoc zLuaDoc = zLuaDocs.iterator().next(); java.lang.String actual = zLuaDoc.getFields().iterator().next().getComment(); Assertions.assertEquals("this field has a comment", actual); actual = zLuaDoc.getMethods().iterator().next().getComment(); Assertions.assertEquals("this method has a comment", actual); } @Test @Order(11) void shouldGatherAllGlobalTypesWhenCompilingLua() { Set<LuaClass> expectedGlobalTypes = Sets.newHashSet( new LuaClass("Object", "java.lang.Object"), new LuaClass("String", "java.lang.String"), new LuaClass("Integer", "java.lang.Integer"), new LuaClass("Double", "java.lang.Double"), new LuaClass("Float", "java.lang.Float"), new LuaClass("Byte", "java.lang.Byte"), new LuaClass("int"), new LuaClass("boolean"), new LuaClass("char"), new LuaClass("ArrayList", "java.util.ArrayList"), new LuaClass("Unknown") ); Set<LuaClass> actualGlobalTypes = LuaCompiler.getGlobalTypes(); Assertions.assertEquals(expectedGlobalTypes, actualGlobalTypes); } @Test @Order(12) void shouldAvoidDuplicateClassNamesWhenCompilingLua() throws CompilerException { final Class<?>[] classObjects = { java.lang.Object.class, java.lang.String.class, java.lang.Integer.class, io.cocolabs.pz.zdoc.compile.test.Object.class, io.cocolabs.pz.zdoc.compile.test.String.class, io.cocolabs.pz.zdoc.compile.test.Integer.class }; Set<ZomboidJavaDoc> zJavaDocs = new LinkedHashSet<>(); for (Class<?> c : classObjects) { zJavaDocs.add(new ZomboidJavaDoc(new JavaClass(c), new ArrayList<>(), new HashSet<>())); } Map<java.lang.String, java.lang.String> classData = ImmutableMap.<java.lang.String, java.lang.String>builder() .put("Object", "java.lang.Object") .put("String", "java.lang.String") .put("Integer", "java.lang.Integer") .put("test_Object", "io.cocolabs.pz.zdoc.compile.test.Object") .put("test_String", "io.cocolabs.pz.zdoc.compile.test.String") .put("test_Integer", "io.cocolabs.pz.zdoc.compile.test.Integer").build(); Set<LuaClass> expectedLuaClasses = new LinkedHashSet<>(); classData.forEach((k, v) -> expectedLuaClasses.add(new LuaClass(k, v))); Set<LuaClass> actualLuaClasses = new HashSet<>(); compileLua(zJavaDocs).forEach(doc -> actualLuaClasses.add(doc.getClazz())); Assertions.assertEquals(expectedLuaClasses, actualLuaClasses); } @Test @Order(13) void shouldAvoidDuplicateTypeNamesWhenCompilingLua() throws CompilerException { MemberModifier modifier = MemberModifier.UNDECLARED; List<JavaField> javaFields = ImmutableList.of( new JavaField(new JavaClass(java.lang.Object.class), "object1", modifier ), new JavaField(new JavaClass(java.lang.String.class), "string1", modifier ), new JavaField(new JavaClass(java.lang.Integer.class), "integer1", modifier ), new JavaField(new JavaClass(io.cocolabs.pz.zdoc.compile.test.Object.class), "object2", modifier ), new JavaField(new JavaClass(io.cocolabs.pz.zdoc.compile.test.String.class), "string2", modifier ), new JavaField(new JavaClass(io.cocolabs.pz.zdoc.compile.test.Integer.class), "integer2", modifier) ); List<LuaField> luaFields = ImmutableList.of( new LuaField(new LuaType("Object"), "object1", modifier ), new LuaField(new LuaType("String"), "string1", modifier ), new LuaField(new LuaType("Integer"), "integer1", modifier ), new LuaField(new LuaType("test_Object"), "object2", modifier ), new LuaField(new LuaType("test_String"), "string2", modifier ), new LuaField(new LuaType("test_Integer"), "integer2", modifier) ); ZomboidJavaDoc zJavaDoc = new ZomboidJavaDoc( new JavaClass(LuaCompilerTest.class), javaFields, new HashSet<>() ); Set<ZomboidLuaDoc> zLuaDocs = compileLua(zJavaDoc); Assertions.assertEquals(1, zLuaDocs.size()); Assertions.assertEquals(luaFields, zLuaDocs.iterator().next().getFields()); } @Test @Order(14) void shouldFilterGlobalClassTypesFromGlobalTypesWhenCompilingLua() { Set<LuaClass> expectedGlobalTypes = Sets.newHashSet( new LuaClass("int"), new LuaClass("boolean"), new LuaClass("char"), new LuaClass("Double", "java.lang.Double"), new LuaClass("Float", "java.lang.Float"), new LuaClass("Byte", "java.lang.Byte"), new LuaClass("ArrayList", "java.util.ArrayList"), new LuaClass("Unknown") ); Set<LuaClass> actualGlobalTypes = LuaCompiler.getGlobalTypes(); Assertions.assertEquals(expectedGlobalTypes, actualGlobalTypes); } @TestOnly private static class Object { } @TestOnly private static class String { } @TestOnly private static class Integer { } }
20,810
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaCompilerTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/JavaCompilerTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import com.google.common.collect.Sets; import io.cocolabs.pz.zdoc.JavaClassUtils; import io.cocolabs.pz.zdoc.doc.DocTest; import io.cocolabs.pz.zdoc.doc.detail.DetailParsingException; import io.cocolabs.pz.zdoc.element.java.JavaClass; import io.cocolabs.pz.zdoc.element.java.JavaField; import io.cocolabs.pz.zdoc.element.java.JavaMethod; import io.cocolabs.pz.zdoc.element.java.JavaParameter; import io.cocolabs.pz.zdoc.element.mod.AccessModifierKey; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.element.mod.ModifierKey; import zombie.characters.IsoPlayer; import zombie.core.Color; @Tag("compile") class JavaCompilerTest extends DocTest { @Test void shouldCompileDeclaredJavaFieldsFromClassWithNullDocument() throws DetailParsingException { List<JavaField> expectedJavaFields = Arrays.asList( new JavaField(float.class, "a", new MemberModifier( AccessModifierKey.PUBLIC )), new JavaField(Integer.class, "b", new MemberModifier( AccessModifierKey.PRIVATE, ModifierKey.FINAL )), new JavaField(Color.class, "black", new MemberModifier( AccessModifierKey.PROTECTED, ModifierKey.STATIC, ModifierKey.FINAL )), new JavaField(Color[].class, "blue", new MemberModifier( AccessModifierKey.DEFAULT, ModifierKey.STATIC )), new JavaField(new JavaClass(ArrayList.class, 1), "cyan", new MemberModifier(AccessModifierKey.PUBLIC)) ); List<JavaField> compiledFields = JavaCompiler.compileJavaFields(CompileTest.class, null); Assertions.assertEquals(expectedJavaFields, compiledFields); } @Test void shouldCompileDeclaredJavaFieldsFromClassWithDocument() throws DetailParsingException { List<JavaField> expectedJavaFields = Arrays.asList( new JavaField(float.class, "a", new MemberModifier( AccessModifierKey.PUBLIC )), new JavaField(Integer.class, "b", new MemberModifier( AccessModifierKey.PRIVATE, ModifierKey.FINAL )), new JavaField(Color.class, "black", new MemberModifier( AccessModifierKey.PROTECTED, ModifierKey.STATIC, ModifierKey.FINAL )), new JavaField(Color[].class, "blue", new MemberModifier( AccessModifierKey.DEFAULT, ModifierKey.STATIC )), new JavaField(new JavaClass(ArrayList.class, new JavaClass(Color.class)), "cyan", new MemberModifier(AccessModifierKey.PUBLIC)) ); List<JavaField> compiledFields = JavaCompiler.compileJavaFields(CompileTest.class, DOCUMENT); Assertions.assertEquals(expectedJavaFields, compiledFields); } @Test void shouldCompileDeclaredJavaMethodsFromClassWithNullDocument() throws DetailParsingException { Set<JavaMethod> expectedJavaMethods = Sets.newHashSet( JavaMethod.Builder.create("begin").withReturnType(int.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(Object.class, "arg0")) .build(), JavaMethod.Builder.create("DoesInstantly").withReturnType(boolean.class) .withModifier(new MemberModifier(AccessModifierKey.PROTECTED, ModifierKey.STATIC)) .withParams(new JavaParameter(int.class, "arg0")) .build(), JavaMethod.Builder.create("init").withReturnType(String.class) .withModifier(new MemberModifier(AccessModifierKey.PRIVATE, ModifierKey.STATIC, ModifierKey.FINAL)) .withParams( new JavaParameter(String.class, "arg0"), new JavaParameter(String[].class, "arg1") ).build(), JavaMethod.Builder.create("IsFinished").withReturnType(Object[].class).build(), JavaMethod.Builder.create("update").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .withParams(new JavaParameter(new JavaClass(ArrayList.class, 1), "arg0")) .build(), JavaMethod.Builder.create("getActivatedMods") .withReturnType(new JavaClass(ArrayList.class, 1)) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .build(), JavaMethod.Builder.create("getColor").withReturnType(Color[].class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(IsoPlayer.class, "arg0")) .build(), JavaMethod.Builder.create("doTask").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams( new JavaParameter(new JavaClass(Map.class, 2), "arg0"), new JavaParameter(Object.class, "arg1") ).build() ); Set<JavaMethod> compiledMethods = JavaCompiler.compileJavaMethods(CompileTest.class, null); Assertions.assertEquals(expectedJavaMethods, compiledMethods); } @Test void shouldCompileDeclaredJavaMethodsFromClassWithDocument() throws DetailParsingException { Set<JavaMethod> expectedJavaMethods = Sets.newHashSet( JavaMethod.Builder.create("begin").withReturnType(int.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(Object.class, "param")) .build(), JavaMethod.Builder.create("DoesInstantly").withReturnType(boolean.class) .withModifier(new MemberModifier(AccessModifierKey.PROTECTED, ModifierKey.STATIC)) .withParams(new JavaParameter(int.class, "number")) .build(), JavaMethod.Builder.create("init").withReturnType(String.class) .withModifier(new MemberModifier(AccessModifierKey.PRIVATE, ModifierKey.STATIC, ModifierKey.FINAL)) .withParams( new JavaParameter(String.class, "object"), new JavaParameter(String[].class, "params") ).build(), JavaMethod.Builder.create("IsFinished").withReturnType(Object[].class).build(), JavaMethod.Builder.create("update").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .withParams(new JavaParameter( new JavaClass(ArrayList.class, new JavaClass(String.class)), "params") ).build(), JavaMethod.Builder.create("getActivatedMods") .withReturnType(new JavaClass(ArrayList.class, new JavaClass(String.class))) .withModifier(new MemberModifier(AccessModifierKey.DEFAULT, ModifierKey.STATIC)) .build(), JavaMethod.Builder.create("getColor").withReturnType(Color[].class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams(new JavaParameter(IsoPlayer.class, "player")) .build(), JavaMethod.Builder.create("doTask").withReturnType(void.class) .withModifier(new MemberModifier(AccessModifierKey.PUBLIC)) .withParams( new JavaParameter(JavaClassUtils.getMap(JavaClassUtils.getMap( JavaClassUtils.CLASS, Object.class), Object.class), "map"), new JavaParameter(Object.class, "obj") ).build() ); Set<JavaMethod> compiledMethods = JavaCompiler.compileJavaMethods(CompileTest.class, DOCUMENT); Assertions.assertEquals(expectedJavaMethods, compiledMethods); } @Test void shouldNotCompileSyntheticConstructsFromClass() throws DetailParsingException { Class<?> nestedClass = CompileSyntheticTest.NestedClass.class; Method[] nestedMethods = nestedClass.getDeclaredMethods(); // when building on Unix CI we find 3 declared methods instead of 2 Assertions.assertTrue(nestedMethods.length > 1 && nestedMethods.length < 4); for (Method declaredMethod : nestedMethods) { Assertions.assertTrue(declaredMethod.isSynthetic()); } Set<JavaMethod> compiledMethods = JavaCompiler.compileJavaMethods(nestedClass, null); Assertions.assertEquals(0, compiledMethods.size()); Field[] nestedFields = nestedClass.getDeclaredFields(); // when building on Unix CI we find 3 declared fields instead of 2 Assertions.assertTrue(nestedFields.length > 1 && nestedFields.length < 4); Assertions.assertFalse(nestedFields[0].isSynthetic()); Assertions.assertTrue(nestedFields[1].isSynthetic()); List<JavaField> compiledFields = JavaCompiler.compileJavaFields(nestedClass, null); Assertions.assertEquals(1, compiledFields.size()); Assertions.assertEquals("nestedField", compiledFields.get(0).getName()); } @SuppressWarnings({ "unused", "SameReturnValue", "ProtectedMembersInFinalClass", "EmptyMethod" }) private static final class CompileTest { //@formatter:off public float a; private final Integer b = null; protected static final Color black = null; static Color[] blue; public ArrayList<Color> cyan; //@formatter:on protected static boolean DoesInstantly(int number) { return false; } @SuppressWarnings({ "FinalPrivateMethod", "FinalStaticMethod" }) private static final String init(String object, String[] params) { return ""; } @TestOnly static void update(ArrayList<String> params) { } static ArrayList<String> getActivatedMods() { return new ArrayList<>(); } public int begin(Object param) { return 0; } Object[] IsFinished() { return new Object[0]; } public Color[] getColor(IsoPlayer player) { return new Color[0]; } public void doTask(Map<Map<Class<?>, Object>, Object> map, Object obj) { } } @SuppressWarnings("unused") private static class CompileSyntheticTest { public String getNestedField() { return new NestedClass().nestedField; } public void setNestedField(String nestedField) { new NestedClass().nestedField = nestedField; } @SuppressWarnings({ "WeakerAccess", "InnerClassMayBeStatic", "ClassCanBeStatic" }) class NestedClass { private String nestedField; } } }
10,505
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
String.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/test/String.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile.test; import org.jetbrains.annotations.TestOnly; @TestOnly @SuppressWarnings("JavaLangClash") public class String { }
907
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Object.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/test/Object.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile.test; import org.jetbrains.annotations.TestOnly; @TestOnly @SuppressWarnings("JavaLangClash") public class Object { }
907
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Integer.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/compile/test/Integer.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.compile.test; import org.jetbrains.annotations.TestOnly; @TestOnly @SuppressWarnings("JavaLangClash") public class Integer { }
908
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
ParseUtilsTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/util/ParseUtilsTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.util; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ParseUtilsTest { @Test void shouldGetValidRegexMatchedGroups() { Pattern pattern = Pattern.compile("(brown)\\s+(dog)\\s+(barks)(\\s+)?"); Matcher matcher = pattern.matcher("brown dog barks"); Assertions.assertThrows(IllegalStateException.class, () -> ParseUtils.getOptionalMatchedGroup(matcher, 1)); Assertions.assertTrue(matcher.find()); Assertions.assertEquals("brown", ParseUtils.getOptionalMatchedGroup(matcher, 1)); Assertions.assertEquals("dog", ParseUtils.getOptionalMatchedGroup(matcher, 2)); Assertions.assertEquals("barks", ParseUtils.getOptionalMatchedGroup(matcher, 3)); Assertions.assertEquals("", ParseUtils.getOptionalMatchedGroup(matcher, 4)); Assertions.assertThrows(IndexOutOfBoundsException.class, () -> ParseUtils.getOptionalMatchedGroup(matcher, 5)); } }
1,745
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
UtilsTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/util/UtilsTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.util; import java.net.MalformedURLException; import java.net.URL; import org.jetbrains.annotations.TestOnly; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class UtilsTest { @Test void shouldResolveUrlWithMultipleDirectories() throws MalformedURLException { URL url = new URL("https://worldwideweb.com"); URL result = Utils.getURL(url, "one", "two", "three"); String expected = "https://worldwideweb.com/one/two/three"; Assertions.assertEquals(expected, result.toString()); } @Test void shouldGetValidClassForObjectClassName() throws ClassNotFoundException { Assertions.assertEquals(Object.class, Utils.getClassForName(Object.class.getName())); Assertions.assertThrows(ClassNotFoundException.class, () -> Utils.getClassForName("nonExistingClass" )); } @Test void shouldGetValidArrayClassForObjectClassName() throws ClassNotFoundException { Assertions.assertEquals(String[].class, Utils.getClassForName("java.lang.String[]")); Assertions.assertEquals(String[][].class, Utils.getClassForName("java.lang.String[][]")); } @Test void shouldGetValidClassForPrimitiveClassName() throws ClassNotFoundException { Assertions.assertEquals(boolean.class, Utils.getClassForName("boolean")); Assertions.assertEquals(byte.class, Utils.getClassForName("byte")); Assertions.assertEquals(char.class, Utils.getClassForName("char")); Assertions.assertEquals(short.class, Utils.getClassForName("short")); Assertions.assertEquals(int.class, Utils.getClassForName("int")); Assertions.assertEquals(long.class, Utils.getClassForName("long")); Assertions.assertEquals(float.class, Utils.getClassForName("float")); Assertions.assertEquals(double.class, Utils.getClassForName("double")); Assertions.assertEquals(void.class, Utils.getClassForName("void")); } @Test void shouldGetCorrectClassForName() { String[] badClassPaths = new String[] { "io.cocolabs.pz.zdoc.util.UtilsTest.TestClass.TestClass2", "io.cocolabs.pz.zdoc.util.UtilsTest.TestClass.TestClass2.TestClass3" }; for (String classPath : badClassPaths) { Assertions.assertThrows(ClassNotFoundException.class, () -> Utils.getClassForName(classPath)); } String[] goodClassPaths = new String[] { "io.cocolabs.pz.zdoc.util.UtilsTest.TestClass$TestClass2", "io.cocolabs.pz.zdoc.util.UtilsTest.TestClass$TestClass2$TestClass3" }; for (String classPath : goodClassPaths) { Assertions.assertDoesNotThrow(() -> Utils.getClassForName(classPath)); } } @TestOnly public static final class TestClass { @SuppressWarnings("unused") public static final class TestClass2 { public static final class TestClass3 { } } } }
3,462
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaFieldTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaFieldTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.element.lua.LuaType; class EmmyLuaFieldTest { @Test void shouldCorrectlyFormatEmmyLuaFieldAnnotation() { // ---@field field_name FIELD_TYPE EmmyLuaField annotation = new EmmyLuaField("car", new LuaType("Vehicle")); Assertions.assertEquals("---@field car Vehicle", annotation.toString()); // ---@field field_name FIELD_TYPE|OTHER_TYPE annotation = new EmmyLuaField("car", new LuaType("Vehicle", new LuaType("Object")) ); Assertions.assertEquals("---@field car Vehicle|Object", annotation.toString()); // ---@field public field_name FIELD_TYPE|OTHER_TYPE annotation = new EmmyLuaField("car", "public", new LuaType("Vehicle", new LuaType("Object") )); Assertions.assertEquals("---@field public car Vehicle|Object", annotation.toString()); // ---@field field_name FIELD_TYPE|OTHER_TYPE [@comment] annotation = new EmmyLuaField("car", new LuaType("Vehicle", new LuaType("Object")), "goes vroom" ); Assertions.assertEquals("---@field car Vehicle|Object @goes vroom", annotation.toString()); // ---@field protected field_name FIELD_TYPE|OTHER_TYPE [@comment] annotation = new EmmyLuaField("car", "protected", new LuaType("Vehicle", new LuaType("Object")), "goes vroom" ); Assertions.assertEquals("---@field protected car Vehicle|Object @goes vroom", annotation.toString()); } @Test void shouldParseEmmyLuaFieldAnnotationFromString() { String[] fieldAnnotations = new String[]{ "---@field type", "---@field public type", "---@field type @comment_", "---@field protected type @comment_", "---@field type@ comment-line", "---@field private type@ comment-line", "---@field type|other_type", "---@field public type|other_type", "---@field type|other_type @comment", "---@field protected type|other_type @comment", "---@field type | other_type @comment# !line", "---@field private type | other_type @comment# !line", "---@field type| other_type@comment ", "---@field public type| other_type@comment ", "---@field type |other_type @ comment ", "---@field protected type |other_type @ comment ", }; for (String fieldAnnotation : fieldAnnotations) { Assertions.assertTrue(EmmyLuaField.isAnnotation(fieldAnnotation)); } Assertions.assertFalse(EmmyLuaField.isAnnotation("--@field testClass")); Assertions.assertFalse(EmmyLuaField.isAnnotation("---@fields testClass")); } }
3,301
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaParamTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaParamTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.element.lua.LuaType; class EmmyLuaParamTest { @Test void shouldCorrectlyFormatEmmyLuaParamAnnotation() { // ---@param param_name TYPE EmmyLuaParam annotation = new EmmyLuaParam("apple", new LuaType("Apple")); Assertions.assertEquals("---@param apple Apple", annotation.toString()); // ---@param param_name TYPE[|other_type] annotation = new EmmyLuaParam("apple", new LuaType("Apple", new LuaType("Fruit")) ); Assertions.assertEquals("---@param apple Apple|Fruit", annotation.toString()); // ---@param param_name TYPE[|other_type] [@comment] annotation = new EmmyLuaParam("apple", new LuaType("Apple", new LuaType("Fruit")), "very healthy" ); Assertions.assertEquals("---@param apple Apple|Fruit @very healthy", annotation.toString()); } @Test void shouldParseEmmyLuaParamAnnotationFromString() { String[] paramAnnotations = new String[]{ "---@param param_name type", "---@param param_name type @comment_", "---@param param_name type@ comment-line", "---@param param_name type|other_type", "---@param param_name type|other_type @comment", "---@param param_name type | other_type @comment# !line", "---@param param_name type| other_type@comment ", "---@param param_name type |other_type @ comment ", }; for (String paramAnnotation : paramAnnotations) { Assertions.assertTrue(EmmyLuaParam.isAnnotation(paramAnnotation)); } Assertions.assertFalse(EmmyLuaParam.isAnnotation("--@param testParam testType")); Assertions.assertFalse(EmmyLuaClass.isAnnotation("---@params testParam testType")); } }
2,475
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.HashSet; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.MainTest; import io.cocolabs.pz.zdoc.element.lua.LuaType; class EmmyLuaTest { @Test void shouldCorrectlyValidateEmmyLuaBuiltInTypes() { for (String type : EmmyLua.BUILT_IN_TYPES) { Assertions.assertTrue(EmmyLua.isBuiltInType(type)); Assertions.assertFalse(EmmyLua.isBuiltInType(type.toUpperCase())); } Assertions.assertFalse(EmmyLua.isBuiltInType("testType")); } @Test void shouldCorrectlyValidateLuaReservedKeywords() { for (String keyword : EmmyLua.RESERVED_KEYWORDS) { Assertions.assertTrue(EmmyLua.isReservedKeyword(keyword)); Assertions.assertFalse(EmmyLua.isReservedKeyword(keyword.toUpperCase())); } Assertions.assertFalse(EmmyLua.isReservedKeyword("testKeyword")); } @Test void shouldEnsureLuaMemberNameSafety() { Set<String> reserved = new HashSet<>(); reserved.addAll(EmmyLua.RESERVED_KEYWORDS); reserved.addAll(EmmyLua.BUILT_IN_TYPES); for (String keyword : reserved) { Assertions.assertEquals('_' + keyword, EmmyLua.getSafeLuaName(keyword)); } Assertions.assertNotEquals("type", EmmyLua.getSafeLuaName("Type")); } @Test void shouldFormatTypeWithCorrectSafeName() { MainTest.registerClassOverride("Vector2", "JVector2"); MainTest.registerClassOverride("TestClass", "JTestClass"); LuaType expectedResult = new LuaType("Vector2"); Assertions.assertEquals("JVector2", EmmyLua.formatType(expectedResult)); expectedResult = new LuaType("Vector2", new LuaType("TestClass")); Assertions.assertEquals("JVector2|JTestClass", EmmyLua.formatType(expectedResult)); } }
2,490
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaOverloadTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaOverloadTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.google.common.collect.ImmutableList; import io.cocolabs.pz.zdoc.element.lua.LuaParameter; import io.cocolabs.pz.zdoc.element.lua.LuaType; public class EmmyLuaOverloadTest { @Test void shouldProperlyFormatEmmyLuaOverloadAnnotation() { List<LuaParameter> params = ImmutableList.of( new LuaParameter(new LuaType("Object"), "arg0"), new LuaParameter(new LuaType("Number"), "arg1"), new LuaParameter(new LuaType("String"), "arg2") ); EmmyLuaOverload annotation = new EmmyLuaOverload(params); String expected = "---@overload fun(arg0:Object, arg1:Number, arg2:String)"; Assertions.assertEquals(expected, annotation.toString()); } }
1,555
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaReturnTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaReturnTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.cocolabs.pz.zdoc.element.lua.LuaMethod; import io.cocolabs.pz.zdoc.element.lua.LuaType; class EmmyLuaReturnTest { @Test void shouldCorrectlyFormatEmmyLuaReturnAnnotation() { // ---@return TYPE EmmyLuaReturn annotation = new EmmyLuaReturn(new LuaMethod.ReturnType("Dog")); Assertions.assertEquals("---@return Dog", annotation.toString()); // ---@return TYPE @comment LuaType luaType = new LuaType("Dog"); String comment = "returns a dog class"; annotation = new EmmyLuaReturn(new LuaMethod.ReturnType(luaType, comment)); Assertions.assertEquals("---@return Dog @" + comment, annotation.toString()); // ---@return TYPE|OTHER_TYPE @commnet luaType = new LuaType("Dog", new LuaType("Animal")); comment = "returns an Animal class"; annotation = new EmmyLuaReturn(new LuaMethod.ReturnType(luaType, comment)); Assertions.assertEquals("---@return Dog|Animal @" + comment, annotation.toString()); } @Test void shouldParseEmmyLuaReturnAnnotationFromString() { String[] returnAnnotations = new String[]{ "---@return type", "---@return type @comment_", "---@return type@ comment-line", "---@return type|other_type", "---@return type|other_type @comment", "---@return type | other_type @comment# !line", "---@return type| other_type@comment ", "---@return type |other_type @ comment ", }; for (String returnAnnotation : returnAnnotations) { Assertions.assertTrue(EmmyLuaReturn.isAnnotation(returnAnnotation)); } Assertions.assertFalse(EmmyLuaReturn.isAnnotation("--@return testReturnType")); Assertions.assertFalse(EmmyLuaReturn.isAnnotation("---@returnk testReturnType")); } }
2,531
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
EmmyLuaClassTest.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/test/java/io/cocolabs/pz/zdoc/lang/lua/EmmyLuaClassTest.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.lang.lua; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class EmmyLuaClassTest { @Test void shouldCorrectlyFormatEmmyLuaClassAnnotation() { // ---@class TYPE EmmyLuaClass annotation = new EmmyLuaClass("Car", null); Assertions.assertEquals("---@class Car", annotation.toString()); // ---@class TYPE[:PARENT_TYPE] annotation = new EmmyLuaClass("Car", "Vehicle"); Assertions.assertEquals("---@class Car : Vehicle", annotation.toString()); // ---@class TYPE[:PARENT_TYPE] [@comment] annotation = new EmmyLuaClass("Car", "Vehicle", "goes vroom"); Assertions.assertEquals("---@class Car : Vehicle @goes vroom", annotation.toString()); } @Test void shouldParseEmmyLuaClassAnnotationFromString() { String[] classAnnotations = new String[]{ "---@class type", "---@class type @comment_", "---@class type@ comment-line", "---@class type:other_type", "---@class type:other_type @comment", "---@class type : other_type @comment# !line", "---@class type: other_type@comment ", "---@class type :other_type @ comment ", }; for (String classAnnotation : classAnnotations) { Assertions.assertTrue(EmmyLuaClass.isAnnotation(classAnnotation)); } Assertions.assertFalse(EmmyLuaClass.isAnnotation("--@class testClass")); Assertions.assertFalse(EmmyLuaClass.isAnnotation("---@classs testClass")); } }
2,167
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
Main.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/Main.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.apache.logging.log4j.util.Strings; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import io.cocolabs.pz.zdoc.cmd.Command; import io.cocolabs.pz.zdoc.cmd.CommandLine; import io.cocolabs.pz.zdoc.compile.CompilerException; import io.cocolabs.pz.zdoc.compile.JavaCompiler; import io.cocolabs.pz.zdoc.compile.LuaAnnotator; import io.cocolabs.pz.zdoc.compile.LuaCompiler; import io.cocolabs.pz.zdoc.doc.ZomboidJavaDoc; import io.cocolabs.pz.zdoc.doc.ZomboidLuaDoc; import io.cocolabs.pz.zdoc.element.lua.LuaClass; import io.cocolabs.pz.zdoc.logger.Logger; import io.cocolabs.pz.zdoc.util.Utils; public class Main { public static final String CHARSET = StandardCharsets.UTF_8.name(); public static final ClassLoader CLASS_LOADER = Main.class.getClassLoader(); static final Map<String, String> CLASS_OVERRIDES = new HashMap<>(); public static void main(String[] args) throws IOException, ParseException, CompilerException { Logger.debug(String.format("Started application with %d args: %s", args.length, Arrays.toString(args))); Command command = Command.parse(args); if (command == null) { String format = "Missing or unknown command argument (%s)"; throw new ParseException(String.format(format, Arrays.toString(args))); } else if (command == Command.HELP) { Command info = args.length > 1 ? Command.parse(args, 1) : null; if (info == null) { CommandLine.printHelp(Command.values()); } else CommandLine.printHelp(info); return; } else if (command == Command.VERSION) { try { /* first try to find version file project root directory, * available when we are not running from a jar */ String zdocVersion; File versionFile = new File("version.txt"); if (!versionFile.exists()) { try (InputStream iStream = CLASS_LOADER.getResourceAsStream("version.txt")) { if (iStream == null) { throw new FileNotFoundException("Unable to read version, missing version.txt"); } try (Reader reader = new InputStreamReader(iStream, Charsets.UTF_8)) { zdocVersion = CharStreams.toString(reader); } } } else zdocVersion = FileUtils.readFileToString(versionFile, CHARSET); Logger.info("zdoc version " + zdocVersion); Class<?> coreClass = Utils.getClassForName("zombie.core.Core"); Object core = MethodUtils.invokeStaticMethod(coreClass, "getInstance"); Object gameVersion = MethodUtils.invokeExactMethod(core, "getGameVersion"); Object sGameVersion = MethodUtils.invokeExactMethod(gameVersion, "toString"); Logger.info("game version " + sGameVersion); return; } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } } CommandLine cmdLine = CommandLine.parse(command.getOptions(), args); Set<String> exclude = cmdLine.getExcludedClasses(); if (command == Command.ANNOTATE) { Logger.debug("Preparing to parse and document lua files..."); Path root = cmdLine.getInputPath(); List<Path> paths; Path dir = cmdLine.getOutputPath(); try (Stream<Path> stream = Files.walk(Paths.get(root.toString()))) { paths = stream.filter(Files::isRegularFile).collect(Collectors.toCollection(ArrayList::new)); } if (paths.size() > 1) { Logger.info("Parsing and documenting lua files found in " + root); } else if (paths.isEmpty()) { Logger.warn("No files found under path " + root); } boolean onlyAnnotated = cmdLine.includeOnlyAnnotated(); Properties properties = Utils.getProperties("annotate.properties"); // process every file found under given root path for (Path path : paths) { if (Utils.isLuaFile(path)) { Logger.debug(String.format("Found lua file \"%s\"", path.getFileName())); Path outputFilePath; if (!root.toFile().exists()) { throw new FileNotFoundException(root.toString()); } /* user did not specify output dir path */ else if (dir != null) { File outputDirFile = dir.toFile(); if (!outputDirFile.exists() && !outputDirFile.mkdirs()) { throw new IOException("Unable to create output directory: " + dir); } /* root path matches current path so there are no * subdirectories, just resolve the filename against root path */ if (root.compareTo(path) == 0) { outputFilePath = dir.resolve(path.getFileName()); } else outputFilePath = dir.resolve(root.relativize(path)); } /* overwrite file when unspecified output directory */ else { outputFilePath = path; Logger.warn("Unspecified output directory, overwriting files"); } File outputFile = outputFilePath.toFile(); String fileName = path.getFileName().toString(); List<String> content = new ArrayList<>(); LuaAnnotator.AnnotateRules rules = new LuaAnnotator.AnnotateRules(properties, exclude); LuaAnnotator.AnnotateResult result = LuaAnnotator.annotate(path.toFile(), content, rules); String addendum = outputFile.exists() ? " and overwriting" : ""; Logger.debug(String.format("Annotating%s file %s...", addendum, fileName)); switch (result) { case ALL_INCLUDED: Logger.info(String.format("Finished annotating file \"%s\", " + "all elements matched.", fileName)); writeAnnotatedLinesToFile(content, outputFile); break; case PARTIAL_INCLUSION: Logger.error(String.format("Failed annotating file \"%s\", " + "some elements were not matched.", fileName)); writeAnnotatedLinesToFile(content, outputFile); break; case NO_MATCH: Logger.error(String.format("Failed annotating file \"%s\", " + "no elements were matched", fileName)); if (!onlyAnnotated) { writeAnnotatedLinesToFile(content, outputFile); } break; case SKIPPED_FILE_IGNORED: Logger.warn(String.format("Skipped annotating file \"%s\", " + "file was ignored.", fileName)); if (!onlyAnnotated) { writeAnnotatedLinesToFile(content, outputFile); } break; case SKIPPED_FILE_EMPTY: Logger.warn(String.format("Skipped annotating file \"%s\", " + "file was empty.", fileName)); if (!onlyAnnotated) { writeAnnotatedLinesToFile(content, outputFile); } break; case ALL_EXCLUDED: Logger.warn(String.format("Skipped annotating file \"%s\", " + "all elements were excluded.", fileName)); if (!onlyAnnotated) { writeAnnotatedLinesToFile(content, outputFile); } break; } } } } else if (command == Command.COMPILE) { Logger.debug("Preparing to parse java doc..."); Path userOutput = cmdLine.getOutputPath(); if (userOutput == null) { userOutput = Paths.get("."); Logger.debug("Output directory not specified, using root directory instead"); } File outputDir = userOutput.toFile(); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new IOException("Unable to create output directory"); } } else if (!outputDir.isDirectory()) { throw new IllegalArgumentException("Output path does not point to a directory"); } else Logger.debug("Designated output path: " + userOutput); Properties properties = Utils.getProperties("compile.properties"); Logger.debug("Reading compile.properties, found %d keys", properties.size()); String excludeProp = properties.getProperty("exclude"); if (!StringUtils.isBlank(excludeProp)) { List<String> excludeEntries = Arrays.asList(excludeProp.split(",")); Logger.debug("Loaded %d exclude entries from compile.properties", excludeEntries.size()); exclude.addAll(excludeEntries); } // remove exclude property so it doesnt get included as override entry properties.remove(exclude); // store all class override entries in map for (Map.Entry<Object, Object> entry : properties.entrySet()) { String override = (String) entry.getValue(); if (Strings.isNotBlank(override)) { CLASS_OVERRIDES.put((String) entry.getKey(), override); } } Set<ZomboidJavaDoc> compiledJava = new JavaCompiler(exclude).compile(); Set<ZomboidLuaDoc> compiledLua = new LuaCompiler(compiledJava).compile(); for (ZomboidLuaDoc zLuaDoc : compiledLua) { String luaDocName = zLuaDoc.getName(); String luaDocProp = properties.getProperty(luaDocName); if (luaDocProp != null) { // override lua document name with property value if (!StringUtils.isBlank(luaDocProp)) { ZomboidLuaDoc overrideDoc = new ZomboidLuaDoc( new LuaClass(luaDocProp, zLuaDoc.getClazz().getParentType()), zLuaDoc.getFields(), zLuaDoc.getMethods() ); overrideDoc.writeToFile(userOutput.resolve(luaDocProp + ".lua").toFile()); } } else zLuaDoc.writeToFile(userOutput.resolve(luaDocName + ".lua").toFile()); } Logger.info("Compiled and written %d lua documents", compiledLua.size()); ZomboidLuaDoc.writeGlobalTypesToFile(userOutput.resolve("Types.lua").toFile()); for (String excludedClass : exclude) { Logger.warn("Class " + excludedClass + " was designated but not excluded from compilation."); } } Logger.debug("Finished processing command"); /* * exit application gracefully to avoid unpredictable * AGENT_ERROR_NO_JNI_ENV error that is present in J8 sun classes: * https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6476706 */ System.exit(0); } /** * <p>Returns Lua class name that is safe to use in compiled library.</p> * <p>Note that it is safe to pass array class names (ex. {@code Vector2[]}).</p> * * @param name name of the class name to lookup. */ public static String getSafeLuaClassName(String name) { boolean isArray = name.endsWith("[]"); String sName = isArray ? name.substring(0, name.length() - 2) : name; String override = CLASS_OVERRIDES.get(sName); return override != null ? (!isArray ? override : override + "[]") : name; } private static void writeAnnotatedLinesToFile(List<String> lines, File file) throws IOException { // do not write empty content if (lines.isEmpty()) { return; } // make sure output file exists before we try to write to it if (!file.exists()) { File parentFile = file.getParentFile(); if (!parentFile.exists() && (!parentFile.mkdirs() || !file.createNewFile())) { throw new IOException("Unable to create specified output file: " + file); } } FileUtils.writeLines(file, lines, false); } }
11,794
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
SignatureToken.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/SignatureToken.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; public interface SignatureToken { }
825
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IField.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IField.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; /** * This class represents a simple generic {@code Field} object. */ public interface IField extends IMember { IClass getType(); /** Returns name of the {@code Field} represented by this object. */ @Override String getName(); /** Returns a string describing this {@code Field}. */ @Override String toString(); }
1,114
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IMember.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IMember.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; /** * Member is an interface that reflects identifying information about * a single member (a field or a method) or a constructor. * * @see java.lang.reflect.Member */ public interface IMember { /** * Returns the simple name of the underlying member or constructor * represented by this Member. * * @return the simple name of the underlying member */ String getName(); MemberModifier getModifier(); String getComment(); }
1,289
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IReturnType.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IReturnType.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; public interface IReturnType { String getComment(); }
844
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IClass.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IClass.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; import java.util.List; public interface IClass { String getName(); List<? extends IClass> getTypeParameters(); }
907
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IMethod.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IMethod.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; import java.util.List; import org.jetbrains.annotations.UnmodifiableView; public interface IMethod extends IMember { IClass getReturnType(); @UnmodifiableView List<? extends IParameter> getParams(); boolean hasVarArg(); }
1,019
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
IParameter.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/IParameter.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element; public interface IParameter { IClass getType(); String getName(); String getAsVarArg(); String getComment(); }
908
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z
JavaMethod.java
/FileExtraction/Java_unseen/cocolabs_pz-zdoc/src/main/java/io/cocolabs/pz/zdoc/element/java/JavaMethod.java
/* * ZomboidDoc - Lua library compiler for Project Zomboid * Copyright (C) 2020-2021 Matthew Cain * * 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 <http://www.gnu.org/licenses/>. */ package io.cocolabs.pz.zdoc.element.java; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.UnmodifiableView; import io.cocolabs.pz.zdoc.element.IMethod; import io.cocolabs.pz.zdoc.element.mod.MemberModifier; import io.cocolabs.pz.zdoc.logger.Logger; /** * This class represents a wrapped {@link Method} object. */ public class JavaMethod implements IMethod { private final String name; private final ReturnType returnType; private final List<JavaParameter> params; private final MemberModifier modifier; private final boolean hasVarArg; private final String comment; public JavaMethod(Builder builder) { this.name = builder.name; this.returnType = builder.returnType != null ? builder.returnType : new ReturnType(void.class); this.modifier = builder.modifier != null ? builder.modifier : MemberModifier.UNDECLARED; List<JavaParameter> jParams = builder.params != null ? builder.params : new ArrayList<>(); if (builder.hasVarArg) { if (!jParams.isEmpty()) { List<JavaParameter> tParams = new ArrayList<>(); /* * copy every element in params list except last one, * which has to be copied separately below */ int lastIndex = jParams.size() - 1; for (int i = 0; i < lastIndex; i++) { tParams.add(jParams.get(i)); } JavaParameter lastParam = jParams.get(lastIndex); JavaClass paramType = lastParam.getType(); /* * copy last parameter with an array of the original * class to match variadic argument in bytecode */ Class<?> arrayClass = Array.newInstance(paramType.getClazz(), 0).getClass(); JavaClass newJClass = new JavaClass(arrayClass, paramType.getTypeParameters()); tParams.add(new JavaParameter(newJClass, lastParam.getName())); this.params = Collections.unmodifiableList(tParams); } else { builder.hasVarArg = false; // initialize params before logging error with toString() to avoid NPE this.params = Collections.unmodifiableList(jParams); Logger.error("Method %s marked with hasVarArg with no parameters", toString()); } } else this.params = Collections.unmodifiableList(jParams); this.hasVarArg = builder.hasVarArg; this.comment = builder.comment; } public JavaMethod(Method method) { this.name = method.getName(); this.returnType = new ReturnType(method.getReturnType()); List<JavaParameter> params = new ArrayList<>(); for (Parameter methodParam : method.getParameters()) { params.add(new JavaParameter(methodParam)); } this.params = Collections.unmodifiableList(params); this.modifier = new MemberModifier(method.getModifiers()); this.hasVarArg = false; this.comment = ""; } @Override public String toString() { String sParams = ""; if (this.params.size() > 0) { final StringBuilder sb = new StringBuilder(); int lastElementIndex = params.size() - 1; // method has 2 or more parameters if (lastElementIndex > 0) { sb.append(params.get(0).toString()); for (int i = 1; i < lastElementIndex; i++) { sb.append(", ").append(params.get(i).toString()); } sb.append(", "); } JavaParameter lastParameter = params.get(lastElementIndex); sb.append(!hasVarArg ? lastParameter.toString() : lastParameter.getAsVarArg()); sParams = sb.toString(); } String modifier = this.modifier.toString(); modifier = modifier.isEmpty() ? "" : modifier + " "; return String.format("%s%s %s(%s)", modifier, returnType, getName(), sParams); } public static class Builder { private final String name; private @Nullable ReturnType returnType; private @Nullable MemberModifier modifier; private @Nullable List<JavaParameter> params; private boolean hasVarArg = false; private String comment = ""; public Builder(String name) { this.name = name; } public static Builder create(String name) { return new Builder(name); } public Builder withReturnType(JavaClass type, String comment) { returnType = new ReturnType(type, comment); return this; } public Builder withReturnType(JavaClass type) { returnType = new ReturnType(type, ""); return this; } public Builder withReturnType(Class<?> type) { returnType = new ReturnType(type); return this; } public Builder withParams(List<JavaParameter> params) { this.params = params; return this; } public Builder withModifier(MemberModifier modifier) { this.modifier = modifier; return this; } public Builder withParams(JavaParameter...params) { this.params = new ArrayList<>(Arrays.asList(params)); return this; } public Builder withVarArgs(boolean hasVarArg) { this.hasVarArg = hasVarArg; return this; } public Builder withComment(String comment) { this.comment = comment; return this; } public JavaMethod build() { return new JavaMethod(this); } } public static class ReturnType extends JavaClass { private final String comment; public ReturnType(Class<?> clazz, @Nullable List<JavaClass> typeParameters, String comment) { super(clazz, typeParameters); this.comment = comment; } public ReturnType(Class<?> clazz, @Nullable List<JavaClass> typeParameters) { this(clazz, typeParameters, ""); } public ReturnType(JavaClass clazz, String comment) { this(clazz.getClazz(), clazz.getTypeParameters(), comment); } public ReturnType(Class<?> clazz) { super(clazz); this.comment = ""; } public String getComment() { return comment; } } @Override public String getName() { return name; } @Override public MemberModifier getModifier() { return modifier; } @Override public String getComment() { return comment; } @Override public ReturnType getReturnType() { return returnType; } @Override public @UnmodifiableView List<JavaParameter> getParams() { return params; } @Override public boolean hasVarArg() { return hasVarArg; } @SuppressWarnings("ReferenceEquality") public boolean equals(JavaMethod method, boolean shallow) { if (shallow) { if (this == method) { return true; } if (method == null) { return false; } if (!name.equals(method.name)) { return false; } if (!returnType.equals(method.returnType, true)) { return false; } else if (!modifier.equals(method.modifier)) { return false; } if (params.size() != method.params.size()) { return false; } for (int i = 0; i < params.size(); i++) { if (!params.get(i).equals(method.params.get(i), true)) { return false; } } return true; } else return equals(method); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof JavaMethod)) { return false; } JavaMethod jMethod = (JavaMethod) obj; if (name.equals(jMethod.name) && returnType.equals(jMethod.returnType)) { return true; } if (hasVarArg != jMethod.hasVarArg) { return false; } return params.equals(jMethod.params) && modifier.equals(jMethod.modifier); } @Override public int hashCode() { int result = 31 * name.hashCode() + returnType.hashCode(); result = 31 * result + params.hashCode(); result = 31 * result + modifier.hashCode(); return 31 * result + (hasVarArg ? 1 : 0); } }
8,229
Java
.java
cocolabs/pz-zdoc
22
9
10
2020-11-20T17:19:36Z
2023-05-13T20:30:48Z