repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/forge/ClientProxy.java
// Path: src/com/mcf/davidee/msc/network/ClientPacketHandler.java // public class ClientPacketHandler extends MSCPacketHandler { // // // //TODO Verify that the GUIs are open for the correct mod? // // private Minecraft mc; // // public ClientPacketHandler() { // this.mc = Minecraft.getMinecraft(); // } // // @Override // protected boolean hasPermission(EntityPlayer player) { // return true; // } // // @Override // public void handleSettings(SettingsPacket pkt, EntityPlayer player) { // if(mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new SettingsScreen(pkt,mc.currentScreen)); // } // // @Override // public void handleAccessDenied(EntityPlayer player) { // if(mc.currentScreen == null) // mc.displayGuiScreen(new AccessDeniedScreen()); // } // // @Override // public void handleRequest(PacketType type, String mod, EntityPlayer player) { } // // @Override // public void handleHandShake(EntityPlayer player) { // if (mc.currentScreen == null) // mc.displayGuiScreen(new MainMenu()); // } // // @Override // public void handleModList(ModListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new ModListScreen(packet,mc.currentScreen)); // } // // @Override // public void handleDebug(DebugPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new DebugScreen(packet,mc.currentScreen)); // } // // @Override // public void handleCreatureType(CreatureTypePacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MobTypesMenu) // mc.displayGuiScreen(new EditCreatureTypeScreen(packet,mc.currentScreen)); // } // // @Override // public void handleGroups(GroupsPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof ModListScreen) // mc.displayGuiScreen(new GroupsMenu(packet,mc.currentScreen)); // // } // // @Override // public void handleBiomeList(BiomeListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof SpawnControlMenu) // mc.displayGuiScreen(new BiomeListScreen(packet, mc.currentScreen)); // } // // @Override // public void handleEntityList(EntityListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof SpawnControlMenu) // mc.displayGuiScreen(new EntityListScreen(packet,mc.currentScreen)); // } // // @Override // public void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof EntityListScreen) // mc.displayGuiScreen(new EditEntityScreen(packet, mc.currentScreen)); // } // // @Override // public void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen || // mc.currentScreen instanceof SpawnControlMenu && packet.biome.equalsIgnoreCase("master")) // mc.displayGuiScreen(new EditBiomeScreen(packet, mc.currentScreen)); // } // // @Override // public void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen) // mc.displayGuiScreen(new EvaluatedGroupsScreen(packet, mc.currentScreen)); // // } // // @Override // public void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen) // mc.displayGuiScreen(new EvaluatedBiomeScreen(packet, mc.currentScreen)); // // } // // } // // Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import java.io.File; import com.mcf.davidee.msc.network.ClientPacketHandler; import com.mcf.davidee.msc.network.MSCPacketHandler; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler;
package com.mcf.davidee.msc.forge; public class ClientProxy extends CommonProxy { protected final MSCPacketHandler client; public ClientProxy() { FMLCommonHandler.instance().bus().register(new KeyListener());
// Path: src/com/mcf/davidee/msc/network/ClientPacketHandler.java // public class ClientPacketHandler extends MSCPacketHandler { // // // //TODO Verify that the GUIs are open for the correct mod? // // private Minecraft mc; // // public ClientPacketHandler() { // this.mc = Minecraft.getMinecraft(); // } // // @Override // protected boolean hasPermission(EntityPlayer player) { // return true; // } // // @Override // public void handleSettings(SettingsPacket pkt, EntityPlayer player) { // if(mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new SettingsScreen(pkt,mc.currentScreen)); // } // // @Override // public void handleAccessDenied(EntityPlayer player) { // if(mc.currentScreen == null) // mc.displayGuiScreen(new AccessDeniedScreen()); // } // // @Override // public void handleRequest(PacketType type, String mod, EntityPlayer player) { } // // @Override // public void handleHandShake(EntityPlayer player) { // if (mc.currentScreen == null) // mc.displayGuiScreen(new MainMenu()); // } // // @Override // public void handleModList(ModListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new ModListScreen(packet,mc.currentScreen)); // } // // @Override // public void handleDebug(DebugPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MainMenu) // mc.displayGuiScreen(new DebugScreen(packet,mc.currentScreen)); // } // // @Override // public void handleCreatureType(CreatureTypePacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof MobTypesMenu) // mc.displayGuiScreen(new EditCreatureTypeScreen(packet,mc.currentScreen)); // } // // @Override // public void handleGroups(GroupsPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof ModListScreen) // mc.displayGuiScreen(new GroupsMenu(packet,mc.currentScreen)); // // } // // @Override // public void handleBiomeList(BiomeListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof SpawnControlMenu) // mc.displayGuiScreen(new BiomeListScreen(packet, mc.currentScreen)); // } // // @Override // public void handleEntityList(EntityListPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof SpawnControlMenu) // mc.displayGuiScreen(new EntityListScreen(packet,mc.currentScreen)); // } // // @Override // public void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof EntityListScreen) // mc.displayGuiScreen(new EditEntityScreen(packet, mc.currentScreen)); // } // // @Override // public void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen || // mc.currentScreen instanceof SpawnControlMenu && packet.biome.equalsIgnoreCase("master")) // mc.displayGuiScreen(new EditBiomeScreen(packet, mc.currentScreen)); // } // // @Override // public void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen) // mc.displayGuiScreen(new EvaluatedGroupsScreen(packet, mc.currentScreen)); // // } // // @Override // public void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player) { // if (mc.currentScreen instanceof BiomeListScreen) // mc.displayGuiScreen(new EvaluatedBiomeScreen(packet, mc.currentScreen)); // // } // // } // // Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/forge/ClientProxy.java import java.io.File; import com.mcf.davidee.msc.network.ClientPacketHandler; import com.mcf.davidee.msc.network.MSCPacketHandler; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; package com.mcf.davidee.msc.forge; public class ClientProxy extends CommonProxy { protected final MSCPacketHandler client; public ClientProxy() { FMLCommonHandler.instance().bus().register(new KeyListener());
client = new ClientPacketHandler();
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/spawning/SpawnCapHelper.java
// Path: src/com/mcf/davidee/msc/MobSpawnControls.java // @Mod(modid = "MSC2", name="Mob Spawn Controls 2", dependencies = "after:*", version=MobSpawnControls.VERSION) // public class MobSpawnControls{ // // public static final String VERSION = "1.2.1"; // public static final PacketPipeline DISPATCHER = new PacketPipeline(); // // @SidedProxy(clientSide = "com.mcf.davidee.msc.forge.ClientProxy", serverSide = "com.mcf.davidee.msc.forge.CommonProxy") // public static CommonProxy proxy; // @Instance("MSC2") // public static MobSpawnControls instance; // // private static FileHandler logHandler = null; // private static Logger logger = Logger.getLogger("MobSpawnControls"); // // // public static Logger getLogger() { // return logger; // } // // private SpawnConfiguration config, defaultConfig; // private SpawnFreqTicker ticker; // // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // ModMetadata modMeta = event.getModMetadata(); // modMeta.authorList = Arrays.asList(new String[] { "Davidee" }); // modMeta.autogenerated = false; // modMeta.credits = "Thanks to Mojang, Forge, and all your support."; // modMeta.description = "Allows you to control the vanilla spawning system."; // modMeta.url = "http://www.minecraftforum.net/topic/1909304-/"; // } // // @EventHandler // public void load(FMLInitializationEvent event) { // logger.setLevel(Level.ALL); // // try { // File logfile = new File(proxy.getMinecraftDirectory(),"MobSpawnControls.log"); // if ((logfile.exists() || logfile.createNewFile()) && logfile.canWrite() && logHandler == null) { // logHandler = new FileHandler(logfile.getPath()); // logHandler.setFormatter(new MSCLogFormatter()); // logger.addHandler(logHandler); // } // } catch (SecurityException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // logger.info("Mob Spawn Controls initializing..."); // // ticker = new SpawnFreqTicker(); // DISPATCHER.initialize(); // } // // @EventHandler // public void modsLoaded(FMLPostInitializationEvent event) { // BiomeClassLoader.loadBiomeClasses(); // logger.info("Generating default creature type map..."); // MobHelper.populateDefaultMap(); // logger.info("Mapping biomes..."); // BiomeNameHelper.initBiomeMap(); // logger.info("Creating default spawn configuration..."); // defaultConfig = new SpawnConfiguration(new File(new File(proxy.getMinecraftDirectory(),"config"), "default_msc")); // defaultConfig.load(); // defaultConfig.save(); // } // // @SubscribeEvent // public void onServerTick(ServerTickEvent event) { // ticker.tick(); // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent event) { // MinecraftServer server = event.getServer(); // WorldServer world = server.worldServerForDimension(0); // if (world != null && world.getSaveHandler() instanceof SaveHandler){ // logger.info("Creating spawn configuration for World \"" + world.getSaveHandler().getWorldDirectoryName() + "\""); // config = new SpawnConfiguration(new File(((SaveHandler)world.getSaveHandler()).getWorldDirectory(),"msc"), defaultConfig); // config.load(); // config.save(); // } // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent event) { // logger.info("Unloading spawn configuration"); // MSCLogFormatter.log.clear(); // config = null; // } // // public SpawnConfiguration getConfigNoThrow() { // return config; // } // // public SpawnConfiguration getConfig() throws RuntimeException { // if (config != null) // return config; // throw new RuntimeException("MSC: Null Spawn Config"); // } // // // }
import net.minecraft.entity.EnumCreatureType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.mcf.davidee.msc.MobSpawnControls;
package com.mcf.davidee.msc.spawning; public final class SpawnCapHelper { public static boolean setSpawnCap(EnumCreatureType type, int value) {
// Path: src/com/mcf/davidee/msc/MobSpawnControls.java // @Mod(modid = "MSC2", name="Mob Spawn Controls 2", dependencies = "after:*", version=MobSpawnControls.VERSION) // public class MobSpawnControls{ // // public static final String VERSION = "1.2.1"; // public static final PacketPipeline DISPATCHER = new PacketPipeline(); // // @SidedProxy(clientSide = "com.mcf.davidee.msc.forge.ClientProxy", serverSide = "com.mcf.davidee.msc.forge.CommonProxy") // public static CommonProxy proxy; // @Instance("MSC2") // public static MobSpawnControls instance; // // private static FileHandler logHandler = null; // private static Logger logger = Logger.getLogger("MobSpawnControls"); // // // public static Logger getLogger() { // return logger; // } // // private SpawnConfiguration config, defaultConfig; // private SpawnFreqTicker ticker; // // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // ModMetadata modMeta = event.getModMetadata(); // modMeta.authorList = Arrays.asList(new String[] { "Davidee" }); // modMeta.autogenerated = false; // modMeta.credits = "Thanks to Mojang, Forge, and all your support."; // modMeta.description = "Allows you to control the vanilla spawning system."; // modMeta.url = "http://www.minecraftforum.net/topic/1909304-/"; // } // // @EventHandler // public void load(FMLInitializationEvent event) { // logger.setLevel(Level.ALL); // // try { // File logfile = new File(proxy.getMinecraftDirectory(),"MobSpawnControls.log"); // if ((logfile.exists() || logfile.createNewFile()) && logfile.canWrite() && logHandler == null) { // logHandler = new FileHandler(logfile.getPath()); // logHandler.setFormatter(new MSCLogFormatter()); // logger.addHandler(logHandler); // } // } catch (SecurityException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // logger.info("Mob Spawn Controls initializing..."); // // ticker = new SpawnFreqTicker(); // DISPATCHER.initialize(); // } // // @EventHandler // public void modsLoaded(FMLPostInitializationEvent event) { // BiomeClassLoader.loadBiomeClasses(); // logger.info("Generating default creature type map..."); // MobHelper.populateDefaultMap(); // logger.info("Mapping biomes..."); // BiomeNameHelper.initBiomeMap(); // logger.info("Creating default spawn configuration..."); // defaultConfig = new SpawnConfiguration(new File(new File(proxy.getMinecraftDirectory(),"config"), "default_msc")); // defaultConfig.load(); // defaultConfig.save(); // } // // @SubscribeEvent // public void onServerTick(ServerTickEvent event) { // ticker.tick(); // } // // @EventHandler // public void serverStarting(FMLServerStartingEvent event) { // MinecraftServer server = event.getServer(); // WorldServer world = server.worldServerForDimension(0); // if (world != null && world.getSaveHandler() instanceof SaveHandler){ // logger.info("Creating spawn configuration for World \"" + world.getSaveHandler().getWorldDirectoryName() + "\""); // config = new SpawnConfiguration(new File(((SaveHandler)world.getSaveHandler()).getWorldDirectory(),"msc"), defaultConfig); // config.load(); // config.save(); // } // } // // @EventHandler // public void serverStopping(FMLServerStoppingEvent event) { // logger.info("Unloading spawn configuration"); // MSCLogFormatter.log.clear(); // config = null; // } // // public SpawnConfiguration getConfigNoThrow() { // return config; // } // // public SpawnConfiguration getConfig() throws RuntimeException { // if (config != null) // return config; // throw new RuntimeException("MSC: Null Spawn Config"); // } // // // } // Path: src/com/mcf/davidee/msc/spawning/SpawnCapHelper.java import net.minecraft.entity.EnumCreatureType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.mcf.davidee.msc.MobSpawnControls; package com.mcf.davidee.msc.spawning; public final class SpawnCapHelper { public static boolean setSpawnCap(EnumCreatureType type, int value) {
MobSpawnControls.getLogger().info("Attempting to set spawn cap to " + value + " for " + type );
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/DebugPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class DebugPacket extends MSCPacket { public String[] log; @Override public MSCPacket readData(Object... data) { log = (String[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeStringArray(log, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { log = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/DebugPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class DebugPacket extends MSCPacket { public String[] log; @Override public MSCPacket readData(Object... data) { log = (String[]) data[0]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeStringArray(log, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { log = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/RequestPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.google.common.primitives.UnsignedBytes; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class RequestPacket extends MSCPacket { private byte request; private String mod; @Override public MSCPacket readData(Object... data) { request = (Byte) data[0]; if (data.length > 1) mod = (String) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeByte(request); writeString(mod != null ? mod : "", to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { request = from.readByte(); mod = readString(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/RequestPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.google.common.primitives.UnsignedBytes; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class RequestPacket extends MSCPacket { private byte request; private String mod; @Override public MSCPacket readData(Object... data) { request = (Byte) data[0]; if (data.length > 1) mod = (String) data[1]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { to.writeByte(request); writeString(mod != null ? mod : "", to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { request = from.readByte(); mod = readString(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/grouping/BiomeOperand.java
// Path: src/com/mcf/davidee/msc/BiomeNameHelper.java // public class BiomeNameHelper { // // public static final int MAX_REG_ID = 39; // public static final List<Integer> VANILLA_MUT = Arrays.asList(129, 130, 131, 132, 133, 134, 140, 149, 151, 155, 156, 157, 158, 160, 162, 163, 164, 165, 166, 167); // // // // private static Map<String, BiomeGenBase> biomeMap; // private static Set<BiomeGenBase> biomeSet; // // private final static Map<String, String> nameSimplificationMap = new HashMap<String, String>(); // // static { // nameSimplificationMap.put("biomesoplenty.biomes", "BOP"); // nameSimplificationMap.put("extrabiomes.module.summa.biome", "EBXL"); // nameSimplificationMap.put("twilightforest.biomes", "TF"); // nameSimplificationMap.put("bwg4.biomes", "BWG4"); // nameSimplificationMap.put("highlands.biome", "HL"); // nameSimplificationMap.put("net.tropicraft.world.biomes", "TROP"); // nameSimplificationMap.put("xolova.blued00r.divinerpg.generation", "DRPG"); // } // // //TODO This better - recognize vanilla biomes some other way // public static boolean isVanilla(BiomeGenBase biome) { // return biome.biomeID <= MAX_REG_ID || VANILLA_MUT.contains(biome.biomeID); // } // // // public static String getBiomeName(BiomeGenBase biome) { // String name = ((isVanilla(biome)) ? "Vanilla" : biome.getClass().getName()) + '.' + biome.biomeName; // for (Entry<String,String> entry : nameSimplificationMap.entrySet()) // if (name.startsWith(entry.getKey())) // return entry.getValue() + '.' + biome.biomeName; // return name; // } // // public static BiomeGenBase getBiome(String biomeName) { // return biomeMap.get(biomeName); // } // // public static void initBiomeMap() { // if (biomeMap != null) // return; // // biomeMap = new HashMap<String, BiomeGenBase>(); // biomeSet = new HashSet<BiomeGenBase>(); // // for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { // if (biome != null) { // biomeMap.put(getBiomeName(biome), biome); // biomeSet.add(biome); // } // } // } // // public static Set<BiomeGenBase> getAllBiomes() { // return biomeSet; // } // // public static Set<String> getAllBiomeNames() { // return biomeMap.keySet(); // } // } // // Path: src/com/mcf/davidee/msc/Utils.java // public class Utils { // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static <E> Set<E> asSet(E... arr) { // Set<E> set = new HashSet<E>(); // for (E obj : arr) // set.add(obj); // return set; // } // // public static <E> List<E> asList(E... arr) { // List<E> list = new ArrayList<E>(); // for (E obj : arr) // list.add(obj); // return list; // } // // public static <T> void copyInto(List<T> source, List<T> dest) { // dest.clear(); // for (T obj : source) // dest.add(obj); // } // // public static void writeLine(BufferedWriter writer, String line) throws IOException { // writer.write(line); // writer.newLine(); // } // }
import java.util.Set; import net.minecraft.world.biome.BiomeGenBase; import com.mcf.davidee.msc.BiomeNameHelper; import com.mcf.davidee.msc.Utils;
package com.mcf.davidee.msc.grouping; public class BiomeOperand { public final BiomeOperator operator; private BiomeGroup group; private BiomeGenBase biome; private boolean isGroup, isAll; public BiomeOperand() { this.operator = BiomeOperator.ALL; isAll = true; } public BiomeOperand(BiomeOperator op, BiomeGroup group) { this.operator = op; this.group = group; isGroup = true; } public BiomeOperand(BiomeOperator op, BiomeGenBase biome) { this.operator = op; this.biome = biome; } public Set<BiomeGenBase> getBiomes() { if (isAll)
// Path: src/com/mcf/davidee/msc/BiomeNameHelper.java // public class BiomeNameHelper { // // public static final int MAX_REG_ID = 39; // public static final List<Integer> VANILLA_MUT = Arrays.asList(129, 130, 131, 132, 133, 134, 140, 149, 151, 155, 156, 157, 158, 160, 162, 163, 164, 165, 166, 167); // // // // private static Map<String, BiomeGenBase> biomeMap; // private static Set<BiomeGenBase> biomeSet; // // private final static Map<String, String> nameSimplificationMap = new HashMap<String, String>(); // // static { // nameSimplificationMap.put("biomesoplenty.biomes", "BOP"); // nameSimplificationMap.put("extrabiomes.module.summa.biome", "EBXL"); // nameSimplificationMap.put("twilightforest.biomes", "TF"); // nameSimplificationMap.put("bwg4.biomes", "BWG4"); // nameSimplificationMap.put("highlands.biome", "HL"); // nameSimplificationMap.put("net.tropicraft.world.biomes", "TROP"); // nameSimplificationMap.put("xolova.blued00r.divinerpg.generation", "DRPG"); // } // // //TODO This better - recognize vanilla biomes some other way // public static boolean isVanilla(BiomeGenBase biome) { // return biome.biomeID <= MAX_REG_ID || VANILLA_MUT.contains(biome.biomeID); // } // // // public static String getBiomeName(BiomeGenBase biome) { // String name = ((isVanilla(biome)) ? "Vanilla" : biome.getClass().getName()) + '.' + biome.biomeName; // for (Entry<String,String> entry : nameSimplificationMap.entrySet()) // if (name.startsWith(entry.getKey())) // return entry.getValue() + '.' + biome.biomeName; // return name; // } // // public static BiomeGenBase getBiome(String biomeName) { // return biomeMap.get(biomeName); // } // // public static void initBiomeMap() { // if (biomeMap != null) // return; // // biomeMap = new HashMap<String, BiomeGenBase>(); // biomeSet = new HashSet<BiomeGenBase>(); // // for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { // if (biome != null) { // biomeMap.put(getBiomeName(biome), biome); // biomeSet.add(biome); // } // } // } // // public static Set<BiomeGenBase> getAllBiomes() { // return biomeSet; // } // // public static Set<String> getAllBiomeNames() { // return biomeMap.keySet(); // } // } // // Path: src/com/mcf/davidee/msc/Utils.java // public class Utils { // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static <E> Set<E> asSet(E... arr) { // Set<E> set = new HashSet<E>(); // for (E obj : arr) // set.add(obj); // return set; // } // // public static <E> List<E> asList(E... arr) { // List<E> list = new ArrayList<E>(); // for (E obj : arr) // list.add(obj); // return list; // } // // public static <T> void copyInto(List<T> source, List<T> dest) { // dest.clear(); // for (T obj : source) // dest.add(obj); // } // // public static void writeLine(BufferedWriter writer, String line) throws IOException { // writer.write(line); // writer.newLine(); // } // } // Path: src/com/mcf/davidee/msc/grouping/BiomeOperand.java import java.util.Set; import net.minecraft.world.biome.BiomeGenBase; import com.mcf.davidee.msc.BiomeNameHelper; import com.mcf.davidee.msc.Utils; package com.mcf.davidee.msc.grouping; public class BiomeOperand { public final BiomeOperator operator; private BiomeGroup group; private BiomeGenBase biome; private boolean isGroup, isAll; public BiomeOperand() { this.operator = BiomeOperator.ALL; isAll = true; } public BiomeOperand(BiomeOperator op, BiomeGroup group) { this.operator = op; this.group = group; isGroup = true; } public BiomeOperand(BiomeOperator op, BiomeGenBase biome) { this.operator = op; this.biome = biome; } public Set<BiomeGenBase> getBiomes() { if (isAll)
return BiomeNameHelper.getAllBiomes();
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/grouping/BiomeOperand.java
// Path: src/com/mcf/davidee/msc/BiomeNameHelper.java // public class BiomeNameHelper { // // public static final int MAX_REG_ID = 39; // public static final List<Integer> VANILLA_MUT = Arrays.asList(129, 130, 131, 132, 133, 134, 140, 149, 151, 155, 156, 157, 158, 160, 162, 163, 164, 165, 166, 167); // // // // private static Map<String, BiomeGenBase> biomeMap; // private static Set<BiomeGenBase> biomeSet; // // private final static Map<String, String> nameSimplificationMap = new HashMap<String, String>(); // // static { // nameSimplificationMap.put("biomesoplenty.biomes", "BOP"); // nameSimplificationMap.put("extrabiomes.module.summa.biome", "EBXL"); // nameSimplificationMap.put("twilightforest.biomes", "TF"); // nameSimplificationMap.put("bwg4.biomes", "BWG4"); // nameSimplificationMap.put("highlands.biome", "HL"); // nameSimplificationMap.put("net.tropicraft.world.biomes", "TROP"); // nameSimplificationMap.put("xolova.blued00r.divinerpg.generation", "DRPG"); // } // // //TODO This better - recognize vanilla biomes some other way // public static boolean isVanilla(BiomeGenBase biome) { // return biome.biomeID <= MAX_REG_ID || VANILLA_MUT.contains(biome.biomeID); // } // // // public static String getBiomeName(BiomeGenBase biome) { // String name = ((isVanilla(biome)) ? "Vanilla" : biome.getClass().getName()) + '.' + biome.biomeName; // for (Entry<String,String> entry : nameSimplificationMap.entrySet()) // if (name.startsWith(entry.getKey())) // return entry.getValue() + '.' + biome.biomeName; // return name; // } // // public static BiomeGenBase getBiome(String biomeName) { // return biomeMap.get(biomeName); // } // // public static void initBiomeMap() { // if (biomeMap != null) // return; // // biomeMap = new HashMap<String, BiomeGenBase>(); // biomeSet = new HashSet<BiomeGenBase>(); // // for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { // if (biome != null) { // biomeMap.put(getBiomeName(biome), biome); // biomeSet.add(biome); // } // } // } // // public static Set<BiomeGenBase> getAllBiomes() { // return biomeSet; // } // // public static Set<String> getAllBiomeNames() { // return biomeMap.keySet(); // } // } // // Path: src/com/mcf/davidee/msc/Utils.java // public class Utils { // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static <E> Set<E> asSet(E... arr) { // Set<E> set = new HashSet<E>(); // for (E obj : arr) // set.add(obj); // return set; // } // // public static <E> List<E> asList(E... arr) { // List<E> list = new ArrayList<E>(); // for (E obj : arr) // list.add(obj); // return list; // } // // public static <T> void copyInto(List<T> source, List<T> dest) { // dest.clear(); // for (T obj : source) // dest.add(obj); // } // // public static void writeLine(BufferedWriter writer, String line) throws IOException { // writer.write(line); // writer.newLine(); // } // }
import java.util.Set; import net.minecraft.world.biome.BiomeGenBase; import com.mcf.davidee.msc.BiomeNameHelper; import com.mcf.davidee.msc.Utils;
package com.mcf.davidee.msc.grouping; public class BiomeOperand { public final BiomeOperator operator; private BiomeGroup group; private BiomeGenBase biome; private boolean isGroup, isAll; public BiomeOperand() { this.operator = BiomeOperator.ALL; isAll = true; } public BiomeOperand(BiomeOperator op, BiomeGroup group) { this.operator = op; this.group = group; isGroup = true; } public BiomeOperand(BiomeOperator op, BiomeGenBase biome) { this.operator = op; this.biome = biome; } public Set<BiomeGenBase> getBiomes() { if (isAll) return BiomeNameHelper.getAllBiomes(); if (isGroup) return group.evaluate(); else
// Path: src/com/mcf/davidee/msc/BiomeNameHelper.java // public class BiomeNameHelper { // // public static final int MAX_REG_ID = 39; // public static final List<Integer> VANILLA_MUT = Arrays.asList(129, 130, 131, 132, 133, 134, 140, 149, 151, 155, 156, 157, 158, 160, 162, 163, 164, 165, 166, 167); // // // // private static Map<String, BiomeGenBase> biomeMap; // private static Set<BiomeGenBase> biomeSet; // // private final static Map<String, String> nameSimplificationMap = new HashMap<String, String>(); // // static { // nameSimplificationMap.put("biomesoplenty.biomes", "BOP"); // nameSimplificationMap.put("extrabiomes.module.summa.biome", "EBXL"); // nameSimplificationMap.put("twilightforest.biomes", "TF"); // nameSimplificationMap.put("bwg4.biomes", "BWG4"); // nameSimplificationMap.put("highlands.biome", "HL"); // nameSimplificationMap.put("net.tropicraft.world.biomes", "TROP"); // nameSimplificationMap.put("xolova.blued00r.divinerpg.generation", "DRPG"); // } // // //TODO This better - recognize vanilla biomes some other way // public static boolean isVanilla(BiomeGenBase biome) { // return biome.biomeID <= MAX_REG_ID || VANILLA_MUT.contains(biome.biomeID); // } // // // public static String getBiomeName(BiomeGenBase biome) { // String name = ((isVanilla(biome)) ? "Vanilla" : biome.getClass().getName()) + '.' + biome.biomeName; // for (Entry<String,String> entry : nameSimplificationMap.entrySet()) // if (name.startsWith(entry.getKey())) // return entry.getValue() + '.' + biome.biomeName; // return name; // } // // public static BiomeGenBase getBiome(String biomeName) { // return biomeMap.get(biomeName); // } // // public static void initBiomeMap() { // if (biomeMap != null) // return; // // biomeMap = new HashMap<String, BiomeGenBase>(); // biomeSet = new HashSet<BiomeGenBase>(); // // for (BiomeGenBase biome : BiomeGenBase.getBiomeGenArray()) { // if (biome != null) { // biomeMap.put(getBiomeName(biome), biome); // biomeSet.add(biome); // } // } // } // // public static Set<BiomeGenBase> getAllBiomes() { // return biomeSet; // } // // public static Set<String> getAllBiomeNames() { // return biomeMap.keySet(); // } // } // // Path: src/com/mcf/davidee/msc/Utils.java // public class Utils { // // public static int parseIntWithMinMax(String s, int min, int max) throws NumberFormatException { // int i = Integer.parseInt(s); // if (i < min) // return min; // if (i > max) // return max; // return i; // // } // // public static int parseIntDMinMax(String s, int _default, int min, int max) { // try { // return parseIntWithMinMax(s, min, max); // } catch (NumberFormatException e) { // return _default; // } // } // // public static <E> Set<E> asSet(E... arr) { // Set<E> set = new HashSet<E>(); // for (E obj : arr) // set.add(obj); // return set; // } // // public static <E> List<E> asList(E... arr) { // List<E> list = new ArrayList<E>(); // for (E obj : arr) // list.add(obj); // return list; // } // // public static <T> void copyInto(List<T> source, List<T> dest) { // dest.clear(); // for (T obj : source) // dest.add(obj); // } // // public static void writeLine(BufferedWriter writer, String line) throws IOException { // writer.write(line); // writer.newLine(); // } // } // Path: src/com/mcf/davidee/msc/grouping/BiomeOperand.java import java.util.Set; import net.minecraft.world.biome.BiomeGenBase; import com.mcf.davidee.msc.BiomeNameHelper; import com.mcf.davidee.msc.Utils; package com.mcf.davidee.msc.grouping; public class BiomeOperand { public final BiomeOperator operator; private BiomeGroup group; private BiomeGenBase biome; private boolean isGroup, isAll; public BiomeOperand() { this.operator = BiomeOperator.ALL; isAll = true; } public BiomeOperand(BiomeOperator op, BiomeGroup group) { this.operator = op; this.group = group; isGroup = true; } public BiomeOperand(BiomeOperator op, BiomeGenBase biome) { this.operator = op; this.biome = biome; } public Set<BiomeGenBase> getBiomes() { if (isAll) return BiomeNameHelper.getAllBiomes(); if (isGroup) return group.evaluate(); else
return Utils.asSet(biome);
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/CreatureTypePacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class CreatureTypePacket extends MSCPacket { public String mod; public String creatureType; public String[] mobs; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; creatureType = (String) data[1]; mobs = (String[]) data[2]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); writeString(creatureType, to); writeStringArray(mobs, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); creatureType = readString(from); mobs = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/CreatureTypePacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class CreatureTypePacket extends MSCPacket { public String mod; public String creatureType; public String[] mobs; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; creatureType = (String) data[1]; mobs = (String[]) data[2]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); writeString(creatureType, to); writeStringArray(mobs, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); creatureType = readString(from); mobs = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
DavidGoldman/MobSpawnControls2
src/com/mcf/davidee/msc/packet/GroupsPacket.java
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler;
package com.mcf.davidee.msc.packet; public class GroupsPacket extends MSCPacket { public String mod; public String[] groups; public String[] biomeNames; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; groups = (String[]) data[1]; biomeNames = (String[]) data[2]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); writeStringArray(groups, to); writeStringArray(biomeNames, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); groups = readStringArray(from); biomeNames = readStringArray(from); } @Override
// Path: src/com/mcf/davidee/msc/network/MSCPacketHandler.java // public abstract class MSCPacketHandler { // // public abstract void handleSettings(SettingsPacket pkt, EntityPlayer player); // public abstract void handleAccessDenied(EntityPlayer player); // public abstract void handleHandShake(EntityPlayer player); // public abstract void handleRequest(PacketType packetType, String mod, EntityPlayer player); // public abstract void handleModList(ModListPacket packet, EntityPlayer player); // public abstract void handleCreatureType(CreatureTypePacket packet, EntityPlayer player); // public abstract void handleGroups(GroupsPacket packet, EntityPlayer player); // public abstract void handleBiomeList(BiomeListPacket packet, EntityPlayer player); // public abstract void handleBiomeSetting(BiomeSettingPacket packet, EntityPlayer player); // public abstract void handleEntityList(EntityListPacket packet, EntityPlayer player); // public abstract void handleEntitySetting(EntitySettingPacket packet, EntityPlayer player); // public abstract void handleEvaluatedBiome(EvaluatedBiomePacket packet, EntityPlayer player); // public abstract void handleEvaluatedGroup(EvaluatedGroupPacket packet, EntityPlayer player); // public abstract void handleDebug(DebugPacket packet, EntityPlayer player); // // protected abstract boolean hasPermission(EntityPlayer player); // // public final void handlePacket(MSCPacket packet, EntityPlayer player) { // if (hasPermission(player)) // packet.execute(this, player); // else if (player instanceof EntityPlayerMP) // MobSpawnControls.DISPATCHER.sendTo(MSCPacket.getPacket(PacketType.ACCESS_DENIED), (EntityPlayerMP)player); // } // } // Path: src/com/mcf/davidee/msc/packet/GroupsPacket.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import com.mcf.davidee.msc.network.MSCPacketHandler; package com.mcf.davidee.msc.packet; public class GroupsPacket extends MSCPacket { public String mod; public String[] groups; public String[] biomeNames; @Override public MSCPacket readData(Object... data) { mod = (String) data[0]; groups = (String[]) data[1]; biomeNames = (String[]) data[2]; return this; } @Override public void encodeInto(ChannelHandlerContext ctx, ByteBuf to) throws IOException { writeString(mod, to); writeStringArray(groups, to); writeStringArray(biomeNames, to); } @Override public void decodeFrom(ChannelHandlerContext ctx, ByteBuf from) throws IOException { mod = readString(from); groups = readStringArray(from); biomeNames = readStringArray(from); } @Override
public void execute(MSCPacketHandler handler, EntityPlayer player) {
elibom/jogger
src/main/java/com/elibom/jogger/http/Response.java
// Path: src/main/java/com/elibom/jogger/asset/Asset.java // public class Asset { // // /** // * The input stream of the asset. // */ // private final InputStream inputStream; // // /** // * The name of the asset. // */ // private final String name; // // /** // * The content length of the asset. // */ // private final long length; // // /** // * The epoch timestamp when this asset was last modified // */ // private final long lastModified; // // /** // * The content type of the asset. // */ // private final String contentType; // // // public Asset(InputStream inputStream, String name, String contentType, long length) { // this(inputStream, name, contentType, length, 0); // } // // public Asset(InputStream inputStream, String name, String contentType, long length, long lastModified) { // this.inputStream = inputStream; // this.name = name; // this.contentType = contentType; // this.length = length; // this.lastModified = lastModified; // } // // public String getName() { // return name; // } // // public String getContentType() { // return contentType; // } // // public InputStream getInputStream() { // return inputStream; // } // // public long getLength() { // return length; // } // // public long getLastModified() { // return lastModified; // } // } // // Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // }
import java.util.Map; import com.elibom.jogger.asset.Asset; import com.elibom.jogger.template.TemplateException;
/** * Removes a cookie. * * @param cookie the name of the cookie to be removed. * * @return itself for method chaining. */ Response removeCookie(Cookie cookie); Map<String,Object> getAttributes(); Response setAttribute(String name, Object object); /** * Writes an HTML string into the response. * * @param output the output code to write in the response. * * @return itself for method chaining. */ Response write(String output); /** * Writes an InputStream into the response. * * @param asset the {@link Asset} to write in the response. * * @return itself for method chaining. */
// Path: src/main/java/com/elibom/jogger/asset/Asset.java // public class Asset { // // /** // * The input stream of the asset. // */ // private final InputStream inputStream; // // /** // * The name of the asset. // */ // private final String name; // // /** // * The content length of the asset. // */ // private final long length; // // /** // * The epoch timestamp when this asset was last modified // */ // private final long lastModified; // // /** // * The content type of the asset. // */ // private final String contentType; // // // public Asset(InputStream inputStream, String name, String contentType, long length) { // this(inputStream, name, contentType, length, 0); // } // // public Asset(InputStream inputStream, String name, String contentType, long length, long lastModified) { // this.inputStream = inputStream; // this.name = name; // this.contentType = contentType; // this.length = length; // this.lastModified = lastModified; // } // // public String getName() { // return name; // } // // public String getContentType() { // return contentType; // } // // public InputStream getInputStream() { // return inputStream; // } // // public long getLength() { // return length; // } // // public long getLastModified() { // return lastModified; // } // } // // Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/com/elibom/jogger/http/Response.java import java.util.Map; import com.elibom.jogger.asset.Asset; import com.elibom.jogger.template.TemplateException; /** * Removes a cookie. * * @param cookie the name of the cookie to be removed. * * @return itself for method chaining. */ Response removeCookie(Cookie cookie); Map<String,Object> getAttributes(); Response setAttribute(String name, Object object); /** * Writes an HTML string into the response. * * @param output the output code to write in the response. * * @return itself for method chaining. */ Response write(String output); /** * Writes an InputStream into the response. * * @param asset the {@link Asset} to write in the response. * * @return itself for method chaining. */
Response write(Asset asset);
elibom/jogger
src/main/java/com/elibom/jogger/http/Response.java
// Path: src/main/java/com/elibom/jogger/asset/Asset.java // public class Asset { // // /** // * The input stream of the asset. // */ // private final InputStream inputStream; // // /** // * The name of the asset. // */ // private final String name; // // /** // * The content length of the asset. // */ // private final long length; // // /** // * The epoch timestamp when this asset was last modified // */ // private final long lastModified; // // /** // * The content type of the asset. // */ // private final String contentType; // // // public Asset(InputStream inputStream, String name, String contentType, long length) { // this(inputStream, name, contentType, length, 0); // } // // public Asset(InputStream inputStream, String name, String contentType, long length, long lastModified) { // this.inputStream = inputStream; // this.name = name; // this.contentType = contentType; // this.length = length; // this.lastModified = lastModified; // } // // public String getName() { // return name; // } // // public String getContentType() { // return contentType; // } // // public InputStream getInputStream() { // return inputStream; // } // // public long getLength() { // return length; // } // // public long getLastModified() { // return lastModified; // } // } // // Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // }
import java.util.Map; import com.elibom.jogger.asset.Asset; import com.elibom.jogger.template.TemplateException;
Map<String,Object> getAttributes(); Response setAttribute(String name, Object object); /** * Writes an HTML string into the response. * * @param output the output code to write in the response. * * @return itself for method chaining. */ Response write(String output); /** * Writes an InputStream into the response. * * @param asset the {@link Asset} to write in the response. * * @return itself for method chaining. */ Response write(Asset asset); /** * Renders the specified template with no additional attributes (besides those already in the response) * * @param templateName the name of the template to be rendered. * * @return itself for method chaining. * @throws TemplateException */
// Path: src/main/java/com/elibom/jogger/asset/Asset.java // public class Asset { // // /** // * The input stream of the asset. // */ // private final InputStream inputStream; // // /** // * The name of the asset. // */ // private final String name; // // /** // * The content length of the asset. // */ // private final long length; // // /** // * The epoch timestamp when this asset was last modified // */ // private final long lastModified; // // /** // * The content type of the asset. // */ // private final String contentType; // // // public Asset(InputStream inputStream, String name, String contentType, long length) { // this(inputStream, name, contentType, length, 0); // } // // public Asset(InputStream inputStream, String name, String contentType, long length, long lastModified) { // this.inputStream = inputStream; // this.name = name; // this.contentType = contentType; // this.length = length; // this.lastModified = lastModified; // } // // public String getName() { // return name; // } // // public String getContentType() { // return contentType; // } // // public InputStream getInputStream() { // return inputStream; // } // // public long getLength() { // return length; // } // // public long getLastModified() { // return lastModified; // } // } // // Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/com/elibom/jogger/http/Response.java import java.util.Map; import com.elibom.jogger.asset.Asset; import com.elibom.jogger.template.TemplateException; Map<String,Object> getAttributes(); Response setAttribute(String name, Object object); /** * Writes an HTML string into the response. * * @param output the output code to write in the response. * * @return itself for method chaining. */ Response write(String output); /** * Writes an InputStream into the response. * * @param asset the {@link Asset} to write in the response. * * @return itself for method chaining. */ Response write(Asset asset); /** * Renders the specified template with no additional attributes (besides those already in the response) * * @param templateName the name of the template to be rendered. * * @return itself for method chaining. * @throws TemplateException */
Response render(String templateName) throws TemplateException;
elibom/jogger
src/main/java/com/elibom/jogger/http/Request.java
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // }
import java.io.InputStream; import java.util.Map; import com.elibom.jogger.middleware.router.Route;
package com.elibom.jogger.http; /** * Represents an HTTP Request. * * @author German Escobar */ public interface Request { String getHost(); /** * Returns the full URL including scheme, host, port, path and query string. * * @return a String object with the URL. */ String getUrl(); /** * Retrieves the path that was requested without the context path - if any. For example, if the URL is * "http://localhost:8080/app/users/1", the path would be "/users/1". * * @return a String object with the path of the request. */ String getPath(); /** * Retrieves the path variables. Path variables are wildcards that you can add to the url in the routes.config * file. * * @return a Map<String,String> object with the path variables. */ Map<String,String> getPathVariables(); /** * Retrieves the value of a path variable. * * @param name the name of the path variable. * * @return a String object. Null if it doesn't exists. */ String getPathVariable(String name); /** * Retrieves the raw query string part of the URL. * * @return a String object with the query string part of the URL. An empty String if there is no query string. */ String getQueryString(); /** * Retrieves the request parameters. * * @return a Map<String,String> object with the request parameters. */ Map<String,String> getParameters(); /** * Retrieves the value of a request parameter. * * @param name the name of the parameter * * @return a String object. Null if it doesn't exists. */ String getParameter(String name); /** * Returns the HTTP method of the request. * * @return a String object with the HTTP method. */ String getMethod(); String getRemoteAddress(); String getContentType(); int getPort(); boolean isSecure(); /** * Tells whether the request was done using an AJAX call or not. * * @return true if this was an AJAX call, false otherwise. */ boolean isAjax(); Map<String,Cookie> getCookies(); /** * Retrieves the {@link Cookie} with the specified name. * * @param name the name of the cookie to be retrieved. * * @return itself for method chaining. */ Cookie getCookie(String name); Map<String,String> getHeaders(); String getHeader(String name); /** * Retrieves the files from the request (if any). * * @return an array of {@link FileItem} objects or an empty array if no files. */ FileItem[] getFiles(); /** * Returns an object that will allow us to retrieve the body in multiple ways. * * @return a {@link BodyParser} implementation. */ BodyParser getBody();
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // } // Path: src/main/java/com/elibom/jogger/http/Request.java import java.io.InputStream; import java.util.Map; import com.elibom.jogger.middleware.router.Route; package com.elibom.jogger.http; /** * Represents an HTTP Request. * * @author German Escobar */ public interface Request { String getHost(); /** * Returns the full URL including scheme, host, port, path and query string. * * @return a String object with the URL. */ String getUrl(); /** * Retrieves the path that was requested without the context path - if any. For example, if the URL is * "http://localhost:8080/app/users/1", the path would be "/users/1". * * @return a String object with the path of the request. */ String getPath(); /** * Retrieves the path variables. Path variables are wildcards that you can add to the url in the routes.config * file. * * @return a Map<String,String> object with the path variables. */ Map<String,String> getPathVariables(); /** * Retrieves the value of a path variable. * * @param name the name of the path variable. * * @return a String object. Null if it doesn't exists. */ String getPathVariable(String name); /** * Retrieves the raw query string part of the URL. * * @return a String object with the query string part of the URL. An empty String if there is no query string. */ String getQueryString(); /** * Retrieves the request parameters. * * @return a Map<String,String> object with the request parameters. */ Map<String,String> getParameters(); /** * Retrieves the value of a request parameter. * * @param name the name of the parameter * * @return a String object. Null if it doesn't exists. */ String getParameter(String name); /** * Returns the HTTP method of the request. * * @return a String object with the HTTP method. */ String getMethod(); String getRemoteAddress(); String getContentType(); int getPort(); boolean isSecure(); /** * Tells whether the request was done using an AJAX call or not. * * @return true if this was an AJAX call, false otherwise. */ boolean isAjax(); Map<String,Cookie> getCookies(); /** * Retrieves the {@link Cookie} with the specified name. * * @param name the name of the cookie to be retrieved. * * @return itself for method chaining. */ Cookie getCookie(String name); Map<String,String> getHeaders(); String getHeader(String name); /** * Retrieves the files from the request (if any). * * @return an array of {@link FileItem} objects or an empty array if no files. */ FileItem[] getFiles(); /** * Returns an object that will allow us to retrieve the body in multiple ways. * * @return a {@link BodyParser} implementation. */ BodyParser getBody();
void setRoute(Route route);
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/ConflictExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/ConflictException.java // public class ConflictException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 409; // private static final String NAME = "Conflict"; // // public ConflictException() { // super(STATUS, NAME); // } // // public ConflictException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.ConflictException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class ConflictExceptionTest { @Test public void shouldCreateConflictException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/ConflictException.java // public class ConflictException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 409; // private static final String NAME = "Conflict"; // // public ConflictException() { // super(STATUS, NAME); // } // // public ConflictException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/ConflictExceptionTest.java import com.elibom.jogger.exception.ConflictException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class ConflictExceptionTest { @Test public void shouldCreateConflictException() throws Exception { try {
throw new ConflictException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/ConflictExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/ConflictException.java // public class ConflictException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 409; // private static final String NAME = "Conflict"; // // public ConflictException() { // super(STATUS, NAME); // } // // public ConflictException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.ConflictException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class ConflictExceptionTest { @Test public void shouldCreateConflictException() throws Exception { try { throw new ConflictException();
// Path: src/main/java/com/elibom/jogger/exception/ConflictException.java // public class ConflictException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 409; // private static final String NAME = "Conflict"; // // public ConflictException() { // super(STATUS, NAME); // } // // public ConflictException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/ConflictExceptionTest.java import com.elibom.jogger.exception.ConflictException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class ConflictExceptionTest { @Test public void shouldCreateConflictException() throws Exception { try { throw new ConflictException();
} catch (WebApplicationException e) {
elibom/jogger
src/main/java/com/elibom/jogger/http/FileItem.java
// Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // }
import java.io.File; import java.util.HashMap; import java.util.Map; import com.elibom.jogger.util.Preconditions;
package com.elibom.jogger.http; /** * Represents a file from an HTTP multipart/form-data request. * * @author German Escobar */ public class FileItem { /** * The name of the field to which this file was associated in the HTTP request */ private String name; /** * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) */ private String fileName; /** * The content type of the file taken from the Content-Type header of the part, null if not specified */ private String contentType; /** * The content length of the file taken from the Content-Length header of the part, -1 if not specified */ private long contentLength; /** * The file. */ private File file; /** * The headers of the file part */ private Map<String,String> headers; /** * Constructor. * * @param fieldName the name of the field that holds the file. * @param fileName the name of the file. * @param contentType * @param contentLength * @param file * @param headers */ public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) {
// Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // } // Path: src/main/java/com/elibom/jogger/http/FileItem.java import java.io.File; import java.util.HashMap; import java.util.Map; import com.elibom.jogger.util.Preconditions; package com.elibom.jogger.http; /** * Represents a file from an HTTP multipart/form-data request. * * @author German Escobar */ public class FileItem { /** * The name of the field to which this file was associated in the HTTP request */ private String name; /** * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) */ private String fileName; /** * The content type of the file taken from the Content-Type header of the part, null if not specified */ private String contentType; /** * The content length of the file taken from the Content-Length header of the part, -1 if not specified */ private long contentLength; /** * The file. */ private File file; /** * The headers of the file part */ private Map<String,String> headers; /** * Constructor. * * @param fieldName the name of the field that holds the file. * @param fileName the name of the file. * @param contentType * @param contentLength * @param file * @param headers */ public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) {
Preconditions.notNull(fieldName, "no fieldName provided.");
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/BadRequestExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/BadRequestException.java // public class BadRequestException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 400; // private static final String NAME = "Bad Request"; // // public BadRequestException() { // super(STATUS, NAME); // } // // public BadRequestException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.BadRequestException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class BadRequestExceptionTest { @Test public void shouldCreateBadRequestException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/BadRequestException.java // public class BadRequestException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 400; // private static final String NAME = "Bad Request"; // // public BadRequestException() { // super(STATUS, NAME); // } // // public BadRequestException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/BadRequestExceptionTest.java import com.elibom.jogger.exception.BadRequestException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class BadRequestExceptionTest { @Test public void shouldCreateBadRequestException() throws Exception { try {
throw new BadRequestException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/BadRequestExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/BadRequestException.java // public class BadRequestException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 400; // private static final String NAME = "Bad Request"; // // public BadRequestException() { // super(STATUS, NAME); // } // // public BadRequestException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.BadRequestException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class BadRequestExceptionTest { @Test public void shouldCreateBadRequestException() throws Exception { try { throw new BadRequestException();
// Path: src/main/java/com/elibom/jogger/exception/BadRequestException.java // public class BadRequestException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 400; // private static final String NAME = "Bad Request"; // // public BadRequestException() { // super(STATUS, NAME); // } // // public BadRequestException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/BadRequestExceptionTest.java import com.elibom.jogger.exception.BadRequestException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class BadRequestExceptionTest { @Test public void shouldCreateBadRequestException() throws Exception { try { throw new BadRequestException();
} catch (WebApplicationException e) {
elibom/jogger
src/main/java/com/elibom/jogger/middleware/router/loader/SpringControllerLoader.java
// Path: src/main/java/com/elibom/jogger/middleware/router/RoutesException.java // public class RoutesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public RoutesException(String message) { // super(message); // } // // public RoutesException(String message, Throwable cause) { // super(message, cause); // } // // public RoutesException(Throwable cause) { // super(cause); // } // // }
import com.elibom.jogger.middleware.router.RoutesException; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;
package com.elibom.jogger.middleware.router.loader; /** * A concrete implementation of {@link ControllerLoader} that loads controllers from a Spring context using an * <code>ApplicationContext</code>. Notice that this class implements <code>ApplicationContextAware</code>, so if you * configure this class as a Spring bean it will have access to that <code>ApplicatonContext</code>. * * @author German Escobar */ public class SpringControllerLoader implements ControllerLoader, ApplicationContextAware { private ApplicationContext applicationContext; @Override
// Path: src/main/java/com/elibom/jogger/middleware/router/RoutesException.java // public class RoutesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public RoutesException(String message) { // super(message); // } // // public RoutesException(String message, Throwable cause) { // super(message, cause); // } // // public RoutesException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/com/elibom/jogger/middleware/router/loader/SpringControllerLoader.java import com.elibom.jogger.middleware.router.RoutesException; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; package com.elibom.jogger.middleware.router.loader; /** * A concrete implementation of {@link ControllerLoader} that loads controllers from a Spring context using an * <code>ApplicationContext</code>. Notice that this class implements <code>ApplicationContextAware</code>, so if you * configure this class as a Spring bean it will have access to that <code>ApplicatonContext</code>. * * @author German Escobar */ public class SpringControllerLoader implements ControllerLoader, ApplicationContextAware { private ApplicationContext applicationContext; @Override
public Object load(String controllerName) throws RoutesException {
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/ForbiddenExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/ForbiddenException.java // public class ForbiddenException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 403; // private static final String NAME = "Forbidden"; // // public ForbiddenException() { // super(STATUS, NAME); // } // // public ForbiddenException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.ForbiddenException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class ForbiddenExceptionTest { @Test public void shouldCreateForbiddenException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/ForbiddenException.java // public class ForbiddenException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 403; // private static final String NAME = "Forbidden"; // // public ForbiddenException() { // super(STATUS, NAME); // } // // public ForbiddenException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/ForbiddenExceptionTest.java import com.elibom.jogger.exception.ForbiddenException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class ForbiddenExceptionTest { @Test public void shouldCreateForbiddenException() throws Exception { try {
throw new ForbiddenException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/ForbiddenExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/ForbiddenException.java // public class ForbiddenException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 403; // private static final String NAME = "Forbidden"; // // public ForbiddenException() { // super(STATUS, NAME); // } // // public ForbiddenException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.ForbiddenException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class ForbiddenExceptionTest { @Test public void shouldCreateForbiddenException() throws Exception { try { throw new ForbiddenException();
// Path: src/main/java/com/elibom/jogger/exception/ForbiddenException.java // public class ForbiddenException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 403; // private static final String NAME = "Forbidden"; // // public ForbiddenException() { // super(STATUS, NAME); // } // // public ForbiddenException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/ForbiddenExceptionTest.java import com.elibom.jogger.exception.ForbiddenException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class ForbiddenExceptionTest { @Test public void shouldCreateForbiddenException() throws Exception { try { throw new ForbiddenException();
} catch (WebApplicationException e) {
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/UnprocessableEntityExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/UnprocessableEntityException.java // public class UnprocessableEntityException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 422; // private static final String NAME = "Unprocessable Entity"; // // public UnprocessableEntityException() { // super(STATUS, NAME); // } // // public UnprocessableEntityException(String message) { // super(STATUS, NAME, message); // } // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.UnprocessableEntityException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class UnprocessableEntityExceptionTest { @Test public void shouldCreateUnprocessableEntityException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/UnprocessableEntityException.java // public class UnprocessableEntityException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 422; // private static final String NAME = "Unprocessable Entity"; // // public UnprocessableEntityException() { // super(STATUS, NAME); // } // // public UnprocessableEntityException(String message) { // super(STATUS, NAME, message); // } // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/UnprocessableEntityExceptionTest.java import com.elibom.jogger.exception.UnprocessableEntityException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class UnprocessableEntityExceptionTest { @Test public void shouldCreateUnprocessableEntityException() throws Exception { try {
throw new UnprocessableEntityException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/UnprocessableEntityExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/UnprocessableEntityException.java // public class UnprocessableEntityException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 422; // private static final String NAME = "Unprocessable Entity"; // // public UnprocessableEntityException() { // super(STATUS, NAME); // } // // public UnprocessableEntityException(String message) { // super(STATUS, NAME, message); // } // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.UnprocessableEntityException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class UnprocessableEntityExceptionTest { @Test public void shouldCreateUnprocessableEntityException() throws Exception { try { throw new UnprocessableEntityException();
// Path: src/main/java/com/elibom/jogger/exception/UnprocessableEntityException.java // public class UnprocessableEntityException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 422; // private static final String NAME = "Unprocessable Entity"; // // public UnprocessableEntityException() { // super(STATUS, NAME); // } // // public UnprocessableEntityException(String message) { // super(STATUS, NAME, message); // } // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/UnprocessableEntityExceptionTest.java import com.elibom.jogger.exception.UnprocessableEntityException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class UnprocessableEntityExceptionTest { @Test public void shouldCreateUnprocessableEntityException() throws Exception { try { throw new UnprocessableEntityException();
} catch (WebApplicationException e) {
elibom/jogger
src/test/java/com/elibom/jogger/template/FreemarkerTemplateEngineTest.java
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/FreemarkerTemplateEngine.java // public class FreemarkerTemplateEngine implements TemplateEngine { // // private Configuration freeMarker; // // public FreemarkerTemplateEngine() { // this.freeMarker = new Configuration(); // } // // public FreemarkerTemplateEngine(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // @Override // public void render(String template, Map<String, Object> root, Writer writer) throws TemplateException { // try { // Template tmpl = freeMarker.getTemplate(template); // tmpl.process(root, writer); // } catch (IOException e) { // throw new TemplateException(e); // } catch (freemarker.template.TemplateException e) { // throw new TemplateException(e.getMessage(), e); // } // } // // public Configuration getFreeMarker() { // return freeMarker; // } // // public void setFreeMarker(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // }
import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.FreemarkerTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.template; public class FreemarkerTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception {
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/FreemarkerTemplateEngine.java // public class FreemarkerTemplateEngine implements TemplateEngine { // // private Configuration freeMarker; // // public FreemarkerTemplateEngine() { // this.freeMarker = new Configuration(); // } // // public FreemarkerTemplateEngine(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // @Override // public void render(String template, Map<String, Object> root, Writer writer) throws TemplateException { // try { // Template tmpl = freeMarker.getTemplate(template); // tmpl.process(root, writer); // } catch (IOException e) { // throw new TemplateException(e); // } catch (freemarker.template.TemplateException e) { // throw new TemplateException(e.getMessage(), e); // } // } // // public Configuration getFreeMarker() { // return freeMarker; // } // // public void setFreeMarker(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // } // Path: src/test/java/com/elibom/jogger/template/FreemarkerTemplateEngineTest.java import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.FreemarkerTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.template; public class FreemarkerTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception {
FreemarkerTemplateEngine templateEngine = new FreemarkerTemplateEngine();
elibom/jogger
src/test/java/com/elibom/jogger/template/FreemarkerTemplateEngineTest.java
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/FreemarkerTemplateEngine.java // public class FreemarkerTemplateEngine implements TemplateEngine { // // private Configuration freeMarker; // // public FreemarkerTemplateEngine() { // this.freeMarker = new Configuration(); // } // // public FreemarkerTemplateEngine(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // @Override // public void render(String template, Map<String, Object> root, Writer writer) throws TemplateException { // try { // Template tmpl = freeMarker.getTemplate(template); // tmpl.process(root, writer); // } catch (IOException e) { // throw new TemplateException(e); // } catch (freemarker.template.TemplateException e) { // throw new TemplateException(e.getMessage(), e); // } // } // // public Configuration getFreeMarker() { // return freeMarker; // } // // public void setFreeMarker(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // }
import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.FreemarkerTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.template; public class FreemarkerTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception { FreemarkerTemplateEngine templateEngine = new FreemarkerTemplateEngine(); Map<String,Object> root = new HashMap<String,Object>(); root.put("title", "This is a test"); StringWriter writer = new StringWriter(); templateEngine.render("src/test/resources/templates/freemarker/template.ftl", root, writer); Assert.assertEquals(writer.toString(), "Title: This is a test"); }
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/FreemarkerTemplateEngine.java // public class FreemarkerTemplateEngine implements TemplateEngine { // // private Configuration freeMarker; // // public FreemarkerTemplateEngine() { // this.freeMarker = new Configuration(); // } // // public FreemarkerTemplateEngine(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // @Override // public void render(String template, Map<String, Object> root, Writer writer) throws TemplateException { // try { // Template tmpl = freeMarker.getTemplate(template); // tmpl.process(root, writer); // } catch (IOException e) { // throw new TemplateException(e); // } catch (freemarker.template.TemplateException e) { // throw new TemplateException(e.getMessage(), e); // } // } // // public Configuration getFreeMarker() { // return freeMarker; // } // // public void setFreeMarker(Configuration freeMarker) { // this.freeMarker = freeMarker; // } // // } // Path: src/test/java/com/elibom/jogger/template/FreemarkerTemplateEngineTest.java import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.FreemarkerTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.template; public class FreemarkerTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception { FreemarkerTemplateEngine templateEngine = new FreemarkerTemplateEngine(); Map<String,Object> root = new HashMap<String,Object>(); root.put("title", "This is a test"); StringWriter writer = new StringWriter(); templateEngine.render("src/test/resources/templates/freemarker/template.ftl", root, writer); Assert.assertEquals(writer.toString(), "Title: This is a test"); }
@Test(expectedExceptions=TemplateException.class)
elibom/jogger
src/test/java/com/elibom/jogger/router/FileSystemRoutesLoaderTest.java
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // } // // Path: src/main/java/com/elibom/jogger/middleware/router/loader/FileSystemRoutesLoader.java // public class FileSystemRoutesLoader extends AbstractFileRoutesLoader { // // private File file; // // public FileSystemRoutesLoader() { // } // // public FileSystemRoutesLoader(String filePath) { // this(new File(filePath)); // } // // public FileSystemRoutesLoader(File file) { // this.file = file; // } // // @Override // protected InputStream getInputStream() throws Exception { // return new FileInputStream(file); // } // // public void setFile(File file) { // this.file = file; // } // // public void setFilePath(String filePath) { // this.file = new File(filePath); // } // }
import java.text.ParseException; import java.util.List; import com.elibom.jogger.middleware.router.Route; import com.elibom.jogger.middleware.router.loader.FileSystemRoutesLoader; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.router; public class FileSystemRoutesLoaderTest { @Test public void shouldParseInput() throws Exception { // prepare
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // } // // Path: src/main/java/com/elibom/jogger/middleware/router/loader/FileSystemRoutesLoader.java // public class FileSystemRoutesLoader extends AbstractFileRoutesLoader { // // private File file; // // public FileSystemRoutesLoader() { // } // // public FileSystemRoutesLoader(String filePath) { // this(new File(filePath)); // } // // public FileSystemRoutesLoader(File file) { // this.file = file; // } // // @Override // protected InputStream getInputStream() throws Exception { // return new FileInputStream(file); // } // // public void setFile(File file) { // this.file = file; // } // // public void setFilePath(String filePath) { // this.file = new File(filePath); // } // } // Path: src/test/java/com/elibom/jogger/router/FileSystemRoutesLoaderTest.java import java.text.ParseException; import java.util.List; import com.elibom.jogger.middleware.router.Route; import com.elibom.jogger.middleware.router.loader.FileSystemRoutesLoader; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.router; public class FileSystemRoutesLoaderTest { @Test public void shouldParseInput() throws Exception { // prepare
FileSystemRoutesLoader routesLoader = new FileSystemRoutesLoader("src/test/resources/routes/routes-1.config");
elibom/jogger
src/test/java/com/elibom/jogger/router/FileSystemRoutesLoaderTest.java
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // } // // Path: src/main/java/com/elibom/jogger/middleware/router/loader/FileSystemRoutesLoader.java // public class FileSystemRoutesLoader extends AbstractFileRoutesLoader { // // private File file; // // public FileSystemRoutesLoader() { // } // // public FileSystemRoutesLoader(String filePath) { // this(new File(filePath)); // } // // public FileSystemRoutesLoader(File file) { // this.file = file; // } // // @Override // protected InputStream getInputStream() throws Exception { // return new FileInputStream(file); // } // // public void setFile(File file) { // this.file = file; // } // // public void setFilePath(String filePath) { // this.file = new File(filePath); // } // }
import java.text.ParseException; import java.util.List; import com.elibom.jogger.middleware.router.Route; import com.elibom.jogger.middleware.router.loader.FileSystemRoutesLoader; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.router; public class FileSystemRoutesLoaderTest { @Test public void shouldParseInput() throws Exception { // prepare FileSystemRoutesLoader routesLoader = new FileSystemRoutesLoader("src/test/resources/routes/routes-1.config"); routesLoader.setBasePackage("com.elibom.jogger"); // execute
// Path: src/main/java/com/elibom/jogger/middleware/router/Route.java // public class Route { // // public enum HttpMethod { // GET, // POST, // PUT, // DELETE, // OPTIONS, // HEAD, // PATCH // } // // private final HttpMethod httpMethod; // // private final String path; // // private final Object controller; // // private final Method action; // // public Route(HttpMethod httpMethod, String path, Object controller, Method action) { // Preconditions.notNull(httpMethod, "no httpMethod provided"); // Preconditions.notNull(path, "no path provided"); // Preconditions.notNull(controller, "no controller provided"); // Preconditions.notNull(action, "no action provided"); // // this.httpMethod = httpMethod; // this.path = Path.fixPath(path); // this.controller = controller; // this.action = action; // } // // public HttpMethod getHttpMethod() { // return httpMethod; // } // // public String getPath() { // return path; // } // // public Object getController() { // return controller; // } // // public Method getAction() { // return action; // } // // } // // Path: src/main/java/com/elibom/jogger/middleware/router/loader/FileSystemRoutesLoader.java // public class FileSystemRoutesLoader extends AbstractFileRoutesLoader { // // private File file; // // public FileSystemRoutesLoader() { // } // // public FileSystemRoutesLoader(String filePath) { // this(new File(filePath)); // } // // public FileSystemRoutesLoader(File file) { // this.file = file; // } // // @Override // protected InputStream getInputStream() throws Exception { // return new FileInputStream(file); // } // // public void setFile(File file) { // this.file = file; // } // // public void setFilePath(String filePath) { // this.file = new File(filePath); // } // } // Path: src/test/java/com/elibom/jogger/router/FileSystemRoutesLoaderTest.java import java.text.ParseException; import java.util.List; import com.elibom.jogger.middleware.router.Route; import com.elibom.jogger.middleware.router.loader.FileSystemRoutesLoader; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.router; public class FileSystemRoutesLoaderTest { @Test public void shouldParseInput() throws Exception { // prepare FileSystemRoutesLoader routesLoader = new FileSystemRoutesLoader("src/test/resources/routes/routes-1.config"); routesLoader.setBasePackage("com.elibom.jogger"); // execute
List<Route> routes = routesLoader.load();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/UnAuthorizedExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/UnAuthorizedException.java // public class UnAuthorizedException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 401; // private static final String NAME = "Unauthorized"; // // public UnAuthorizedException() { // super(STATUS, NAME); // } // // public UnAuthorizedException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.UnAuthorizedException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class UnAuthorizedExceptionTest { @Test public void shouldCreateUnAuthorizedException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/UnAuthorizedException.java // public class UnAuthorizedException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 401; // private static final String NAME = "Unauthorized"; // // public UnAuthorizedException() { // super(STATUS, NAME); // } // // public UnAuthorizedException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/UnAuthorizedExceptionTest.java import com.elibom.jogger.exception.UnAuthorizedException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class UnAuthorizedExceptionTest { @Test public void shouldCreateUnAuthorizedException() throws Exception { try {
throw new UnAuthorizedException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/UnAuthorizedExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/UnAuthorizedException.java // public class UnAuthorizedException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 401; // private static final String NAME = "Unauthorized"; // // public UnAuthorizedException() { // super(STATUS, NAME); // } // // public UnAuthorizedException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.UnAuthorizedException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class UnAuthorizedExceptionTest { @Test public void shouldCreateUnAuthorizedException() throws Exception { try { throw new UnAuthorizedException();
// Path: src/main/java/com/elibom/jogger/exception/UnAuthorizedException.java // public class UnAuthorizedException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 401; // private static final String NAME = "Unauthorized"; // // public UnAuthorizedException() { // super(STATUS, NAME); // } // // public UnAuthorizedException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/UnAuthorizedExceptionTest.java import com.elibom.jogger.exception.UnAuthorizedException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class UnAuthorizedExceptionTest { @Test public void shouldCreateUnAuthorizedException() throws Exception { try { throw new UnAuthorizedException();
} catch (WebApplicationException e) {
elibom/jogger
src/test/java/com/elibom/jogger/template/JadeTemplateEngineTest.java
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/JadeTemplateEngine.java // public class JadeTemplateEngine implements TemplateEngine { // // private JadeConfiguration jadeConfig; // // public JadeTemplateEngine() { // this(new JadeConfiguration()); // } // // public JadeTemplateEngine(JadeConfiguration jadeConfig) { // this.jadeConfig = jadeConfig; // } // // @Override // public void render(String templateName, Map<String, Object> root, Writer writer) throws TemplateException { // try { // JadeTemplate template = jadeConfig.getTemplate(templateName); // jadeConfig.renderTemplate(template, root, writer); // } catch(Exception e) { // throw new TemplateException(e); // } // } // // }
import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.JadeTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.template; public class JadeTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception {
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/JadeTemplateEngine.java // public class JadeTemplateEngine implements TemplateEngine { // // private JadeConfiguration jadeConfig; // // public JadeTemplateEngine() { // this(new JadeConfiguration()); // } // // public JadeTemplateEngine(JadeConfiguration jadeConfig) { // this.jadeConfig = jadeConfig; // } // // @Override // public void render(String templateName, Map<String, Object> root, Writer writer) throws TemplateException { // try { // JadeTemplate template = jadeConfig.getTemplate(templateName); // jadeConfig.renderTemplate(template, root, writer); // } catch(Exception e) { // throw new TemplateException(e); // } // } // // } // Path: src/test/java/com/elibom/jogger/template/JadeTemplateEngineTest.java import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.JadeTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.template; public class JadeTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception {
JadeTemplateEngine templateEngine = new JadeTemplateEngine();
elibom/jogger
src/test/java/com/elibom/jogger/template/JadeTemplateEngineTest.java
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/JadeTemplateEngine.java // public class JadeTemplateEngine implements TemplateEngine { // // private JadeConfiguration jadeConfig; // // public JadeTemplateEngine() { // this(new JadeConfiguration()); // } // // public JadeTemplateEngine(JadeConfiguration jadeConfig) { // this.jadeConfig = jadeConfig; // } // // @Override // public void render(String templateName, Map<String, Object> root, Writer writer) throws TemplateException { // try { // JadeTemplate template = jadeConfig.getTemplate(templateName); // jadeConfig.renderTemplate(template, root, writer); // } catch(Exception e) { // throw new TemplateException(e); // } // } // // }
import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.JadeTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.template; public class JadeTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception { JadeTemplateEngine templateEngine = new JadeTemplateEngine(); Map<String,Object> root = new HashMap<String,Object>(); root.put("title", "This is a test"); StringWriter writer = new StringWriter(); templateEngine.render("src/test/resources/templates/jade/template.jade", root, writer); Assert.assertEquals(writer.toString(), "<body>This is a test</body>"); }
// Path: src/main/java/com/elibom/jogger/template/TemplateException.java // public class TemplateException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public TemplateException() { // super(); // } // // public TemplateException(String message, Throwable cause) { // super(message, cause); // } // // public TemplateException(String message) { // super(message); // } // // public TemplateException(Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/elibom/jogger/template/JadeTemplateEngine.java // public class JadeTemplateEngine implements TemplateEngine { // // private JadeConfiguration jadeConfig; // // public JadeTemplateEngine() { // this(new JadeConfiguration()); // } // // public JadeTemplateEngine(JadeConfiguration jadeConfig) { // this.jadeConfig = jadeConfig; // } // // @Override // public void render(String templateName, Map<String, Object> root, Writer writer) throws TemplateException { // try { // JadeTemplate template = jadeConfig.getTemplate(templateName); // jadeConfig.renderTemplate(template, root, writer); // } catch(Exception e) { // throw new TemplateException(e); // } // } // // } // Path: src/test/java/com/elibom/jogger/template/JadeTemplateEngineTest.java import com.elibom.jogger.template.TemplateException; import com.elibom.jogger.template.JadeTemplateEngine; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.template; public class JadeTemplateEngineTest { @Test public void shouldRenderExistingTemplate() throws Exception { JadeTemplateEngine templateEngine = new JadeTemplateEngine(); Map<String,Object> root = new HashMap<String,Object>(); root.put("title", "This is a test"); StringWriter writer = new StringWriter(); templateEngine.render("src/test/resources/templates/jade/template.jade", root, writer); Assert.assertEquals(writer.toString(), "<body>This is a test</body>"); }
@Test(expectedExceptions=TemplateException.class)
elibom/jogger
src/main/java/com/elibom/jogger/middleware/router/loader/ClassPathControllerLoader.java
// Path: src/main/java/com/elibom/jogger/middleware/router/RoutesException.java // public class RoutesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public RoutesException(String message) { // super(message); // } // // public RoutesException(String message, Throwable cause) { // super(message, cause); // } // // public RoutesException(Throwable cause) { // super(cause); // } // // }
import com.elibom.jogger.middleware.router.RoutesException;
package com.elibom.jogger.middleware.router.loader; /** * A concrete implementation of {@link ControllerLoader} that loads controllers from the classpath using a * <code>ClassLoader</code>. You can specified a <code>basePackage</code> to avoid repeating the package in the routes * file. * * @author German Escobar */ public class ClassPathControllerLoader implements ControllerLoader { private String basePackage; private ClassLoader classLoader = ClassPathControllerLoader.class.getClassLoader(); /** * Constructor. Initializes the object with an empty <code>basePackage</code>. */ public ClassPathControllerLoader() { this(""); } /** * Constructor. Initializes the object with the specified <code>basePackage</code>. * @param basePackage */ public ClassPathControllerLoader(String basePackage) { this.basePackage = basePackage; if (this.basePackage != null && !"".equals(this.basePackage)) { if (!this.basePackage.endsWith(".")) { this.basePackage += "."; } } } @Override
// Path: src/main/java/com/elibom/jogger/middleware/router/RoutesException.java // public class RoutesException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public RoutesException(String message) { // super(message); // } // // public RoutesException(String message, Throwable cause) { // super(message, cause); // } // // public RoutesException(Throwable cause) { // super(cause); // } // // } // Path: src/main/java/com/elibom/jogger/middleware/router/loader/ClassPathControllerLoader.java import com.elibom.jogger.middleware.router.RoutesException; package com.elibom.jogger.middleware.router.loader; /** * A concrete implementation of {@link ControllerLoader} that loads controllers from the classpath using a * <code>ClassLoader</code>. You can specified a <code>basePackage</code> to avoid repeating the package in the routes * file. * * @author German Escobar */ public class ClassPathControllerLoader implements ControllerLoader { private String basePackage; private ClassLoader classLoader = ClassPathControllerLoader.class.getClassLoader(); /** * Constructor. Initializes the object with an empty <code>basePackage</code>. */ public ClassPathControllerLoader() { this(""); } /** * Constructor. Initializes the object with the specified <code>basePackage</code>. * @param basePackage */ public ClassPathControllerLoader(String basePackage) { this.basePackage = basePackage; if (this.basePackage != null && !"".equals(this.basePackage)) { if (!this.basePackage.endsWith(".")) { this.basePackage += "."; } } } @Override
public Object load(String controllerName) throws RoutesException {
elibom/jogger
src/main/java/com/elibom/jogger/http/servlet/multipart/PartHandler.java
// Path: src/main/java/com/elibom/jogger/http/FileItem.java // public class FileItem { // // /** // * The name of the field to which this file was associated in the HTTP request // */ // private String name; // // /** // * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) // */ // private String fileName; // // /** // * The content type of the file taken from the Content-Type header of the part, null if not specified // */ // private String contentType; // // /** // * The content length of the file taken from the Content-Length header of the part, -1 if not specified // */ // private long contentLength; // // /** // * The file. // */ // private File file; // // /** // * The headers of the file part // */ // private Map<String,String> headers; // // /** // * Constructor. // * // * @param fieldName the name of the field that holds the file. // * @param fileName the name of the file. // * @param contentType // * @param contentLength // * @param file // * @param headers // */ // public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) { // Preconditions.notNull(fieldName, "no fieldName provided."); // Preconditions.notNull(fileName, "no fileName provided."); // Preconditions.notNull(file, "no inputStream provided"); // // this.fileName = fileName; // this.contentType = contentType; // this.contentLength = contentLength; // this.file = file; // this.headers = headers; // if (headers == null) { // this.headers = new HashMap<String,String>(); // } // } // // public String getName() { // return name; // } // // public String getFileName() { // return fileName; // } // // public String getContentType() { // return contentType; // } // // public long getContentLength() { // return contentLength; // } // // public File getFile() { // return file; // } // // public Map<String, String> getHeaders() { // return headers; // } // // }
import com.elibom.jogger.http.FileItem;
package com.elibom.jogger.http.servlet.multipart; /** * Implementations of this interface are passed to the * {@link Multipart#parse(javax.servlet.http.HttpServletRequest, PartHandler)} method and handle the request parts. * * @author German Escobar */ public interface PartHandler { /** * Called when a form item part is found. * * @param name the name of the field to which this part is associated. * @param value the value of the field. */ void handleFormItem(String name, String value); /** * Called when a file item part (or subpart) is found. * * @param name the name of the field to which this part is associated. * @param fileItem the {@link FileItem} that holds the data and input stream of the file. */
// Path: src/main/java/com/elibom/jogger/http/FileItem.java // public class FileItem { // // /** // * The name of the field to which this file was associated in the HTTP request // */ // private String name; // // /** // * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) // */ // private String fileName; // // /** // * The content type of the file taken from the Content-Type header of the part, null if not specified // */ // private String contentType; // // /** // * The content length of the file taken from the Content-Length header of the part, -1 if not specified // */ // private long contentLength; // // /** // * The file. // */ // private File file; // // /** // * The headers of the file part // */ // private Map<String,String> headers; // // /** // * Constructor. // * // * @param fieldName the name of the field that holds the file. // * @param fileName the name of the file. // * @param contentType // * @param contentLength // * @param file // * @param headers // */ // public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) { // Preconditions.notNull(fieldName, "no fieldName provided."); // Preconditions.notNull(fileName, "no fileName provided."); // Preconditions.notNull(file, "no inputStream provided"); // // this.fileName = fileName; // this.contentType = contentType; // this.contentLength = contentLength; // this.file = file; // this.headers = headers; // if (headers == null) { // this.headers = new HashMap<String,String>(); // } // } // // public String getName() { // return name; // } // // public String getFileName() { // return fileName; // } // // public String getContentType() { // return contentType; // } // // public long getContentLength() { // return contentLength; // } // // public File getFile() { // return file; // } // // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/elibom/jogger/http/servlet/multipart/PartHandler.java import com.elibom.jogger.http.FileItem; package com.elibom.jogger.http.servlet.multipart; /** * Implementations of this interface are passed to the * {@link Multipart#parse(javax.servlet.http.HttpServletRequest, PartHandler)} method and handle the request parts. * * @author German Escobar */ public interface PartHandler { /** * Called when a form item part is found. * * @param name the name of the field to which this part is associated. * @param value the value of the field. */ void handleFormItem(String name, String value); /** * Called when a file item part (or subpart) is found. * * @param name the name of the field to which this part is associated. * @param fileItem the {@link FileItem} that holds the data and input stream of the file. */
void handleFileItem(String name, FileItem fileItem);
elibom/jogger
src/main/java/com/elibom/jogger/http/servlet/multipart/Multipart.java
// Path: src/main/java/com/elibom/jogger/http/FileItem.java // public class FileItem { // // /** // * The name of the field to which this file was associated in the HTTP request // */ // private String name; // // /** // * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) // */ // private String fileName; // // /** // * The content type of the file taken from the Content-Type header of the part, null if not specified // */ // private String contentType; // // /** // * The content length of the file taken from the Content-Length header of the part, -1 if not specified // */ // private long contentLength; // // /** // * The file. // */ // private File file; // // /** // * The headers of the file part // */ // private Map<String,String> headers; // // /** // * Constructor. // * // * @param fieldName the name of the field that holds the file. // * @param fileName the name of the file. // * @param contentType // * @param contentLength // * @param file // * @param headers // */ // public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) { // Preconditions.notNull(fieldName, "no fieldName provided."); // Preconditions.notNull(fileName, "no fileName provided."); // Preconditions.notNull(file, "no inputStream provided"); // // this.fileName = fileName; // this.contentType = contentType; // this.contentLength = contentLength; // this.file = file; // this.headers = headers; // if (headers == null) { // this.headers = new HashMap<String,String>(); // } // } // // public String getName() { // return name; // } // // public String getFileName() { // return fileName; // } // // public String getContentType() { // return contentType; // } // // public long getContentLength() { // return contentLength; // } // // public File getFile() { // return file; // } // // public Map<String, String> getHeaders() { // return headers; // } // // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.elibom.jogger.http.FileItem;
Map<String,String> headers = getHeadersMap(headersString); if (currentFieldName == null) { // we're parsing the outer multipart String fieldName = getFieldName( headers.get(CONTENT_DISPOSITION) ); if (fieldName != null) { String partContentType = headers.get(CONTENT_TYPE); if (partContentType != null && partContentType.toLowerCase().startsWith(MULTIPART_MIXED)) { // multiple files associated with this field name currentFieldName = fieldName; multipartReader.setBoundary( getBoundary(partContentType)); skipPreamble = true; continue; } String fileName = getFileName( headers.get(CONTENT_DISPOSITION) ); if (fileName == null) { // call the part handler String value = Streams.asString( multipartReader.newInputStream() ); partHandler.handleFormItem(fieldName, value); } else { // create the temp file File tempFile = createTempFile(multipartReader); // call the part handler
// Path: src/main/java/com/elibom/jogger/http/FileItem.java // public class FileItem { // // /** // * The name of the field to which this file was associated in the HTTP request // */ // private String name; // // /** // * The name of the file taken from the HTTP part (in the filename attribute of the Content-Disposition header) // */ // private String fileName; // // /** // * The content type of the file taken from the Content-Type header of the part, null if not specified // */ // private String contentType; // // /** // * The content length of the file taken from the Content-Length header of the part, -1 if not specified // */ // private long contentLength; // // /** // * The file. // */ // private File file; // // /** // * The headers of the file part // */ // private Map<String,String> headers; // // /** // * Constructor. // * // * @param fieldName the name of the field that holds the file. // * @param fileName the name of the file. // * @param contentType // * @param contentLength // * @param file // * @param headers // */ // public FileItem(String fieldName, String fileName, String contentType, long contentLength, File file, Map<String,String> headers) { // Preconditions.notNull(fieldName, "no fieldName provided."); // Preconditions.notNull(fileName, "no fileName provided."); // Preconditions.notNull(file, "no inputStream provided"); // // this.fileName = fileName; // this.contentType = contentType; // this.contentLength = contentLength; // this.file = file; // this.headers = headers; // if (headers == null) { // this.headers = new HashMap<String,String>(); // } // } // // public String getName() { // return name; // } // // public String getFileName() { // return fileName; // } // // public String getContentType() { // return contentType; // } // // public long getContentLength() { // return contentLength; // } // // public File getFile() { // return file; // } // // public Map<String, String> getHeaders() { // return headers; // } // // } // Path: src/main/java/com/elibom/jogger/http/servlet/multipart/Multipart.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.elibom.jogger.http.FileItem; Map<String,String> headers = getHeadersMap(headersString); if (currentFieldName == null) { // we're parsing the outer multipart String fieldName = getFieldName( headers.get(CONTENT_DISPOSITION) ); if (fieldName != null) { String partContentType = headers.get(CONTENT_TYPE); if (partContentType != null && partContentType.toLowerCase().startsWith(MULTIPART_MIXED)) { // multiple files associated with this field name currentFieldName = fieldName; multipartReader.setBoundary( getBoundary(partContentType)); skipPreamble = true; continue; } String fileName = getFileName( headers.get(CONTENT_DISPOSITION) ); if (fileName == null) { // call the part handler String value = Streams.asString( multipartReader.newInputStream() ); partHandler.handleFormItem(fieldName, value); } else { // create the temp file File tempFile = createTempFile(multipartReader); // call the part handler
FileItem fileItem = new FileItem(fieldName, fileName, partContentType, tempFile.length(), tempFile, headers);
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/NotFoundExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/NotFoundException.java // public class NotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 404; // private static final String NAME = "Not Found"; // // public NotFoundException() { // super(STATUS, NAME); // } // // public NotFoundException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.NotFoundException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class NotFoundExceptionTest { @Test public void shouldCreateNotFoundException() throws Exception { try {
// Path: src/main/java/com/elibom/jogger/exception/NotFoundException.java // public class NotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 404; // private static final String NAME = "Not Found"; // // public NotFoundException() { // super(STATUS, NAME); // } // // public NotFoundException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/NotFoundExceptionTest.java import com.elibom.jogger.exception.NotFoundException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class NotFoundExceptionTest { @Test public void shouldCreateNotFoundException() throws Exception { try {
throw new NotFoundException();
elibom/jogger
src/test/java/com/elibom/jogger/exceptions/NotFoundExceptionTest.java
// Path: src/main/java/com/elibom/jogger/exception/NotFoundException.java // public class NotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 404; // private static final String NAME = "Not Found"; // // public NotFoundException() { // super(STATUS, NAME); // } // // public NotFoundException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // }
import com.elibom.jogger.exception.NotFoundException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test;
package com.elibom.jogger.exceptions; public class NotFoundExceptionTest { @Test public void shouldCreateNotFoundException() throws Exception { try { throw new NotFoundException();
// Path: src/main/java/com/elibom/jogger/exception/NotFoundException.java // public class NotFoundException extends WebApplicationException { // // private static final long serialVersionUID = 1L; // // private static final int STATUS = 404; // private static final String NAME = "Not Found"; // // public NotFoundException() { // super(STATUS, NAME); // } // // public NotFoundException(String message) { // super(STATUS, NAME, message); // } // // } // // Path: src/main/java/com/elibom/jogger/exception/WebApplicationException.java // public abstract class WebApplicationException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // protected int status; // // protected String name; // // public WebApplicationException(int status, String name) { // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message) { // super(message); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, Throwable cause) { // super(cause); // this.status = status; // this.name = name; // } // // public WebApplicationException(int status, String name, String message, Throwable cause) { // super(message, cause); // this.status = status; // this.name = name; // } // // public static long getSerialversionuid() { // return serialVersionUID; // } // // public int getStatus() { // return status; // } // // public String getName() { // return name; // } // // } // Path: src/test/java/com/elibom/jogger/exceptions/NotFoundExceptionTest.java import com.elibom.jogger.exception.NotFoundException; import com.elibom.jogger.exception.WebApplicationException; import org.testng.Assert; import org.testng.annotations.Test; package com.elibom.jogger.exceptions; public class NotFoundExceptionTest { @Test public void shouldCreateNotFoundException() throws Exception { try { throw new NotFoundException();
} catch (WebApplicationException e) {
elibom/jogger
src/main/java/com/elibom/jogger/asset/FileAssetLoader.java
// Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import com.elibom.jogger.util.Preconditions;
package com.elibom.jogger.asset; /** * An {@link AssetLoader} implementation that uses the file system to retrieve assets. * * @author German Escobar */ public class FileAssetLoader implements AssetLoader { private static final String DEFAULT_BASE_DIRECTORY = "assets"; private File parent; /** * Constructor. Initializes the object with the default base directory. */ public FileAssetLoader() { this(DEFAULT_BASE_DIRECTORY); } /** * Constructor. Initializes the object with the specified base <code>directory</code>. * * @param directory */ public FileAssetLoader(String directory) {
// Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // } // Path: src/main/java/com/elibom/jogger/asset/FileAssetLoader.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import org.eclipse.jetty.http.MimeTypes; import org.eclipse.jetty.io.Buffer; import com.elibom.jogger.util.Preconditions; package com.elibom.jogger.asset; /** * An {@link AssetLoader} implementation that uses the file system to retrieve assets. * * @author German Escobar */ public class FileAssetLoader implements AssetLoader { private static final String DEFAULT_BASE_DIRECTORY = "assets"; private File parent; /** * Constructor. Initializes the object with the default base directory. */ public FileAssetLoader() { this(DEFAULT_BASE_DIRECTORY); } /** * Constructor. Initializes the object with the specified base <code>directory</code>. * * @param directory */ public FileAssetLoader(String directory) {
Preconditions.notEmpty(directory, "no directory provided");
elibom/jogger
src/main/java/com/elibom/jogger/middleware/router/Route.java
// Path: src/main/java/com/elibom/jogger/http/Path.java // public class Path { // // /** // * The regular expression to find holders in a path (e.g. {userId}). // */ // public static final String VAR_REGEXP = "\\{([^{}]+)\\}"; // // public static final String VAR_REPLACE = "([^#/?]+)"; // // public static String fixPath(String path) { // if (path == null) { // return "/"; // } // // if (!path.startsWith("/")) { // path = "/" + path; // } // // if (path.length() > 1 && path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // // return path; // } // // } // // Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // }
import java.lang.reflect.Method; import com.elibom.jogger.http.Path; import com.elibom.jogger.util.Preconditions;
package com.elibom.jogger.middleware.router; /** * Holds the information of a route. * * @author German Escobar */ public class Route { public enum HttpMethod { GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH } private final HttpMethod httpMethod; private final String path; private final Object controller; private final Method action; public Route(HttpMethod httpMethod, String path, Object controller, Method action) {
// Path: src/main/java/com/elibom/jogger/http/Path.java // public class Path { // // /** // * The regular expression to find holders in a path (e.g. {userId}). // */ // public static final String VAR_REGEXP = "\\{([^{}]+)\\}"; // // public static final String VAR_REPLACE = "([^#/?]+)"; // // public static String fixPath(String path) { // if (path == null) { // return "/"; // } // // if (!path.startsWith("/")) { // path = "/" + path; // } // // if (path.length() > 1 && path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // // return path; // } // // } // // Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // } // Path: src/main/java/com/elibom/jogger/middleware/router/Route.java import java.lang.reflect.Method; import com.elibom.jogger.http.Path; import com.elibom.jogger.util.Preconditions; package com.elibom.jogger.middleware.router; /** * Holds the information of a route. * * @author German Escobar */ public class Route { public enum HttpMethod { GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH } private final HttpMethod httpMethod; private final String path; private final Object controller; private final Method action; public Route(HttpMethod httpMethod, String path, Object controller, Method action) {
Preconditions.notNull(httpMethod, "no httpMethod provided");
elibom/jogger
src/main/java/com/elibom/jogger/middleware/router/Route.java
// Path: src/main/java/com/elibom/jogger/http/Path.java // public class Path { // // /** // * The regular expression to find holders in a path (e.g. {userId}). // */ // public static final String VAR_REGEXP = "\\{([^{}]+)\\}"; // // public static final String VAR_REPLACE = "([^#/?]+)"; // // public static String fixPath(String path) { // if (path == null) { // return "/"; // } // // if (!path.startsWith("/")) { // path = "/" + path; // } // // if (path.length() > 1 && path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // // return path; // } // // } // // Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // }
import java.lang.reflect.Method; import com.elibom.jogger.http.Path; import com.elibom.jogger.util.Preconditions;
package com.elibom.jogger.middleware.router; /** * Holds the information of a route. * * @author German Escobar */ public class Route { public enum HttpMethod { GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH } private final HttpMethod httpMethod; private final String path; private final Object controller; private final Method action; public Route(HttpMethod httpMethod, String path, Object controller, Method action) { Preconditions.notNull(httpMethod, "no httpMethod provided"); Preconditions.notNull(path, "no path provided"); Preconditions.notNull(controller, "no controller provided"); Preconditions.notNull(action, "no action provided"); this.httpMethod = httpMethod;
// Path: src/main/java/com/elibom/jogger/http/Path.java // public class Path { // // /** // * The regular expression to find holders in a path (e.g. {userId}). // */ // public static final String VAR_REGEXP = "\\{([^{}]+)\\}"; // // public static final String VAR_REPLACE = "([^#/?]+)"; // // public static String fixPath(String path) { // if (path == null) { // return "/"; // } // // if (!path.startsWith("/")) { // path = "/" + path; // } // // if (path.length() > 1 && path.endsWith("/")) { // path = path.substring(0, path.length() - 1); // } // // return path; // } // // } // // Path: src/main/java/com/elibom/jogger/util/Preconditions.java // public final class Preconditions { // // /** // * Hide constructor. // */ // private Preconditions() {} // // /** // * Checks that an object is not null. // * // * @param object the object to be tested // * @param message the message for the exception in case the object is null. // * // * @throws IllegalArgumentException if the object is null. // */ // public static void notNull(Object object, String message) throws IllegalArgumentException { // if (object == null) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // // /** // * Checks that a string is not null or empty. // * // * @param value the string to be tested. // * @param message the message for the exception in case the string is empty. // * // * @throws IllegalArgumentException if the string is empty. // */ // public static void notEmpty(String value, String message) throws IllegalArgumentException { // if (value == null || "".equals(value.trim())) { // throw new IllegalArgumentException("A precondition failed: " + message); // } // } // } // Path: src/main/java/com/elibom/jogger/middleware/router/Route.java import java.lang.reflect.Method; import com.elibom.jogger.http.Path; import com.elibom.jogger.util.Preconditions; package com.elibom.jogger.middleware.router; /** * Holds the information of a route. * * @author German Escobar */ public class Route { public enum HttpMethod { GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH } private final HttpMethod httpMethod; private final String path; private final Object controller; private final Method action; public Route(HttpMethod httpMethod, String path, Object controller, Method action) { Preconditions.notNull(httpMethod, "no httpMethod provided"); Preconditions.notNull(path, "no path provided"); Preconditions.notNull(controller, "no controller provided"); Preconditions.notNull(action, "no action provided"); this.httpMethod = httpMethod;
this.path = Path.fixPath(path);
houkx/nettythrift
client.json/src/io/client/thrift/ClientInterfaceFactory.java
// Path: client.json/src/io/client/thrift/Json.java // public static class Strategy { // int excludeModifiers = Modifier.TRANSIENT | Modifier.STATIC; // // /** // * 返回字段名,如果返回null,则表示忽略这个字段 // * // * @param field // * @return // */ // public String fieldName(Field field) { // if (excludeClass(field.getType(), true)) // return null; // return field.getName(); // } // // public Field field(Class<?> cls, String fieldName) throws NoSuchFieldException, SecurityException { // if (excludeClass(cls, false)) // return null; // Field f = cls.getDeclaredField(fieldName); // if ((f.getModifiers() & excludeModifiers) != 0) { // return null; // } // f.setAccessible(true); // return f; // } // // /** // * 是否忽略指定class // * // * @param clazz // * @param serialize // * - 是否在序列化过程中(Object to JSON) // * @return // */ // public boolean excludeClass(Class<?> clazz, boolean serialize) { // return false; // } // // public void excludeFieldsWithModifiers(int... modifiers) { // excludeModifiers = 0; // for (int modifier : modifiers) { // excludeModifiers |= modifier; // } // } // // public void publicFieldsOnly() { // excludeFieldsWithModifiers(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.STATIC, Modifier.TRANSIENT); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.net.ProtocolException; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.net.SocketFactory; import org.json.JSONArray; import org.json.JSONObject; import io.client.thrift.Json.Strategy; import io.client.thrift.annotaion.Index;
/** * */ package io.client.thrift; /** * 使用 HTTP + JSON 协议 * <p> * 只有这一个文件,适合轻量级通信,如单一接口。由于依赖的 org.json 包 在 android.jar中 已存在,代码整体尺寸很小。 * * @author HouKangxi * */ public class ClientInterfaceFactory { private ClientInterfaceFactory() { } private static ConcurrentHashMap<Long, Object> ifaceCache = new ConcurrentHashMap<Long, Object>(); /** * 获得与服务端通信的接口对象 * <p> * 调用者可以实现自定义的 SocketFactory来内部配置Socket参数(如超时时间,SSL等),也可以通过返回包装的Socket来实现连接池<br/> * SocketFactory::createSocket(String host,int ip)//NOTE: 实际传入createSocket(methodName,flag) * * @param ifaceClass * - 接口class * @param factory * - 套接字工厂类, 注意:需要实现 createSocket() 方法,需要实现hashCode()方法来区分factory * @return 接口对象 */ @SuppressWarnings("unchecked") public static <INTERFACE> INTERFACE getClientInterface(Class<INTERFACE> ifaceClass, SocketFactory factory) { long part1 = ifaceClass.getName().hashCode(); final Long KEY = (part1 << 32) | factory.hashCode(); INTERFACE iface = (INTERFACE) ifaceCache.get(KEY); if (iface == null) { iface = (INTERFACE) Proxy.newProxyInstance(ifaceClass.getClassLoader(), new Class[] { ifaceClass }, new Handler(factory)); ifaceCache.putIfAbsent(KEY, iface); } return iface; } @SuppressWarnings("unchecked") public static <INTERFACE> INTERFACE getClientInterface(Class<INTERFACE> ifaceClass, String host) { long part1 = ifaceClass.getName().hashCode(); final Long KEY = (part1 << 32) | host.hashCode(); INTERFACE iface = (INTERFACE) ifaceCache.get(KEY); if (iface == null) { iface = (INTERFACE) Proxy.newProxyInstance(ifaceClass.getClassLoader(), new Class[] { ifaceClass }, new Handler(host)); ifaceCache.putIfAbsent(KEY, iface); } return iface; } private static ConcurrentHashMap<Class<?>, Map<Object, Field>> fieldCache = new ConcurrentHashMap<Class<?>, Map<Object, Field>>();
// Path: client.json/src/io/client/thrift/Json.java // public static class Strategy { // int excludeModifiers = Modifier.TRANSIENT | Modifier.STATIC; // // /** // * 返回字段名,如果返回null,则表示忽略这个字段 // * // * @param field // * @return // */ // public String fieldName(Field field) { // if (excludeClass(field.getType(), true)) // return null; // return field.getName(); // } // // public Field field(Class<?> cls, String fieldName) throws NoSuchFieldException, SecurityException { // if (excludeClass(cls, false)) // return null; // Field f = cls.getDeclaredField(fieldName); // if ((f.getModifiers() & excludeModifiers) != 0) { // return null; // } // f.setAccessible(true); // return f; // } // // /** // * 是否忽略指定class // * // * @param clazz // * @param serialize // * - 是否在序列化过程中(Object to JSON) // * @return // */ // public boolean excludeClass(Class<?> clazz, boolean serialize) { // return false; // } // // public void excludeFieldsWithModifiers(int... modifiers) { // excludeModifiers = 0; // for (int modifier : modifiers) { // excludeModifiers |= modifier; // } // } // // public void publicFieldsOnly() { // excludeFieldsWithModifiers(Modifier.PRIVATE, Modifier.PROTECTED, Modifier.STATIC, Modifier.TRANSIENT); // } // } // Path: client.json/src/io/client/thrift/ClientInterfaceFactory.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.net.ProtocolException; import java.net.Socket; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.net.SocketFactory; import org.json.JSONArray; import org.json.JSONObject; import io.client.thrift.Json.Strategy; import io.client.thrift.annotaion.Index; /** * */ package io.client.thrift; /** * 使用 HTTP + JSON 协议 * <p> * 只有这一个文件,适合轻量级通信,如单一接口。由于依赖的 org.json 包 在 android.jar中 已存在,代码整体尺寸很小。 * * @author HouKangxi * */ public class ClientInterfaceFactory { private ClientInterfaceFactory() { } private static ConcurrentHashMap<Long, Object> ifaceCache = new ConcurrentHashMap<Long, Object>(); /** * 获得与服务端通信的接口对象 * <p> * 调用者可以实现自定义的 SocketFactory来内部配置Socket参数(如超时时间,SSL等),也可以通过返回包装的Socket来实现连接池<br/> * SocketFactory::createSocket(String host,int ip)//NOTE: 实际传入createSocket(methodName,flag) * * @param ifaceClass * - 接口class * @param factory * - 套接字工厂类, 注意:需要实现 createSocket() 方法,需要实现hashCode()方法来区分factory * @return 接口对象 */ @SuppressWarnings("unchecked") public static <INTERFACE> INTERFACE getClientInterface(Class<INTERFACE> ifaceClass, SocketFactory factory) { long part1 = ifaceClass.getName().hashCode(); final Long KEY = (part1 << 32) | factory.hashCode(); INTERFACE iface = (INTERFACE) ifaceCache.get(KEY); if (iface == null) { iface = (INTERFACE) Proxy.newProxyInstance(ifaceClass.getClassLoader(), new Class[] { ifaceClass }, new Handler(factory)); ifaceCache.putIfAbsent(KEY, iface); } return iface; } @SuppressWarnings("unchecked") public static <INTERFACE> INTERFACE getClientInterface(Class<INTERFACE> ifaceClass, String host) { long part1 = ifaceClass.getName().hashCode(); final Long KEY = (part1 << 32) | host.hashCode(); INTERFACE iface = (INTERFACE) ifaceCache.get(KEY); if (iface == null) { iface = (INTERFACE) Proxy.newProxyInstance(ifaceClass.getClassLoader(), new Class[] { ifaceClass }, new Handler(host)); ifaceCache.putIfAbsent(KEY, iface); } return iface; } private static ConcurrentHashMap<Class<?>, Map<Object, Field>> fieldCache = new ConcurrentHashMap<Class<?>, Map<Object, Field>>();
private static class Handler extends Json.Strategy implements InvocationHandler {
houkx/nettythrift
io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDefBuilderBase.java
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/DefaultProtocolFactorySelectorFactory.java // public class DefaultProtocolFactorySelectorFactory implements ProtocolFactorySelectorFactory { // // /* // * (non-Javadoc) // * // * @see io.netty5thrift.protocol.ProtocolFactorySelectorFactory# // * createProtocolFactorySelector(java.lang.Class) // */ // @Override // public ProtocolFactorySelector createProtocolFactorySelector(Class<?> interfaceClass) { // return new ProtocolFactorySelector(interfaceClass); // } // // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.DefaultExecutorServiceFactory; import io.nettythrift.protocol.DefaultProtocolFactorySelectorFactory; import io.nettythrift.protocol.ProtocolFactorySelectorFactory;
/* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Builder for the Thrift Server descriptor. Example : <code> * new ThriftServerDefBuilder() * .listen(config.getServerPort()) * .limitFrameSizeTo(config.getMaxFrameSize()) * .withProcessor(new FacebookService.Processor(new MyFacebookBase())) * .using(Executors.newFixedThreadPool(5)) * .build(); * <p/> * <p/> * You can then pass ThriftServerDef to guice via a multibinder. * <p/> * </code> */ public abstract class ThriftServerDefBuilderBase<T extends ThriftServerDefBuilderBase<T>> { private static final AtomicInteger ID = new AtomicInteger(1); private String name = "netty5thrift-" + ID.getAndIncrement(); private int serverPort = 8081; private int maxFrameSize = MAX_FRAME_SIZE; private int maxConnections; private int queuedResponseLimit = 16; @SuppressWarnings("rawtypes") private TBaseProcessor processor; private NettyProcessorFactory nettyProcessorFactory;// hasDefault private ChannelHandler contextHandlerInstaller;// hasDefault private ExecutorService executor;// hasDefault private long clientIdleTimeout = 15000;// hasDefault
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/DefaultProtocolFactorySelectorFactory.java // public class DefaultProtocolFactorySelectorFactory implements ProtocolFactorySelectorFactory { // // /* // * (non-Javadoc) // * // * @see io.netty5thrift.protocol.ProtocolFactorySelectorFactory# // * createProtocolFactorySelector(java.lang.Class) // */ // @Override // public ProtocolFactorySelector createProtocolFactorySelector(Class<?> interfaceClass) { // return new ProtocolFactorySelector(interfaceClass); // } // // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // } // Path: io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDefBuilderBase.java import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.DefaultExecutorServiceFactory; import io.nettythrift.protocol.DefaultProtocolFactorySelectorFactory; import io.nettythrift.protocol.ProtocolFactorySelectorFactory; /* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Builder for the Thrift Server descriptor. Example : <code> * new ThriftServerDefBuilder() * .listen(config.getServerPort()) * .limitFrameSizeTo(config.getMaxFrameSize()) * .withProcessor(new FacebookService.Processor(new MyFacebookBase())) * .using(Executors.newFixedThreadPool(5)) * .build(); * <p/> * <p/> * You can then pass ThriftServerDef to guice via a multibinder. * <p/> * </code> */ public abstract class ThriftServerDefBuilderBase<T extends ThriftServerDefBuilderBase<T>> { private static final AtomicInteger ID = new AtomicInteger(1); private String name = "netty5thrift-" + ID.getAndIncrement(); private int serverPort = 8081; private int maxFrameSize = MAX_FRAME_SIZE; private int maxConnections; private int queuedResponseLimit = 16; @SuppressWarnings("rawtypes") private TBaseProcessor processor; private NettyProcessorFactory nettyProcessorFactory;// hasDefault private ChannelHandler contextHandlerInstaller;// hasDefault private ExecutorService executor;// hasDefault private long clientIdleTimeout = 15000;// hasDefault
private ProtocolFactorySelectorFactory protocolFactorySelectorFactory;// hasDefault
houkx/nettythrift
io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDefBuilderBase.java
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/DefaultProtocolFactorySelectorFactory.java // public class DefaultProtocolFactorySelectorFactory implements ProtocolFactorySelectorFactory { // // /* // * (non-Javadoc) // * // * @see io.netty5thrift.protocol.ProtocolFactorySelectorFactory# // * createProtocolFactorySelector(java.lang.Class) // */ // @Override // public ProtocolFactorySelector createProtocolFactorySelector(Class<?> interfaceClass) { // return new ProtocolFactorySelector(interfaceClass); // } // // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // }
import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.DefaultExecutorServiceFactory; import io.nettythrift.protocol.DefaultProtocolFactorySelectorFactory; import io.nettythrift.protocol.ProtocolFactorySelectorFactory;
@SuppressWarnings("unchecked") public T httpHandlerFactory(HttpHandlerFactory httpHandlerFactory) { this.httpHandlerFactory = httpHandlerFactory; return (T) this; } @SuppressWarnings("unchecked") public T trafficForecastFactory(TrafficForecastFactory trafficForecast) { this.trafficForecastFactory = trafficForecast; return (T) this; } @SuppressWarnings("unchecked") public T logicExecutionStatistics(LogicExecutionStatistics logicExecutionStatistics) { this.logicExecutionStatistics = logicExecutionStatistics; return (T) this; } /** * Build the ThriftServerDef */ public ThriftServerDef build() { checkState(processor != null, "Processor not defined!"); checkState(maxConnections >= 0, "maxConnections should be 0 (for unlimited) or positive"); if (executor == null) { executor = new DefaultExecutorServiceFactory("NettyThrift") .newExecutorService(Runtime.getRuntime().availableProcessors() + 1); } if (protocolFactorySelectorFactory == null) {
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/DefaultProtocolFactorySelectorFactory.java // public class DefaultProtocolFactorySelectorFactory implements ProtocolFactorySelectorFactory { // // /* // * (non-Javadoc) // * // * @see io.netty5thrift.protocol.ProtocolFactorySelectorFactory# // * createProtocolFactorySelector(java.lang.Class) // */ // @Override // public ProtocolFactorySelector createProtocolFactorySelector(Class<?> interfaceClass) { // return new ProtocolFactorySelector(interfaceClass); // } // // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // } // Path: io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDefBuilderBase.java import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.util.concurrent.DefaultExecutorServiceFactory; import io.nettythrift.protocol.DefaultProtocolFactorySelectorFactory; import io.nettythrift.protocol.ProtocolFactorySelectorFactory; @SuppressWarnings("unchecked") public T httpHandlerFactory(HttpHandlerFactory httpHandlerFactory) { this.httpHandlerFactory = httpHandlerFactory; return (T) this; } @SuppressWarnings("unchecked") public T trafficForecastFactory(TrafficForecastFactory trafficForecast) { this.trafficForecastFactory = trafficForecast; return (T) this; } @SuppressWarnings("unchecked") public T logicExecutionStatistics(LogicExecutionStatistics logicExecutionStatistics) { this.logicExecutionStatistics = logicExecutionStatistics; return (T) this; } /** * Build the ThriftServerDef */ public ThriftServerDef build() { checkState(processor != null, "Processor not defined!"); checkState(maxConnections >= 0, "maxConnections should be 0 (for unlimited) or positive"); if (executor == null) { executor = new DefaultExecutorServiceFactory("NettyThrift") .newExecutorService(Runtime.getRuntime().availableProcessors() + 1); } if (protocolFactorySelectorFactory == null) {
protocolFactorySelectorFactory = new DefaultProtocolFactorySelectorFactory();
houkx/nettythrift
io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDef.java
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelector.java // public class ProtocolFactorySelector { // private static Logger logger = LoggerFactory.getLogger(ProtocolFactorySelector.class); // private final HashMap<Short, TProtocolFactory> protocolFactoryMap = new HashMap<Short, TProtocolFactory>(8); // // public ProtocolFactorySelector() { // } // // public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) { // protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory()); // protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory()); // protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory()); // if (interfaceClass != null) { // protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass)); // } // } // // protected void registProtocolFactory(short head, TProtocolFactory factory) { // protocolFactoryMap.put(head, factory); // } // // public TProtocolFactory getProtocolFactory(short head) { // // SimpleJson的前两个字符为:[" ,而TJSONProtocol的第二个字符为一个数字 // TProtocolFactory fac = protocolFactoryMap.get(head); // if (logger.isDebugEnabled()) { // logger.debug("head:{}, getProtocolFactory:{}", head, fac); // } // return fac; // } // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // }
import io.nettythrift.protocol.ProtocolFactorySelectorFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import org.apache.thrift.ProcessFunction; import org.apache.thrift.TBase; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.channel.socket.SocketChannel; import io.nettythrift.protocol.ProtocolFactorySelector;
/* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Descriptor for a Thrift Server. This defines a listener port that Server need * to start a Thrift endpoint. */ public class ThriftServerDef { // === CONSTANTS ====== // === configurations === public final String name; public final int serverPort; public final int maxFrameSize; public final int maxConnections; public final int queuedResponseLimit; public final NettyProcessor nettyProcessor; public final ChannelHandler codecInstaller; @SuppressWarnings("rawtypes") public final Map<String, ProcessFunction<?, ? extends TBase>> processMap; public final Object iface; public final ExecutorService executor; public final long clientIdleTimeout;
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelector.java // public class ProtocolFactorySelector { // private static Logger logger = LoggerFactory.getLogger(ProtocolFactorySelector.class); // private final HashMap<Short, TProtocolFactory> protocolFactoryMap = new HashMap<Short, TProtocolFactory>(8); // // public ProtocolFactorySelector() { // } // // public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) { // protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory()); // protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory()); // protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory()); // if (interfaceClass != null) { // protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass)); // } // } // // protected void registProtocolFactory(short head, TProtocolFactory factory) { // protocolFactoryMap.put(head, factory); // } // // public TProtocolFactory getProtocolFactory(short head) { // // SimpleJson的前两个字符为:[" ,而TJSONProtocol的第二个字符为一个数字 // TProtocolFactory fac = protocolFactoryMap.get(head); // if (logger.isDebugEnabled()) { // logger.debug("head:{}, getProtocolFactory:{}", head, fac); // } // return fac; // } // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // } // Path: io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDef.java import io.nettythrift.protocol.ProtocolFactorySelectorFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import org.apache.thrift.ProcessFunction; import org.apache.thrift.TBase; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.channel.socket.SocketChannel; import io.nettythrift.protocol.ProtocolFactorySelector; /* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Descriptor for a Thrift Server. This defines a listener port that Server need * to start a Thrift endpoint. */ public class ThriftServerDef { // === CONSTANTS ====== // === configurations === public final String name; public final int serverPort; public final int maxFrameSize; public final int maxConnections; public final int queuedResponseLimit; public final NettyProcessor nettyProcessor; public final ChannelHandler codecInstaller; @SuppressWarnings("rawtypes") public final Map<String, ProcessFunction<?, ? extends TBase>> processMap; public final Object iface; public final ExecutorService executor; public final long clientIdleTimeout;
public final ProtocolFactorySelector protocolFactorySelector;
houkx/nettythrift
io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDef.java
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelector.java // public class ProtocolFactorySelector { // private static Logger logger = LoggerFactory.getLogger(ProtocolFactorySelector.class); // private final HashMap<Short, TProtocolFactory> protocolFactoryMap = new HashMap<Short, TProtocolFactory>(8); // // public ProtocolFactorySelector() { // } // // public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) { // protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory()); // protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory()); // protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory()); // if (interfaceClass != null) { // protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass)); // } // } // // protected void registProtocolFactory(short head, TProtocolFactory factory) { // protocolFactoryMap.put(head, factory); // } // // public TProtocolFactory getProtocolFactory(short head) { // // SimpleJson的前两个字符为:[" ,而TJSONProtocol的第二个字符为一个数字 // TProtocolFactory fac = protocolFactoryMap.get(head); // if (logger.isDebugEnabled()) { // logger.debug("head:{}, getProtocolFactory:{}", head, fac); // } // return fac; // } // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // }
import io.nettythrift.protocol.ProtocolFactorySelectorFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import org.apache.thrift.ProcessFunction; import org.apache.thrift.TBase; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.channel.socket.SocketChannel; import io.nettythrift.protocol.ProtocolFactorySelector;
/* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Descriptor for a Thrift Server. This defines a listener port that Server need * to start a Thrift endpoint. */ public class ThriftServerDef { // === CONSTANTS ====== // === configurations === public final String name; public final int serverPort; public final int maxFrameSize; public final int maxConnections; public final int queuedResponseLimit; public final NettyProcessor nettyProcessor; public final ChannelHandler codecInstaller; @SuppressWarnings("rawtypes") public final Map<String, ProcessFunction<?, ? extends TBase>> processMap; public final Object iface; public final ExecutorService executor; public final long clientIdleTimeout; public final ProtocolFactorySelector protocolFactorySelector; public final HttpResourceHandler httpResourceHandler; public final boolean voidMethodDirectReturn; public final HttpHandlerFactory httpHandlerFactory; private final int[] voidMethodHashes; public final TrafficForecast trafficForecast; public final LogicExecutionStatistics logicExecutionStatistics; @SuppressWarnings("unchecked") public ThriftServerDef(String name, int serverPort, int maxFrameSize, int maxConnections, int queuedResponseLimit, NettyProcessorFactory nettyProcessorFactory, ChannelHandler codecInstaller, @SuppressWarnings("rawtypes") TBaseProcessor processor, ExecutorService executor, long clientIdleTimeout,
// Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelector.java // public class ProtocolFactorySelector { // private static Logger logger = LoggerFactory.getLogger(ProtocolFactorySelector.class); // private final HashMap<Short, TProtocolFactory> protocolFactoryMap = new HashMap<Short, TProtocolFactory>(8); // // public ProtocolFactorySelector() { // } // // public ProtocolFactorySelector(@SuppressWarnings("rawtypes") Class interfaceClass) { // protocolFactoryMap.put((short) -32767, new TBinaryProtocol.Factory()); // protocolFactoryMap.put((short) -32223, new TCompactProtocol.Factory()); // protocolFactoryMap.put((short) 23345, new TJSONProtocol.Factory()); // if (interfaceClass != null) { // protocolFactoryMap.put((short) 23330, new TSimpleJSONProtocol.Factory(interfaceClass)); // } // } // // protected void registProtocolFactory(short head, TProtocolFactory factory) { // protocolFactoryMap.put(head, factory); // } // // public TProtocolFactory getProtocolFactory(short head) { // // SimpleJson的前两个字符为:[" ,而TJSONProtocol的第二个字符为一个数字 // TProtocolFactory fac = protocolFactoryMap.get(head); // if (logger.isDebugEnabled()) { // logger.debug("head:{}, getProtocolFactory:{}", head, fac); // } // return fac; // } // } // // Path: io.nettythrift/src/main/java/io/nettythrift/protocol/ProtocolFactorySelectorFactory.java // public interface ProtocolFactorySelectorFactory { // // ProtocolFactorySelector createProtocolFactorySelector(Class<?> ifaceClass); // } // Path: io.nettythrift/src/main/java/io/nettythrift/core/ThriftServerDef.java import io.nettythrift.protocol.ProtocolFactorySelectorFactory; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import org.apache.thrift.ProcessFunction; import org.apache.thrift.TBase; import org.apache.thrift.TBaseProcessor; import io.netty.channel.ChannelHandler; import io.netty.channel.socket.SocketChannel; import io.nettythrift.protocol.ProtocolFactorySelector; /* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nettythrift.core; /** * Descriptor for a Thrift Server. This defines a listener port that Server need * to start a Thrift endpoint. */ public class ThriftServerDef { // === CONSTANTS ====== // === configurations === public final String name; public final int serverPort; public final int maxFrameSize; public final int maxConnections; public final int queuedResponseLimit; public final NettyProcessor nettyProcessor; public final ChannelHandler codecInstaller; @SuppressWarnings("rawtypes") public final Map<String, ProcessFunction<?, ? extends TBase>> processMap; public final Object iface; public final ExecutorService executor; public final long clientIdleTimeout; public final ProtocolFactorySelector protocolFactorySelector; public final HttpResourceHandler httpResourceHandler; public final boolean voidMethodDirectReturn; public final HttpHandlerFactory httpHandlerFactory; private final int[] voidMethodHashes; public final TrafficForecast trafficForecast; public final LogicExecutionStatistics logicExecutionStatistics; @SuppressWarnings("unchecked") public ThriftServerDef(String name, int serverPort, int maxFrameSize, int maxConnections, int queuedResponseLimit, NettyProcessorFactory nettyProcessorFactory, ChannelHandler codecInstaller, @SuppressWarnings("rawtypes") TBaseProcessor processor, ExecutorService executor, long clientIdleTimeout,
ProtocolFactorySelectorFactory protocolFactorySelectorFactory, HttpResourceHandler httpResourceHandler,
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/workflow/AddGitLabMergeRequestCommentStep.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener;
@Override public StepExecution start(StepContext context) throws Exception { return new AddGitLabMergeRequestCommentStepExecution(context, this); } public String getComment() { return comment; } @DataBoundSetter public void setComment(String comment) { this.comment = StringUtils.isEmpty(comment) ? null : comment; } public static class AddGitLabMergeRequestCommentStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AddGitLabMergeRequestCommentStep step; AddGitLabMergeRequestCommentStepExecution(StepContext context, AddGitLabMergeRequestCommentStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception {
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/workflow/AddGitLabMergeRequestCommentStep.java import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; @Override public StepExecution start(StepContext context) throws Exception { return new AddGitLabMergeRequestCommentStepExecution(context, this); } public String getComment() { return comment; } @DataBoundSetter public void setComment(String comment) { this.comment = StringUtils.isEmpty(comment) ? null : comment; } public static class AddGitLabMergeRequestCommentStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AddGitLabMergeRequestCommentStep step; AddGitLabMergeRequestCommentStepExecution(StepContext context, AddGitLabMergeRequestCommentStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception {
GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class);
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/workflow/AddGitLabMergeRequestCommentStep.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener;
} public String getComment() { return comment; } @DataBoundSetter public void setComment(String comment) { this.comment = StringUtils.isEmpty(comment) ? null : comment; } public static class AddGitLabMergeRequestCommentStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AddGitLabMergeRequestCommentStep step; AddGitLabMergeRequestCommentStepExecution(StepContext context, AddGitLabMergeRequestCommentStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception { GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class); if (cause != null) { MergeRequest mergeRequest = cause.getData().getMergeRequest(); if (mergeRequest != null) {
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/workflow/AddGitLabMergeRequestCommentStep.java import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; } public String getComment() { return comment; } @DataBoundSetter public void setComment(String comment) { this.comment = StringUtils.isEmpty(comment) ? null : comment; } public static class AddGitLabMergeRequestCommentStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AddGitLabMergeRequestCommentStep step; AddGitLabMergeRequestCommentStepExecution(StepContext context, AddGitLabMergeRequestCommentStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception { GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class); if (cause != null) { MergeRequest mergeRequest = cause.getData().getMergeRequest(); if (mergeRequest != null) {
GitLabClient client = getClient(run);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl;
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl;
private GitLabClientBuilder clientBuilder;
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
addGitLabApiToken();
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder());
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder());
api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10);
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10);
v3Request = versionRequest(V3GitLabApiProxy.ID);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception {
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception {
mockServerClient.when(v3Request).respond(responseOk());
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception { mockServerClient.when(v3Request).respond(responseOk()); api.getCurrentUser();
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception { mockServerClient.when(v3Request).respond(responseOk()); api.getCurrentUser();
assertApiImpl(api, V3GitLabApiProxy.class);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception { mockServerClient.when(v3Request).respond(responseOk()); api.getCurrentUser(); assertApiImpl(api, V3GitLabApiProxy.class); mockServerClient.verify(v3Request, v3Request); } @Test public void buildClient_success_v4() throws Exception {
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static final String API_TOKEN = "secret"; // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void addGitLabApiToken() throws IOException { // for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { // if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { // List<Domain> domains = credentialsStore.getDomains(); // credentialsStore.addCredentials(domains.get(0), // new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); // } // } // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseNotFound() { // return responseWithStatus(Response.Status.NOT_FOUND); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpResponse responseOk() { // return responseWithStatus(Response.Status.OK); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static HttpRequest versionRequest(String id) { // return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectingGitLabClientTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.API_TOKEN; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.addGitLabApiToken; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseNotFound; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.responseOk; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.versionRequest; import static org.junit.Assert.fail; import static org.mockserver.matchers.Times.exactly; import static org.mockserver.matchers.Times.once; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.client.MockServerClient; import org.mockserver.junit.MockServerRule; import org.mockserver.model.HttpRequest; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class AutodetectingGitLabClientTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); private MockServerClient mockServerClient; private String gitLabUrl; private GitLabClientBuilder clientBuilder; private AutodetectingGitLabClient api; private HttpRequest v3Request; private HttpRequest v4Request; @Before public void setup() throws IOException { gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab"; addGitLabApiToken(); List<GitLabClientBuilder> builders = Arrays.<GitLabClientBuilder>asList(new V3GitLabClientBuilder(), new V4GitLabClientBuilder()); api = new AutodetectingGitLabClient(builders, gitLabUrl, API_TOKEN, true, 10, 10); v3Request = versionRequest(V3GitLabApiProxy.ID); v4Request = versionRequest(V4GitLabApiProxy.ID); } @Test public void buildClient_success_v3() throws Exception { mockServerClient.when(v3Request).respond(responseOk()); api.getCurrentUser(); assertApiImpl(api, V3GitLabApiProxy.class); mockServerClient.verify(v3Request, v3Request); } @Test public void buildClient_success_v4() throws Exception {
mockServerClient.when(v3Request).respond(responseNotFound());
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule;
package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders();
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders();
assertThat(builders.get(0), instanceOf(AutodetectGitLabClientBuilder.class));
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule;
package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders(); assertThat(builders.get(0), instanceOf(AutodetectGitLabClientBuilder.class));
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders(); assertThat(builders.get(0), instanceOf(AutodetectGitLabClientBuilder.class));
assertThat(builders.get(1), instanceOf(V4GitLabClientBuilder.class));
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule;
package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders(); assertThat(builders.get(0), instanceOf(AutodetectGitLabClientBuilder.class)); assertThat(builders.get(1), instanceOf(V4GitLabClientBuilder.class));
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { // public AutodetectGitLabClientBuilder() { // super("autodetect", 0); // } // // @Override // @NonNull // public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) { // Collection<GitLabClientBuilder> candidates = new ArrayList<>(getAllGitLabClientBuilders()); // candidates.remove(this); // return new AutodetectingGitLabClient(candidates, url, token, ignoreCertificateErrors, connectionTimeout, readTimeout); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V3GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V3GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 2; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getId(); // } // }; // // public V3GitLabClientBuilder() { // super(V3GitLabApiProxy.ID, ORDINAL, V3GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/V4GitLabClientBuilder.java // @Extension // @Restricted(NoExternalUse.class) // public final class V4GitLabClientBuilder extends ResteasyGitLabClientBuilder { // private static final int ORDINAL = 1; // private static final Function<MergeRequest, Integer> MERGE_REQUEST_ID_PROVIDER = new Function<MergeRequest, Integer>() { // @Override // public Integer apply(MergeRequest mergeRequest) { // return mergeRequest.getIid(); // } // }; // // public V4GitLabClientBuilder() { // super(V4GitLabApiProxy.ID, ORDINAL, V4GitLabApiProxy.class, MERGE_REQUEST_ID_PROVIDER); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilderTest.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsInstanceOf.instanceOf; import com.dabsquared.gitlabjenkins.gitlab.api.impl.AutodetectGitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V3GitLabClientBuilder; import com.dabsquared.gitlabjenkins.gitlab.api.impl.V4GitLabClientBuilder; import java.util.List; import java.util.NoSuchElementException; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; package com.dabsquared.gitlabjenkins.gitlab.api; public class GitLabClientBuilderTest { @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void getAllGitLabClientBuilders_list_is_sorted_by_ordinal() { List<GitLabClientBuilder> builders = GitLabClientBuilder.getAllGitLabClientBuilders(); assertThat(builders.get(0), instanceOf(AutodetectGitLabClientBuilder.class)); assertThat(builders.get(1), instanceOf(V4GitLabClientBuilder.class));
assertThat(builders.get(2), instanceOf(V3GitLabClientBuilder.class));
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/workflow/AcceptGitLabMergeRequestStep.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.*; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener;
@DataBoundSetter public void setMergeCommitMessage(String mergeCommitMessage) { this.mergeCommitMessage = StringUtils.isEmpty(mergeCommitMessage) ? null : mergeCommitMessage; } @DataBoundSetter public void setUseMRDescription(boolean useMRDescription) { this.useMRDescription = useMRDescription; } @DataBoundSetter public void setRemoveSourceBranch(boolean removeSourceBranch) { this.removeSourceBranch = removeSourceBranch; } public static class AcceptGitLabMergeRequestStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AcceptGitLabMergeRequestStep step; AcceptGitLabMergeRequestStepExecution(StepContext context, AcceptGitLabMergeRequestStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception {
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/workflow/AcceptGitLabMergeRequestStep.java import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.*; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; @DataBoundSetter public void setMergeCommitMessage(String mergeCommitMessage) { this.mergeCommitMessage = StringUtils.isEmpty(mergeCommitMessage) ? null : mergeCommitMessage; } @DataBoundSetter public void setUseMRDescription(boolean useMRDescription) { this.useMRDescription = useMRDescription; } @DataBoundSetter public void setRemoveSourceBranch(boolean removeSourceBranch) { this.removeSourceBranch = removeSourceBranch; } public static class AcceptGitLabMergeRequestStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AcceptGitLabMergeRequestStep step; AcceptGitLabMergeRequestStepExecution(StepContext context, AcceptGitLabMergeRequestStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception {
GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class);
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/workflow/AcceptGitLabMergeRequestStep.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.*; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener;
@DataBoundSetter public void setUseMRDescription(boolean useMRDescription) { this.useMRDescription = useMRDescription; } @DataBoundSetter public void setRemoveSourceBranch(boolean removeSourceBranch) { this.removeSourceBranch = removeSourceBranch; } public static class AcceptGitLabMergeRequestStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AcceptGitLabMergeRequestStep step; AcceptGitLabMergeRequestStepExecution(StepContext context, AcceptGitLabMergeRequestStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception { GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class); if (cause != null) { MergeRequest mergeRequest = cause.getData().getMergeRequest(); if (mergeRequest != null) {
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/workflow/AcceptGitLabMergeRequestStep.java import static com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty.getClient; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.workflow.steps.*; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.export.ExportedBean; import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.Run; import hudson.model.TaskListener; @DataBoundSetter public void setUseMRDescription(boolean useMRDescription) { this.useMRDescription = useMRDescription; } @DataBoundSetter public void setRemoveSourceBranch(boolean removeSourceBranch) { this.removeSourceBranch = removeSourceBranch; } public static class AcceptGitLabMergeRequestStepExecution extends AbstractSynchronousStepExecution<Void> { private static final long serialVersionUID = 1; private final transient Run<?, ?> run; private final transient AcceptGitLabMergeRequestStep step; AcceptGitLabMergeRequestStepExecution(StepContext context, AcceptGitLabMergeRequestStep step) throws Exception { super(context); this.step = step; run = context.get(Run.class); } @Override protected Void run() throws Exception { GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class); if (cause != null) { MergeRequest mergeRequest = cause.getData().getMergeRequest(); if (mergeRequest != null) {
GitLabClient client = getClient(run);
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/publisher/GitLabAcceptMergeRequestPublisher.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import java.util.logging.Level; import java.util.logging.Logger;
package com.dabsquared.gitlabjenkins.publisher; /** * @author Robin Müller */ public class GitLabAcceptMergeRequestPublisher extends MergeRequestNotifier { private static final Logger LOGGER = Logger.getLogger(GitLabAcceptMergeRequestPublisher.class.getName()); private Boolean deleteSourceBranch; @DataBoundConstructor public GitLabAcceptMergeRequestPublisher() { } @DataBoundSetter public void setDeleteSourceBranch(boolean deleteSourceBranch) { this.deleteSourceBranch = deleteSourceBranch; } public boolean isDeleteSourceBranch() { return deleteSourceBranch; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } @Override public String getDisplayName() { return Messages.GitLabAcceptMergeRequestPublisher_DisplayName(); } } @Override
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/publisher/GitLabAcceptMergeRequestPublisher.java import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.model.MergeRequest; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; import java.util.logging.Level; import java.util.logging.Logger; package com.dabsquared.gitlabjenkins.publisher; /** * @author Robin Müller */ public class GitLabAcceptMergeRequestPublisher extends MergeRequestNotifier { private static final Logger LOGGER = Logger.getLogger(GitLabAcceptMergeRequestPublisher.class.getName()); private Boolean deleteSourceBranch; @DataBoundConstructor public GitLabAcceptMergeRequestPublisher() { } @DataBoundSetter public void setDeleteSourceBranch(boolean deleteSourceBranch) { this.deleteSourceBranch = deleteSourceBranch; } public boolean isDeleteSourceBranch() { return deleteSourceBranch; } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { @Override public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } @Override public String getDisplayName() { return Messages.GitLabAcceptMergeRequestPublisher_DisplayName(); } } @Override
protected void perform(Run<?, ?> build, TaskListener listener, GitLabClient client, MergeRequest mergeRequest) {
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_8_1_2_8c8af7b.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections;
package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_8_1_2_8c8af7b implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000"; private static final String COMMIT_25 = "258d6f6e21e6dda343f6e9f8e78c38f12bb81c87"; private static final String COMMIT_63 = "63b30060be89f0338123f2d8975588e7d40a1874"; private static final String COMMIT_64 = "64ed77c360ee7ac900c68292775bee2184c1e593"; private static final String COMMIT_74 = "742d8d0b4b16792c38c6798b28ba1fa754da165e"; private static final String COMMIT_E5 = "e5a46665b80965724b45fe921788105258b3ec5c";
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_8_1_2_8c8af7b.java import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections; package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_8_1_2_8c8af7b implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000"; private static final String COMMIT_25 = "258d6f6e21e6dda343f6e9f8e78c38f12bb81c87"; private static final String COMMIT_63 = "63b30060be89f0338123f2d8975588e7d40a1874"; private static final String COMMIT_64 = "64ed77c360ee7ac900c68292775bee2184c1e593"; private static final String COMMIT_74 = "742d8d0b4b16792c38c6798b28ba1fa754da165e"; private static final String COMMIT_E5 = "e5a46665b80965724b45fe921788105258b3ec5c";
public PushHook pushBrandNewMasterBranchRequest() {
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.Extension; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.Collection;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; @Extension @Restricted(NoExternalUse.class)
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.Extension; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.Collection; package com.dabsquared.gitlabjenkins.gitlab.api.impl; @Extension @Restricted(NoExternalUse.class)
public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder {
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.Extension; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.Collection;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; @Extension @Restricted(NoExternalUse.class) public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { public AutodetectGitLabClientBuilder() { super("autodetect", 0); } @Override @NonNull
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/AutodetectGitLabClientBuilder.java import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.Extension; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.Collection; package com.dabsquared.gitlabjenkins.gitlab.api.impl; @Extension @Restricted(NoExternalUse.class) public final class AutodetectGitLabClientBuilder extends GitLabClientBuilder { public AutodetectGitLabClientBuilder() { super("autodetect", 0); } @Override @NonNull
public GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout) {
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.util.Secret; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.Response; import jenkins.model.Jenkins; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; class TestUtility { static final String API_TOKEN = "secret"; private static final String API_TOKEN_ID = "apiTokenId"; private static final boolean IGNORE_CERTIFICATE_ERRORS = true; private static final int CONNECTION_TIMEOUT = 10; private static final int READ_TIMEOUT = 10; static void addGitLabApiToken() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); } } } static HttpRequest versionRequest(String id) { return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); } static HttpResponse responseOk() { return responseWithStatus(Response.Status.OK); } static HttpResponse responseNotFound() { return responseWithStatus(Response.Status.NOT_FOUND); } private static HttpResponse responseWithStatus(Response.Status status) { return response().withStatusCode(status.getStatusCode()); }
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.util.Secret; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.Response; import jenkins.model.Jenkins; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse; package com.dabsquared.gitlabjenkins.gitlab.api.impl; class TestUtility { static final String API_TOKEN = "secret"; private static final String API_TOKEN_ID = "apiTokenId"; private static final boolean IGNORE_CERTIFICATE_ERRORS = true; private static final int CONNECTION_TIMEOUT = 10; private static final int READ_TIMEOUT = 10; static void addGitLabApiToken() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); } } } static HttpRequest versionRequest(String id) { return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); } static HttpResponse responseOk() { return responseWithStatus(Response.Status.OK); } static HttpResponse responseNotFound() { return responseWithStatus(Response.Status.NOT_FOUND); } private static HttpResponse responseWithStatus(Response.Status status) { return response().withStatusCode(status.getStatusCode()); }
static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) {
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.util.Secret; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.Response; import jenkins.model.Jenkins; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; class TestUtility { static final String API_TOKEN = "secret"; private static final String API_TOKEN_ID = "apiTokenId"; private static final boolean IGNORE_CERTIFICATE_ERRORS = true; private static final int CONNECTION_TIMEOUT = 10; private static final int READ_TIMEOUT = 10; static void addGitLabApiToken() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); } } } static HttpRequest versionRequest(String id) { return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); } static HttpResponse responseOk() { return responseWithStatus(Response.Status.OK); } static HttpResponse responseNotFound() { return responseWithStatus(Response.Status.NOT_FOUND); } private static HttpResponse responseWithStatus(Response.Status status) { return response().withStatusCode(status.getStatusCode()); }
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.instanceOf; import static org.mockserver.model.HttpRequest.request; import static org.mockserver.model.HttpResponse.response; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.util.Secret; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.Response; import jenkins.model.Jenkins; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.mockserver.model.HttpRequest; import org.mockserver.model.HttpResponse; package com.dabsquared.gitlabjenkins.gitlab.api.impl; class TestUtility { static final String API_TOKEN = "secret"; private static final String API_TOKEN_ID = "apiTokenId"; private static final boolean IGNORE_CERTIFICATE_ERRORS = true; private static final int CONNECTION_TIMEOUT = 10; private static final int READ_TIMEOUT = 10; static void addGitLabApiToken() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN))); } } } static HttpRequest versionRequest(String id) { return request().withMethod(HttpMethod.GET).withPath("/gitlab/api/" + id + "/.*").withHeader("PRIVATE-TOKEN", API_TOKEN); } static HttpResponse responseOk() { return responseWithStatus(Response.Status.OK); } static HttpResponse responseNotFound() { return responseWithStatus(Response.Status.NOT_FOUND); } private static HttpResponse responseWithStatus(Response.Status status) { return response().withStatusCode(status.getStatusCode()); }
static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) {
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java // static TestData forRemoteUrl(String baseUrl, String remoteUrl) { // return new TestData(baseUrl, remoteUrl); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.util.ProjectIdUtilTest.TestData.forRemoteUrl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith;
package com.dabsquared.gitlabjenkins.util; /** * @author Robin Müller */ @RunWith(Theories.class) public class ProjectIdUtilTest { @DataPoints public static TestData[] testData = {
// Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java // static TestData forRemoteUrl(String baseUrl, String remoteUrl) { // return new TestData(baseUrl, remoteUrl); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java import static com.dabsquared.gitlabjenkins.util.ProjectIdUtilTest.TestData.forRemoteUrl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; package com.dabsquared.gitlabjenkins.util; /** * @author Robin Müller */ @RunWith(Theories.class) public class ProjectIdUtilTest { @DataPoints public static TestData[] testData = {
forRemoteUrl("[email protected]", "[email protected]:test/project.git").expectProjectId("test/project"),
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java // static TestData forRemoteUrl(String baseUrl, String remoteUrl) { // return new TestData(baseUrl, remoteUrl); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import static com.dabsquared.gitlabjenkins.util.ProjectIdUtilTest.TestData.forRemoteUrl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith;
package com.dabsquared.gitlabjenkins.util; /** * @author Robin Müller */ @RunWith(Theories.class) public class ProjectIdUtilTest { @DataPoints public static TestData[] testData = { forRemoteUrl("[email protected]", "[email protected]:test/project.git").expectProjectId("test/project"), forRemoteUrl("https://gitlab.com", "https://gitlab.com/test/project.git").expectProjectId("test/project"), forRemoteUrl("https://myurl.com/gitlab", "https://myurl.com/gitlab/group/project.git").expectProjectId("group/project"), forRemoteUrl("[email protected]", "[email protected]:group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com/gitlab", "https://myurl.com/gitlab/group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com", "https://myurl.com/group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com", "https://myurl.com/group/subgroup/subsubgroup/project.git").expectProjectId("group/subgroup/subsubgroup/project"), forRemoteUrl("[email protected]", "[email protected]:group/subgroup/subsubgroup/project.git").expectProjectId("group/subgroup/subsubgroup/project"), forRemoteUrl("http://myhost", "http://myhost.com/group/project.git").expectProjectId("group/project"), forRemoteUrl("", "http://myhost.com/group/project.git").expectProjectId("group/project"), forRemoteUrl("", "http://myhost.com:group/project.git").expectProjectId("group/project"), }; @Theory public void retrieveProjectId(TestData testData) throws ProjectIdUtil.ProjectIdResolutionException {
// Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java // static TestData forRemoteUrl(String baseUrl, String remoteUrl) { // return new TestData(baseUrl, remoteUrl); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/test/java/com/dabsquared/gitlabjenkins/util/ProjectIdUtilTest.java import static com.dabsquared.gitlabjenkins.util.ProjectIdUtilTest.TestData.forRemoteUrl; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; package com.dabsquared.gitlabjenkins.util; /** * @author Robin Müller */ @RunWith(Theories.class) public class ProjectIdUtilTest { @DataPoints public static TestData[] testData = { forRemoteUrl("[email protected]", "[email protected]:test/project.git").expectProjectId("test/project"), forRemoteUrl("https://gitlab.com", "https://gitlab.com/test/project.git").expectProjectId("test/project"), forRemoteUrl("https://myurl.com/gitlab", "https://myurl.com/gitlab/group/project.git").expectProjectId("group/project"), forRemoteUrl("[email protected]", "[email protected]:group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com/gitlab", "https://myurl.com/gitlab/group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com", "https://myurl.com/group/subgroup/project.git").expectProjectId("group/subgroup/project"), forRemoteUrl("https://myurl.com", "https://myurl.com/group/subgroup/subsubgroup/project.git").expectProjectId("group/subgroup/subsubgroup/project"), forRemoteUrl("[email protected]", "[email protected]:group/subgroup/subsubgroup/project.git").expectProjectId("group/subgroup/subsubgroup/project"), forRemoteUrl("http://myhost", "http://myhost.com/group/project.git").expectProjectId("group/project"), forRemoteUrl("", "http://myhost.com/group/project.git").expectProjectId("group/project"), forRemoteUrl("", "http://myhost.com:group/project.git").expectProjectId("group/project"), }; @Theory public void retrieveProjectId(TestData testData) throws ProjectIdUtil.ProjectIdResolutionException {
GitLabClient client = new GitLabClientStub(testData.hostUrl);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_7_5_1_36679b5.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections;
package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_7_5_1_36679b5 implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000";
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_7_5_1_36679b5.java import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections; package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_7_5_1_36679b5 implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000";
public PushHook pushBrandNewMasterBranchRequest() {
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_7_10_5_489b413.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections;
package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_7_10_5_489b413 implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000"; private static final String COMMIT_7A = "7a5db3baf5d42b4218a2a501c88f745559b1d24c"; private static final String COMMIT_21 = "21d67fe28097b49a1a6fb5c82cbfe03d389e8685"; private static final String COMMIT_9d = "9dbdd7a128a2789d0f436222ce116f1d8229e083";
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/hook/model/PushHook.java // @GeneratePojoBuilder(intoPackage = "*.builder.generated", withFactoryMethod = "*") // public class PushHook extends WebHook { // // private String before; // private String after; // private String ref; // private Integer userId; // private String userName; // private String userUsername; // private String userEmail; // private String userAvatar; // private Integer projectId; // private Project project; // private List<Commit> commits; // private Integer totalCommitsCount; // // public String getBefore() { // return before; // } // // public void setBefore(String before) { // this.before = before; // } // // public String getAfter() { // return after; // } // // public void setAfter(String after) { // this.after = after; // } // // public String getRef() { // return ref; // } // // public void setRef(String ref) { // this.ref = ref; // } // // public Integer getUserId() { // return userId; // } // // public void setUserId(Integer userId) { // this.userId = userId; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // // public String getUserUsername() { // return userUsername; // } // // public void setUserUsername(String userUsername) { // this.userUsername = userUsername; // } // // public String getUserEmail() { // return userEmail; // } // // public void setUserEmail(String userEmail) { // this.userEmail = userEmail; // } // // public String getUserAvatar() { // return userAvatar; // } // // public void setUserAvatar(String userAvatar) { // this.userAvatar = userAvatar; // } // // public Integer getProjectId() { // return projectId; // } // // public void setProjectId(Integer projectId) { // this.projectId = projectId; // } // // public Project getProject() { // return project; // } // // public void setProject(Project project) { // this.project = project; // } // // public List<Commit> getCommits() { // return commits; // } // // public void setCommits(List<Commit> commits) { // this.commits = commits; // } // // public Integer getTotalCommitsCount() { // return totalCommitsCount; // } // // public void setTotalCommitsCount(Integer totalCommitsCount) { // this.totalCommitsCount = totalCommitsCount; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // PushHook pushHook = (PushHook) o; // return new EqualsBuilder() // .append(before, pushHook.before) // .append(after, pushHook.after) // .append(ref, pushHook.ref) // .append(userId, pushHook.userId) // .append(userName, pushHook.userName) // .append(userEmail, pushHook.userEmail) // .append(userAvatar, pushHook.userAvatar) // .append(projectId, pushHook.projectId) // .append(project, pushHook.project) // .append(commits, pushHook.commits) // .append(totalCommitsCount, pushHook.totalCommitsCount) // .isEquals(); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(17, 37) // .append(before) // .append(after) // .append(ref) // .append(userId) // .append(userName) // .append(userEmail) // .append(userAvatar) // .append(projectId) // .append(project) // .append(commits) // .append(totalCommitsCount) // .toHashCode(); // } // // @Override // public String toString() { // return new ToStringBuilder(this) // .append("before", before) // .append("after", after) // .append("ref", ref) // .append("userId", userId) // .append("userName", userName) // .append("userEmail", userEmail) // .append("userAvatar", userAvatar) // .append("projectId", projectId) // .append("project", project) // .append("commits", commits) // .append("totalCommitsCount", totalCommitsCount) // .toString(); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/testhelpers/GitLabPushRequestSamples_7_10_5_489b413.java import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.CommitBuilder.commit; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.PushHookBuilder.pushHook; import static com.dabsquared.gitlabjenkins.gitlab.hook.model.builder.generated.RepositoryBuilder.repository; import com.dabsquared.gitlabjenkins.gitlab.hook.model.PushHook; import java.util.Arrays; import java.util.Collections; package com.dabsquared.gitlabjenkins.testhelpers; public class GitLabPushRequestSamples_7_10_5_489b413 implements GitLabPushRequestSamples { private static final String ZERO_SHA = "0000000000000000000000000000000000000000"; private static final String COMMIT_7A = "7a5db3baf5d42b4218a2a501c88f745559b1d24c"; private static final String COMMIT_21 = "21d67fe28097b49a1a6fb5c82cbfe03d389e8685"; private static final String COMMIT_9d = "9dbdd7a128a2789d0f436222ce116f1d8229e083";
public PushHook pushBrandNewMasterBranchRequest() {
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/connection/GitLabConnectionConfig.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // }
import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Item; import jenkins.model.GlobalConfiguration; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
public boolean isUseAuthenticatedEndpoint() { return useAuthenticatedEndpoint; } @DataBoundSetter public void setUseAuthenticatedEndpoint(boolean useAuthenticatedEndpoint) { this.useAuthenticatedEndpoint = useAuthenticatedEndpoint; save(); } public List<GitLabConnection> getConnections() { return connections; } public void addConnection(GitLabConnection connection) { connections.add(connection); connectionMap.put(connection.getName(), connection); } @DataBoundSetter public void setConnections(List<GitLabConnection> newConnections) { connections = new ArrayList<>(); connectionMap = new HashMap<>(); for (GitLabConnection connection: newConnections){ addConnection(connection); } save(); }
// Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClient.java // public interface GitLabClient { // String getHostUrl(); // // Project createProject(String projectName); // // MergeRequest createMergeRequest(Integer projectId, String sourceBranch, String targetBranch, String title); // // Project getProject(String projectName); // // Project updateProject(String projectId, String name, String path); // // void deleteProject(String projectId); // // void addProjectHook(String projectId, String url, Boolean pushEvents, Boolean mergeRequestEvents, Boolean noteEvents); // // void changeBuildStatus(String projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void changeBuildStatus(Integer projectId, String sha, BuildState state, String ref, String context, String targetUrl, String description); // // void getCommit(String projectId, String sha); // // void acceptMergeRequest(MergeRequest mr, String mergeCommitMessage, Boolean shouldRemoveSourceBranch); // // void createMergeRequestNote(MergeRequest mr, String body); // // List<Awardable> getMergeRequestEmoji(MergeRequest mr); // // void awardMergeRequestEmoji(MergeRequest mr, String name); // // void deleteMergeRequestEmoji(MergeRequest mr, Integer awardId); // // List<MergeRequest> getMergeRequests(String projectId, State state, int page, int perPage); // // List<Branch> getBranches(String projectId); // // Branch getBranch(String projectId, String branch); // // User getCurrentUser(); // // User addUser(String email, String username, String name, String password); // // User updateUser(String userId, String email, String username, String name, String password); // // List<Label> getLabels(String projectId); // // List<Pipeline> getPipelines(String projectName); // } // Path: src/main/java/com/dabsquared/gitlabjenkins/connection/GitLabConnectionConfig.java import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClient; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Item; import jenkins.model.GlobalConfiguration; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public boolean isUseAuthenticatedEndpoint() { return useAuthenticatedEndpoint; } @DataBoundSetter public void setUseAuthenticatedEndpoint(boolean useAuthenticatedEndpoint) { this.useAuthenticatedEndpoint = useAuthenticatedEndpoint; save(); } public List<GitLabConnection> getConnections() { return connections; } public void addConnection(GitLabConnection connection) { connections.add(connection); connectionMap.put(connection.getName(), connection); } @DataBoundSetter public void setConnections(List<GitLabConnection> newConnections) { connections = new ArrayList<>(); connectionMap = new HashMap<>(); for (GitLabConnection connection: newConnections){ addConnection(connection); } save(); }
public GitLabClient getClient(String connectionName, Item item, String jobCredentialId) {
jenkinsci/gitlab-plugin
src/main/java/com/dabsquared/gitlabjenkins/environment/GitLabEnvironmentContributor.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // }
import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import hudson.EnvVars; import hudson.Extension; import hudson.matrix.MatrixRun; import hudson.matrix.MatrixBuild; import hudson.model.EnvironmentContributor; import hudson.model.Run; import hudson.model.TaskListener; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException;
package com.dabsquared.gitlabjenkins.environment; /** * @author Robin Müller */ @Extension public class GitLabEnvironmentContributor extends EnvironmentContributor { @Override public void buildEnvironmentFor(@NonNull Run r, @NonNull EnvVars envs, @NonNull TaskListener listener) throws IOException, InterruptedException {
// Path: src/main/java/com/dabsquared/gitlabjenkins/cause/GitLabWebHookCause.java // @ExportedBean // public class GitLabWebHookCause extends SCMTrigger.SCMTriggerCause { // // private final CauseData data; // // public GitLabWebHookCause(CauseData data) { // super(""); // this.data = Objects.requireNonNull(data, "data must not be null"); // } // // @Exported // public CauseData getData() { // return data; // } // // @Override // public String getShortDescription() { // return data.getShortDescription(); // } // } // Path: src/main/java/com/dabsquared/gitlabjenkins/environment/GitLabEnvironmentContributor.java import com.dabsquared.gitlabjenkins.cause.GitLabWebHookCause; import hudson.EnvVars; import hudson.Extension; import hudson.matrix.MatrixRun; import hudson.matrix.MatrixBuild; import hudson.model.EnvironmentContributor; import hudson.model.Run; import hudson.model.TaskListener; import edu.umd.cs.findbugs.annotations.NonNull; import java.io.IOException; package com.dabsquared.gitlabjenkins.environment; /** * @author Robin Müller */ @Extension public class GitLabEnvironmentContributor extends EnvironmentContributor { @Override public void buildEnvironmentFor(@NonNull Run r, @NonNull EnvVars envs, @NonNull TaskListener listener) throws IOException, InterruptedException {
GitLabWebHookCause cause = null;
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception {
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception {
GitLabClientBuilder clientBuilder = new ResteasyGitLabClientBuilder("test", 0, V3GitLabApiProxy.class, null);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception { GitLabClientBuilder clientBuilder = new ResteasyGitLabClientBuilder("test", 0, V3GitLabApiProxy.class, null);
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception { GitLabClientBuilder clientBuilder = new ResteasyGitLabClientBuilder("test", 0, V3GitLabApiProxy.class, null);
assertApiImpl(buildClientWithDefaults(clientBuilder, "http://localhost/"), V3GitLabApiProxy.class);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // }
import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule;
package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception { GitLabClientBuilder clientBuilder = new ResteasyGitLabClientBuilder("test", 0, V3GitLabApiProxy.class, null);
// Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static void assertApiImpl(GitLabClient client, Class<? extends GitLabApiProxy> apiImplClass) throws Exception { // Field apiField = ((ResteasyGitLabClient) client).getClass().getDeclaredField("api"); // apiField.setAccessible(true); // assertThat(apiField.get(client), instanceOf(apiImplClass)); // } // // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/TestUtility.java // static GitLabClient buildClientWithDefaults(GitLabClientBuilder clientBuilder, String url) { // return clientBuilder.buildClient(url, API_TOKEN, IGNORE_CERTIFICATE_ERRORS, CONNECTION_TIMEOUT, READ_TIMEOUT); // } // // Path: src/main/java/com/dabsquared/gitlabjenkins/gitlab/api/GitLabClientBuilder.java // @Restricted(NoExternalUse.class) // public abstract class GitLabClientBuilder implements Comparable<GitLabClientBuilder>, ExtensionPoint, Serializable { // public static GitLabClientBuilder getGitLabClientBuilderById(String id) { // for (GitLabClientBuilder provider : getAllGitLabClientBuilders()) { // if (provider.id().equals(id)) { // return provider; // } // } // // throw new NoSuchElementException("unknown client-builder-id: " + id); // } // // public static List<GitLabClientBuilder> getAllGitLabClientBuilders() { // List<GitLabClientBuilder> builders = new ArrayList<>(Jenkins.getInstance().getExtensionList(GitLabClientBuilder.class)); // sort(builders); // return builders; // } // // private final String id; // private final int ordinal; // // protected GitLabClientBuilder(String id, int ordinal) { // this.id = id; // this.ordinal = ordinal; // } // // @NonNull // public final String id() { // return id; // } // // @NonNull // public abstract GitLabClient buildClient(String url, String token, boolean ignoreCertificateErrors, int connectionTimeout, int readTimeout); // // @Override // public final int compareTo(@NonNull GitLabClientBuilder other) { // int o = ordinal - other.ordinal; // return o != 0 ? o : id().compareTo(other.id()); // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/gitlab/api/impl/ResteasyGitLabClientBuilderTest.java import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.assertApiImpl; import static com.dabsquared.gitlabjenkins.gitlab.api.impl.TestUtility.buildClientWithDefaults; import static org.junit.Assert.assertNotNull; import com.dabsquared.gitlabjenkins.gitlab.api.GitLabClientBuilder; import hudson.ProxyConfiguration; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.junit.MockServerRule; package com.dabsquared.gitlabjenkins.gitlab.api.impl; public class ResteasyGitLabClientBuilderTest { @Rule public MockServerRule mockServer = new MockServerRule(this); @Rule public JenkinsRule jenkins = new JenkinsRule(); @Test public void buildClient() throws Exception { GitLabClientBuilder clientBuilder = new ResteasyGitLabClientBuilder("test", 0, V3GitLabApiProxy.class, null);
assertApiImpl(buildClientWithDefaults(clientBuilder, "http://localhost/"), V3GitLabApiProxy.class);
jenkinsci/gitlab-plugin
src/test/java/com/dabsquared/gitlabjenkins/connection/GitLabConnectionConfigSSLTest.java
// Path: src/main/java/com/dabsquared/gitlabjenkins/connection/GitLabConnection.java // @Extension // public static class DescriptorImpl extends Descriptor<GitLabConnection> { // public FormValidation doCheckName(@QueryParameter String id, @QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.name_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckUrl(@QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.url_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckApiTokenId(@QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.apiToken_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckConnectionTimeout(@QueryParameter Integer value) { // if (value == null) { // return FormValidation.error(Messages.connectionTimeout_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckReadTimeout(@QueryParameter Integer value) { // if (value == null) { // return FormValidation.error(Messages.readTimeout_required()); // } else { // return FormValidation.ok(); // } // } // // @RequirePOST // @Restricted(DoNotUse.class) // WebOnly // public FormValidation doTestConnection(@QueryParameter String url, // @QueryParameter String apiTokenId, // @QueryParameter String clientBuilderId, // @QueryParameter boolean ignoreCertificateErrors, // @QueryParameter int connectionTimeout, // @QueryParameter int readTimeout) { // Jenkins.get().checkPermission(Jenkins.ADMINISTER); // try { // new GitLabConnection("", url, apiTokenId, clientBuilderId, ignoreCertificateErrors, connectionTimeout, readTimeout).getClient(null, null).getCurrentUser(); // return FormValidation.ok(Messages.connection_success()); // } catch (WebApplicationException e) { // return FormValidation.error(Messages.connection_error(e.getMessage())); // } catch (ProcessingException e) { // return FormValidation.error(Messages.connection_error(e.getCause().getMessage())); // } // } // // public ListBoxModel doFillApiTokenIdItems(@QueryParameter String url, @QueryParameter String apiTokenId) { // if (Jenkins.get().hasPermission(Item.CONFIGURE)) { // return new StandardListBoxModel() // .includeEmptyValue() // .includeMatchingAs(ACL.SYSTEM, // Jenkins.get(), // StandardCredentials.class, // URIRequirementBuilder.fromUri(url).build(), // new GitLabCredentialMatcher()) // .includeCurrentValue(apiTokenId); // } // return new StandardListBoxModel(); // } // // public ListBoxModel doFillClientBuilderIdItems() { // ListBoxModel model = new ListBoxModel(); // for (GitLabClientBuilder builder : getAllGitLabClientBuilders()) { // model.add(builder.id()); // } // // return model; // } // }
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.connection.GitLabConnection.DescriptorImpl; import hudson.util.FormValidation; import hudson.util.Secret; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.socket.PortFactory;
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); } } }); server.setHandler(handlerCollection); server.start(); } @AfterClass public static void stopJetty() throws Exception { server.stop(); } @Before public void setup() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN_ID))); } } } @Test public void doCheckConnection_ignoreCertificateErrors() {
// Path: src/main/java/com/dabsquared/gitlabjenkins/connection/GitLabConnection.java // @Extension // public static class DescriptorImpl extends Descriptor<GitLabConnection> { // public FormValidation doCheckName(@QueryParameter String id, @QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.name_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckUrl(@QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.url_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckApiTokenId(@QueryParameter String value) { // if (StringUtils.isEmptyOrNull(value)) { // return FormValidation.error(Messages.apiToken_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckConnectionTimeout(@QueryParameter Integer value) { // if (value == null) { // return FormValidation.error(Messages.connectionTimeout_required()); // } else { // return FormValidation.ok(); // } // } // // public FormValidation doCheckReadTimeout(@QueryParameter Integer value) { // if (value == null) { // return FormValidation.error(Messages.readTimeout_required()); // } else { // return FormValidation.ok(); // } // } // // @RequirePOST // @Restricted(DoNotUse.class) // WebOnly // public FormValidation doTestConnection(@QueryParameter String url, // @QueryParameter String apiTokenId, // @QueryParameter String clientBuilderId, // @QueryParameter boolean ignoreCertificateErrors, // @QueryParameter int connectionTimeout, // @QueryParameter int readTimeout) { // Jenkins.get().checkPermission(Jenkins.ADMINISTER); // try { // new GitLabConnection("", url, apiTokenId, clientBuilderId, ignoreCertificateErrors, connectionTimeout, readTimeout).getClient(null, null).getCurrentUser(); // return FormValidation.ok(Messages.connection_success()); // } catch (WebApplicationException e) { // return FormValidation.error(Messages.connection_error(e.getMessage())); // } catch (ProcessingException e) { // return FormValidation.error(Messages.connection_error(e.getCause().getMessage())); // } // } // // public ListBoxModel doFillApiTokenIdItems(@QueryParameter String url, @QueryParameter String apiTokenId) { // if (Jenkins.get().hasPermission(Item.CONFIGURE)) { // return new StandardListBoxModel() // .includeEmptyValue() // .includeMatchingAs(ACL.SYSTEM, // Jenkins.get(), // StandardCredentials.class, // URIRequirementBuilder.fromUri(url).build(), // new GitLabCredentialMatcher()) // .includeCurrentValue(apiTokenId); // } // return new StandardListBoxModel(); // } // // public ListBoxModel doFillClientBuilderIdItems() { // ListBoxModel model = new ListBoxModel(); // for (GitLabClientBuilder builder : getAllGitLabClientBuilders()) { // model.add(builder.id()); // } // // return model; // } // } // Path: src/test/java/com/dabsquared/gitlabjenkins/connection/GitLabConnectionConfigSSLTest.java import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.SystemCredentialsProvider; import com.cloudbees.plugins.credentials.domains.Domain; import com.dabsquared.gitlabjenkins.connection.GitLabConnection.DescriptorImpl; import hudson.util.FormValidation; import hudson.util.Secret; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jenkins.model.Jenkins; import org.eclipse.jetty.http.HttpVersion; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.mockserver.socket.PortFactory; public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); } } }); server.setHandler(handlerCollection); server.start(); } @AfterClass public static void stopJetty() throws Exception { server.stop(); } @Before public void setup() throws IOException { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); credentialsStore.addCredentials(domains.get(0), new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN_ID))); } } } @Test public void doCheckConnection_ignoreCertificateErrors() {
GitLabConnection.DescriptorImpl descriptor = (DescriptorImpl) jenkins.jenkins.getDescriptor(GitLabConnection.class);
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/VariableTable.java
// Path: src/java/net/rkoubou/kspparser/analyzer/Variable.java // public class Variable extends SymbolDefinition // { // /** 元となるASTノード */ // public final ASTVariableDeclaration astNode; // // /** 配列型の場合の要素数 */ // public int arraySize = 0; // // /** // * UI型変数の場合に値がセットされる(シンボル収集フェーズ) // * 初期値は null // * @see SymbolCollector // */ // public UIType uiTypeInfo = null; // // /** コンスタントプールに格納される場合のインデックス番号 */ // public int constantIndex = -1; // // /** on init 内で使用可能な変数かどうか(外部低ファイルから読み込むビルトイン変数用) */ // public boolean availableOnInit = true; // // /** 単項演算子により生成、かつリテラル値 */ // public boolean constantValueWithSingleOperator = false; // // /** // * Ctor. // */ // public Variable( ASTVariableDeclaration node ) // { // copy( node.symbol, this ); // this.astNode = node; // this.symbolType = SymbolType.Variable; // } // // /** // * 変数の型データからKSP文法の変数名表現に変換する // */ // public String getVariableName() // { // // 1文字目に型情報の文字を含んでいる場合はそのまま返す // if( AnalyzerConstants.REGEX_TYPE_PREFIX.matcher( getName() ).find() ) // { // return getName(); // } // return toKSPTypeCharacter() + getName(); // } // // /** // * 変数の型データからKSP文法の変数名表現に変換する // */ // @Override // public String toString() // { // return getVariableName(); // } // } // // Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.analyzer.Variable; import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration;
* 変数テーブルへの追加 */ @Override public boolean add( ASTVariableDeclaration decl ) { Variable v = new Variable( decl ); return add( v ); } /** * 変数テーブルへの追加 */ public boolean add( Variable v ) { final String name = v.getName(); if( table.containsKey( name ) ) { // 宣言済み return false; } if( v.isConstant() ) { v.index = -1; } else { v.index = index; index++; }
// Path: src/java/net/rkoubou/kspparser/analyzer/Variable.java // public class Variable extends SymbolDefinition // { // /** 元となるASTノード */ // public final ASTVariableDeclaration astNode; // // /** 配列型の場合の要素数 */ // public int arraySize = 0; // // /** // * UI型変数の場合に値がセットされる(シンボル収集フェーズ) // * 初期値は null // * @see SymbolCollector // */ // public UIType uiTypeInfo = null; // // /** コンスタントプールに格納される場合のインデックス番号 */ // public int constantIndex = -1; // // /** on init 内で使用可能な変数かどうか(外部低ファイルから読み込むビルトイン変数用) */ // public boolean availableOnInit = true; // // /** 単項演算子により生成、かつリテラル値 */ // public boolean constantValueWithSingleOperator = false; // // /** // * Ctor. // */ // public Variable( ASTVariableDeclaration node ) // { // copy( node.symbol, this ); // this.astNode = node; // this.symbolType = SymbolType.Variable; // } // // /** // * 変数の型データからKSP文法の変数名表現に変換する // */ // public String getVariableName() // { // // 1文字目に型情報の文字を含んでいる場合はそのまま返す // if( AnalyzerConstants.REGEX_TYPE_PREFIX.matcher( getName() ).find() ) // { // return getName(); // } // return toKSPTypeCharacter() + getName(); // } // // /** // * 変数の型データからKSP文法の変数名表現に変換する // */ // @Override // public String toString() // { // return getVariableName(); // } // } // // Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/VariableTable.java import net.rkoubou.kspparser.analyzer.Variable; import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration; * 変数テーブルへの追加 */ @Override public boolean add( ASTVariableDeclaration decl ) { Variable v = new Variable( decl ); return add( v ); } /** * 変数テーブルへの追加 */ public boolean add( Variable v ) { final String name = v.getName(); if( table.containsKey( name ) ) { // 宣言済み return false; } if( v.isConstant() ) { v.index = -1; } else { v.index = index; index++; }
v.symbolType = SymbolType.Variable;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/Argument.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration;
/* ========================================================================= Argument.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * 引数の変数の中間表現を示す */ public class Argument extends Variable { /** on init 内で変数宣言されている必要があるかどうか(例:on ui_control コールバック) */ public boolean requireDeclarationOnInit = false; /** * Ctor. */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/Argument.java import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration; /* ========================================================================= Argument.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * 引数の変数の中間表現を示す */ public class Argument extends Variable { /** on init 内で変数宣言されている必要があるかどうか(例:on ui_control コールバック) */ public boolean requireDeclarationOnInit = false; /** * Ctor. */
public Argument( ASTVariableDeclaration node )
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/UserFunction.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTUserFunctionDeclaration.java // public // class ASTUserFunctionDeclaration extends SimpleNode { // public ASTUserFunctionDeclaration(int id) { // super(id); // } // // public ASTUserFunctionDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.javacc.generated.ASTUserFunctionDeclaration;
/* ========================================================================= UserFunction.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * ユーザー定義関数の中間表現を示す */ public class UserFunction extends SymbolDefinition { /** 元となるASTノード */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTUserFunctionDeclaration.java // public // class ASTUserFunctionDeclaration extends SimpleNode { // public ASTUserFunctionDeclaration(int id) { // super(id); // } // // public ASTUserFunctionDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/UserFunction.java import net.rkoubou.kspparser.javacc.generated.ASTUserFunctionDeclaration; /* ========================================================================= UserFunction.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * ユーザー定義関数の中間表現を示す */ public class UserFunction extends SymbolDefinition { /** 元となるASTノード */
public final ASTUserFunctionDeclaration astNode;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/CommandTable.java
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallCommand.java // public // class ASTCallCommand extends SimpleNode { // public ASTCallCommand(int id) { // super(id); // } // // public ASTCallCommand(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTCallCommand;
/* ========================================================================= CommandTable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPコマンド定義テーブル */ public class CommandTable extends SymbolTable<ASTCallCommand, Command> implements AnalyzerConstants { /** * ctor */ public CommandTable() { super(); } /** * ctor */ public CommandTable( CommandTable parent ) { super( parent ); } /** * ctor */ public CommandTable( CommandTable parent, int startIndex ) { super( parent, startIndex ); } /** * ユーザー定義関数テーブルへの追加 */ @Override public boolean add( ASTCallCommand decl ) { return add( new Command( decl ) ); } /** * コマンドテーブルへの追加 */ public boolean add( Command c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++;
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallCommand.java // public // class ASTCallCommand extends SimpleNode { // public ASTCallCommand(int id) { // super(id); // } // // public ASTCallCommand(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/CommandTable.java import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTCallCommand; /* ========================================================================= CommandTable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPコマンド定義テーブル */ public class CommandTable extends SymbolTable<ASTCallCommand, Command> implements AnalyzerConstants { /** * ctor */ public CommandTable() { super(); } /** * ctor */ public CommandTable( CommandTable parent ) { super( parent ); } /** * ctor */ public CommandTable( CommandTable parent, int startIndex ) { super( parent, startIndex ); } /** * ユーザー定義関数テーブルへの追加 */ @Override public boolean add( ASTCallCommand decl ) { return add( new Command( decl ) ); } /** * コマンドテーブルへの追加 */ public boolean add( Command c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++;
c.symbolType = SymbolType.Command;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/util/KSPParserProperties.java
// Path: src/java/net/rkoubou/kspparser/ApplicationConstants.java // public class ApplicationConstants // { // /** VM引数 -D dataフォルダの明示的指定時のプロパティ名 */ // static public final String SYSTEM_PROPERTY_DATADIR = "kspparser.datadir"; // // /** VM引数 -Dkspparser.datadir がなかった時のデフォルトの dataフォルダの相対パス */ // static public final String DEFAULT_DATADIR = "data"; // // /** */ // static public String DATA_DIR; // // /** // * static initializer // */ // static // { // String dir = System.getProperty( SYSTEM_PROPERTY_DATADIR ); // if( dir == null ) // { // DATA_DIR = DEFAULT_DATADIR; // } // else // { // DATA_DIR = dir; // } // } // // /** // * ctor. // */ // private ApplicationConstants(){} // // }
import java.io.IOException; import java.io.InputStream; import java.util.Properties; import net.rkoubou.kspparser.ApplicationConstants;
/* ========================================================================= KSPParserProperties.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.util; public class KSPParserProperties { /** プロパティ格納先 */ protected Properties properties = new Properties(); /** * ctor. */ public KSPParserProperties( String path ) throws IOException {
// Path: src/java/net/rkoubou/kspparser/ApplicationConstants.java // public class ApplicationConstants // { // /** VM引数 -D dataフォルダの明示的指定時のプロパティ名 */ // static public final String SYSTEM_PROPERTY_DATADIR = "kspparser.datadir"; // // /** VM引数 -Dkspparser.datadir がなかった時のデフォルトの dataフォルダの相対パス */ // static public final String DEFAULT_DATADIR = "data"; // // /** */ // static public String DATA_DIR; // // /** // * static initializer // */ // static // { // String dir = System.getProperty( SYSTEM_PROPERTY_DATADIR ); // if( dir == null ) // { // DATA_DIR = DEFAULT_DATADIR; // } // else // { // DATA_DIR = dir; // } // } // // /** // * ctor. // */ // private ApplicationConstants(){} // // } // Path: src/java/net/rkoubou/kspparser/util/KSPParserProperties.java import java.io.IOException; import java.io.InputStream; import java.util.Properties; import net.rkoubou.kspparser.ApplicationConstants; /* ========================================================================= KSPParserProperties.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.util; public class KSPParserProperties { /** プロパティ格納先 */ protected Properties properties = new Properties(); /** * ctor. */ public KSPParserProperties( String path ) throws IOException {
this( path, ApplicationConstants.DATA_DIR );
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/PreProcessorSymbol.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorDefine.java // public // class ASTPreProcessorDefine extends SimpleNode { // public ASTPreProcessorDefine(int id) { // super(id); // } // // public ASTPreProcessorDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorDefine;
/* ========================================================================= PreProcessorSymbol.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * プリプロセッサで定義したシンボルの中間表現を示す */ public class PreProcessorSymbol extends SymbolDefinition { /** 元となるASTノード */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorDefine.java // public // class ASTPreProcessorDefine extends SimpleNode { // public ASTPreProcessorDefine(int id) { // super(id); // } // // public ASTPreProcessorDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/PreProcessorSymbol.java import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorDefine; /* ========================================================================= PreProcessorSymbol.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * プリプロセッサで定義したシンボルの中間表現を示す */ public class PreProcessorSymbol extends SymbolDefinition { /** 元となるASTノード */
public final ASTPreProcessorDefine astNode;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/KSPLanguageLimitations.java
// Path: src/java/net/rkoubou/kspparser/util/KSPParserProperties.java // public class KSPParserProperties // { // /** プロパティ格納先 */ // protected Properties properties = new Properties(); // // /** // * ctor. // */ // public KSPParserProperties( String path ) throws IOException // { // this( path, ApplicationConstants.DATA_DIR ); // } // // /** // * ctor. // */ // public KSPParserProperties( String path, String dir ) throws IOException // { // String propertiesPath = path; // InputStream in = null; // if( dir == null ) // { // dir = ApplicationConstants.DEFAULT_DATADIR; // } // propertiesPath = dir + "/" + path; // // try // { // properties = UTF8Properties.load( propertiesPath ); // } // finally // { // StreamCloser.close( in ); // } // } // // /** // * Propertiesインスタンスを取得する // */ // public Properties get() // { // return properties; // } // // /** // * 指定されたキーから値の取得を試みる // */ // public String getInt( String key, String defaultValue ) // { // return properties.getProperty( key, defaultValue ).trim(); // } // // /** // * 指定されたキーの値が整数の場合、値を int として取得を試みる // */ // public int getInt( String key, int defaultValue ) // { // String str = properties.getProperty( key, "" ).trim(); // if( str.length() == 0 ) // { // return defaultValue; // } // return Integer.parseInt( str ); // } // }
import net.rkoubou.kspparser.util.KSPParserProperties;
/* ========================================================================= KSPLanguageLimitations.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPの言語仕様、バグなどに起因するパラメータ類の限界値の定義 */ public class KSPLanguageLimitations { /** 定義ファイルパス */ static private final String PROPERTIES_PATH = "ksp_limitations.properties"; /** コールバック・ユーザー関数の行数オーバーフローのしきい値 */ static public int OVERFLOW_LINES; /** 配列変数宣言時の要素数の上限 */ static public int MAX_KSP_ARRAY_SIZE; static { try {
// Path: src/java/net/rkoubou/kspparser/util/KSPParserProperties.java // public class KSPParserProperties // { // /** プロパティ格納先 */ // protected Properties properties = new Properties(); // // /** // * ctor. // */ // public KSPParserProperties( String path ) throws IOException // { // this( path, ApplicationConstants.DATA_DIR ); // } // // /** // * ctor. // */ // public KSPParserProperties( String path, String dir ) throws IOException // { // String propertiesPath = path; // InputStream in = null; // if( dir == null ) // { // dir = ApplicationConstants.DEFAULT_DATADIR; // } // propertiesPath = dir + "/" + path; // // try // { // properties = UTF8Properties.load( propertiesPath ); // } // finally // { // StreamCloser.close( in ); // } // } // // /** // * Propertiesインスタンスを取得する // */ // public Properties get() // { // return properties; // } // // /** // * 指定されたキーから値の取得を試みる // */ // public String getInt( String key, String defaultValue ) // { // return properties.getProperty( key, defaultValue ).trim(); // } // // /** // * 指定されたキーの値が整数の場合、値を int として取得を試みる // */ // public int getInt( String key, int defaultValue ) // { // String str = properties.getProperty( key, "" ).trim(); // if( str.length() == 0 ) // { // return defaultValue; // } // return Integer.parseInt( str ); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/KSPLanguageLimitations.java import net.rkoubou.kspparser.util.KSPParserProperties; /* ========================================================================= KSPLanguageLimitations.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPの言語仕様、バグなどに起因するパラメータ類の限界値の定義 */ public class KSPLanguageLimitations { /** 定義ファイルパス */ static private final String PROPERTIES_PATH = "ksp_limitations.properties"; /** コールバック・ユーザー関数の行数オーバーフローのしきい値 */ static public int OVERFLOW_LINES; /** 配列変数宣言時の要素数の上限 */ static public int MAX_KSP_ARRAY_SIZE; static { try {
KSPParserProperties p = new KSPParserProperties( PROPERTIES_PATH );
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/Position.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/Token.java // public class Token implements java.io.Serializable { // // /** // * The version identifier for this Serializable class. // * Increment only if the <i>serialized</i> form of the // * class changes. // */ // private static final long serialVersionUID = 1L; // // /** // * An integer that describes the kind of this token. This numbering // * system is determined by JavaCCParser, and a table of these numbers is // * stored in the file ...Constants.java. // */ // public int kind; // // /** The line number of the first character of this Token. */ // public int beginLine; // /** The column number of the first character of this Token. */ // public int beginColumn; // /** The line number of the last character of this Token. */ // public int endLine; // /** The column number of the last character of this Token. */ // public int endColumn; // // /** // * The string image of the token. // */ // public String image; // // /** // * A reference to the next regular (non-special) token from the input // * stream. If this is the last token from the input stream, or if the // * token manager has not read tokens beyond this one, this field is // * set to null. This is true only if this token is also a regular // * token. Otherwise, see below for a description of the contents of // * this field. // */ // public Token next; // // /** // * This field is used to access special tokens that occur prior to this // * token, but after the immediately preceding regular (non-special) token. // * If there are no such special tokens, this field is set to null. // * When there are more than one such special token, this field refers // * to the last of these special tokens, which in turn refers to the next // * previous special token through its specialToken field, and so on // * until the first special token (whose specialToken field is null). // * The next fields of special tokens refer to other special tokens that // * immediately follow it (without an intervening regular token). If there // * is no such token, this field is null. // */ // public Token specialToken; // // /** // * An optional attribute value of the Token. // * Tokens which are not used as syntactic sugar will often contain // * meaningful values that will be used later on by the compiler or // * interpreter. This attribute value is often different from the image. // * Any subclass of Token that actually wants to return a non-null value can // * override this method as appropriate. // */ // public Object getValue() { // return null; // } // // /** // * No-argument constructor // */ // public Token() {} // // /** // * Constructs a new token for the specified Image. // */ // public Token(int kind) // { // this(kind, null); // } // // /** // * Constructs a new token for the specified Image and Kind. // */ // public Token(int kind, String image) // { // this.kind = kind; // this.image = image; // } // // /** // * Returns the image. // */ // public String toString() // { // return image; // } // // /** // * Returns a new Token object, by default. However, if you want, you // * can create and return subclass objects based on the value of ofKind. // * Simply add the cases to the switch for all those special cases. // * For example, if you have a subclass of Token called IDToken that // * you want to create if ofKind is ID, simply add something like : // * // * case MyParserConstants.ID : return new IDToken(ofKind, image); // * // * to the following switch statement. Then you can cast matchedToken // * variable to the appropriate type and use sit in your lexical actions. // */ // public static Token newToken(int ofKind, String image) // { // switch(ofKind) // { // default : return new Token(ofKind, image); // } // } // // public static Token newToken(int ofKind) // { // return newToken(ofKind, null); // } // // }
import net.rkoubou.kspparser.javacc.generated.Token;
/* ========================================================================= Position.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * シンボル等の行番号、列を格納する */ public class Position { public int beginLine = 0; public int endLine = 0; public int beginColumn = 0; public int endColumn = 0; /** * ctor. */ public Position(){} /** * コピーコンストラクタ */ public Position( Position src ) { copy( src, this ); } /** * ディープコピー */ static public void copy( Position src, Position dest ) { dest.beginLine = src.beginLine; dest.endLine = src.endLine; dest.beginColumn = src.beginColumn; dest.endColumn = src.endColumn; } /** * ディープコピー */ public void copy( Position src ) { this.beginLine = src.beginLine; this.endLine = src.endLine; this.beginColumn = src.beginColumn; this.endColumn = src.endColumn; } /** * Tokenからの値のディープコピー */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/Token.java // public class Token implements java.io.Serializable { // // /** // * The version identifier for this Serializable class. // * Increment only if the <i>serialized</i> form of the // * class changes. // */ // private static final long serialVersionUID = 1L; // // /** // * An integer that describes the kind of this token. This numbering // * system is determined by JavaCCParser, and a table of these numbers is // * stored in the file ...Constants.java. // */ // public int kind; // // /** The line number of the first character of this Token. */ // public int beginLine; // /** The column number of the first character of this Token. */ // public int beginColumn; // /** The line number of the last character of this Token. */ // public int endLine; // /** The column number of the last character of this Token. */ // public int endColumn; // // /** // * The string image of the token. // */ // public String image; // // /** // * A reference to the next regular (non-special) token from the input // * stream. If this is the last token from the input stream, or if the // * token manager has not read tokens beyond this one, this field is // * set to null. This is true only if this token is also a regular // * token. Otherwise, see below for a description of the contents of // * this field. // */ // public Token next; // // /** // * This field is used to access special tokens that occur prior to this // * token, but after the immediately preceding regular (non-special) token. // * If there are no such special tokens, this field is set to null. // * When there are more than one such special token, this field refers // * to the last of these special tokens, which in turn refers to the next // * previous special token through its specialToken field, and so on // * until the first special token (whose specialToken field is null). // * The next fields of special tokens refer to other special tokens that // * immediately follow it (without an intervening regular token). If there // * is no such token, this field is null. // */ // public Token specialToken; // // /** // * An optional attribute value of the Token. // * Tokens which are not used as syntactic sugar will often contain // * meaningful values that will be used later on by the compiler or // * interpreter. This attribute value is often different from the image. // * Any subclass of Token that actually wants to return a non-null value can // * override this method as appropriate. // */ // public Object getValue() { // return null; // } // // /** // * No-argument constructor // */ // public Token() {} // // /** // * Constructs a new token for the specified Image. // */ // public Token(int kind) // { // this(kind, null); // } // // /** // * Constructs a new token for the specified Image and Kind. // */ // public Token(int kind, String image) // { // this.kind = kind; // this.image = image; // } // // /** // * Returns the image. // */ // public String toString() // { // return image; // } // // /** // * Returns a new Token object, by default. However, if you want, you // * can create and return subclass objects based on the value of ofKind. // * Simply add the cases to the switch for all those special cases. // * For example, if you have a subclass of Token called IDToken that // * you want to create if ofKind is ID, simply add something like : // * // * case MyParserConstants.ID : return new IDToken(ofKind, image); // * // * to the following switch statement. Then you can cast matchedToken // * variable to the appropriate type and use sit in your lexical actions. // */ // public static Token newToken(int ofKind, String image) // { // switch(ofKind) // { // default : return new Token(ofKind, image); // } // } // // public static Token newToken(int ofKind) // { // return newToken(ofKind, null); // } // // } // Path: src/java/net/rkoubou/kspparser/analyzer/Position.java import net.rkoubou.kspparser.javacc.generated.Token; /* ========================================================================= Position.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * シンボル等の行番号、列を格納する */ public class Position { public int beginLine = 0; public int endLine = 0; public int beginColumn = 0; public int endColumn = 0; /** * ctor. */ public Position(){} /** * コピーコンストラクタ */ public Position( Position src ) { copy( src, this ); } /** * ディープコピー */ static public void copy( Position src, Position dest ) { dest.beginLine = src.beginLine; dest.endLine = src.endLine; dest.beginColumn = src.beginColumn; dest.endColumn = src.endColumn; } /** * ディープコピー */ public void copy( Position src ) { this.beginLine = src.beginLine; this.endLine = src.endLine; this.beginColumn = src.beginColumn; this.endColumn = src.endColumn; } /** * Tokenからの値のディープコピー */
static public void copy( Token src, Position dest )
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/CallbackTable.java
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallbackDeclaration.java // public // class ASTCallbackDeclaration extends SimpleNode { // public ASTCallbackDeclaration(int id) { // super(id); // } // // public ASTCallbackDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // }
import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTCallbackDeclaration; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants;
*/ public boolean add( Callback c, String name ) { if( table.containsKey( name ) ) { //-------------------------------------------------------------------------- // 宣言済み //-------------------------------------------------------------------------- { Callback p = table.get( name ); //-------------------------------------------------------------------------- // 外部定義ファイルで取り込んだシンボルがソースコード上で宣言されているかどうか // 初回の検出時はフラグを立てるだけ //-------------------------------------------------------------------------- if( p.reserved && !p.declared ) { p.declared = true; } //-------------------------------------------------------------------------- // 多重定義を許可されていないコールバックには追加不可 //-------------------------------------------------------------------------- if( !p.isAllowDuplicate() ) { return false; } return true; } } c.index = index; index++;
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallbackDeclaration.java // public // class ASTCallbackDeclaration extends SimpleNode { // public ASTCallbackDeclaration(int id) { // super(id); // } // // public ASTCallbackDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // } // Path: src/java/net/rkoubou/kspparser/analyzer/CallbackTable.java import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTCallbackDeclaration; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants; */ public boolean add( Callback c, String name ) { if( table.containsKey( name ) ) { //-------------------------------------------------------------------------- // 宣言済み //-------------------------------------------------------------------------- { Callback p = table.get( name ); //-------------------------------------------------------------------------- // 外部定義ファイルで取り込んだシンボルがソースコード上で宣言されているかどうか // 初回の検出時はフラグを立てるだけ //-------------------------------------------------------------------------- if( p.reserved && !p.declared ) { p.declared = true; } //-------------------------------------------------------------------------- // 多重定義を許可されていないコールバックには追加不可 //-------------------------------------------------------------------------- if( !p.isAllowDuplicate() ) { return false; } return true; } } c.index = index; index++;
c.symbolType = SymbolType.Callback;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/UserFunctionTable.java
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTUserFunctionDeclaration.java // public // class ASTUserFunctionDeclaration extends SimpleNode { // public ASTUserFunctionDeclaration(int id) { // super(id); // } // // public ASTUserFunctionDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTUserFunctionDeclaration;
/* ========================================================================= UserFunctionTable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * ユーザー定義関数テーブル */ public class UserFunctionTable extends SymbolTable<ASTUserFunctionDeclaration, UserFunction> implements AnalyzerConstants { /** * ctor */ public UserFunctionTable() { super(); } /** * ctor */ public UserFunctionTable( UserFunctionTable parent ) { super( parent ); } /** * ctor */ public UserFunctionTable( UserFunctionTable parent, int startIndex ) { super( parent, startIndex ); } /** * ユーザー定義関数テーブルへの追加 */ @Override public boolean add( ASTUserFunctionDeclaration decl ) { return add( new UserFunction( decl ) ); } /** * ユーザー定義関数テーブルへの追加 */ public boolean add( UserFunction c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++;
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTUserFunctionDeclaration.java // public // class ASTUserFunctionDeclaration extends SimpleNode { // public ASTUserFunctionDeclaration(int id) { // super(id); // } // // public ASTUserFunctionDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/UserFunctionTable.java import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTUserFunctionDeclaration; /* ========================================================================= UserFunctionTable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * ユーザー定義関数テーブル */ public class UserFunctionTable extends SymbolTable<ASTUserFunctionDeclaration, UserFunction> implements AnalyzerConstants { /** * ctor */ public UserFunctionTable() { super(); } /** * ctor */ public UserFunctionTable( UserFunctionTable parent ) { super( parent ); } /** * ctor */ public UserFunctionTable( UserFunctionTable parent, int startIndex ) { super( parent, startIndex ); } /** * ユーザー定義関数テーブルへの追加 */ @Override public boolean add( ASTUserFunctionDeclaration decl ) { return add( new UserFunction( decl ) ); } /** * ユーザー定義関数テーブルへの追加 */ public boolean add( UserFunction c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++;
c.symbolType = SymbolType.UserFunction;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/util/table/SeparatedTextParser.java
// Path: src/java/net/rkoubou/kspparser/util/StreamCloser.java // public class StreamCloser // { // /** // * ctor. // */ // private StreamCloser(){} // // /** // * 指定されたストリームのクローズ // */ // static public void close( InputStream in ) // { // try{ in.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( OutputStream out ) // { // try{ out.flush(); } catch( Throwable e ){} // try{ out.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( Reader r ) // { // try{ r.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( Writer w ) // { // try{ w.flush(); } catch( Throwable e ){} // try{ w.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( PrintStream ps ) // { // try{ ps.flush(); } catch( Throwable e ){} // try{ ps.close(); } catch( Throwable e ){} // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Pattern; import net.rkoubou.kspparser.util.StreamCloser;
} /** * 指定された入力ストリームからパースを実行する */ public void parse( InputStream in ) throws IOException { BufferedReader br = null; try { String line; br = new BufferedReader( new InputStreamReader( in, encoding ) ); while( ( line = br.readLine() ) != null ) { boolean skip; String[] split; line = line.trim(); skip = REGEX_LINECOMMENT.matcher( line ).find(); if( skip ) { continue; } split = line.split( delimiter ); table.add( parseLine( line, split ) ); Math.max( maxColumnsNum, split.length ); } } finally {
// Path: src/java/net/rkoubou/kspparser/util/StreamCloser.java // public class StreamCloser // { // /** // * ctor. // */ // private StreamCloser(){} // // /** // * 指定されたストリームのクローズ // */ // static public void close( InputStream in ) // { // try{ in.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( OutputStream out ) // { // try{ out.flush(); } catch( Throwable e ){} // try{ out.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( Reader r ) // { // try{ r.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( Writer w ) // { // try{ w.flush(); } catch( Throwable e ){} // try{ w.close(); } catch( Throwable e ){} // } // // /** // * 指定されたストリームのクローズ // */ // static public void close( PrintStream ps ) // { // try{ ps.flush(); } catch( Throwable e ){} // try{ ps.close(); } catch( Throwable e ){} // } // } // Path: src/java/net/rkoubou/kspparser/util/table/SeparatedTextParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.regex.Pattern; import net.rkoubou.kspparser.util.StreamCloser; } /** * 指定された入力ストリームからパースを実行する */ public void parse( InputStream in ) throws IOException { BufferedReader br = null; try { String line; br = new BufferedReader( new InputStreamReader( in, encoding ) ); while( ( line = br.readLine() ) != null ) { boolean skip; String[] split; line = line.trim(); skip = REGEX_LINECOMMENT.matcher( line ).find(); if( skip ) { continue; } split = line.split( delimiter ); table.add( parseLine( line, split ) ); Math.max( maxColumnsNum, split.length ); } } finally {
StreamCloser.close( br );
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/Variable.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // }
import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration;
/* ========================================================================= Variable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPの値、変数の中間表現を示す */ public class Variable extends SymbolDefinition { /** 元となるASTノード */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTVariableDeclaration.java // public // class ASTVariableDeclaration extends SimpleNode { // public ASTVariableDeclaration(int id) { // super(id); // } // // public ASTVariableDeclaration(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // Path: src/java/net/rkoubou/kspparser/analyzer/Variable.java import net.rkoubou.kspparser.javacc.generated.ASTVariableDeclaration; /* ========================================================================= Variable.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * KSPの値、変数の中間表現を示す */ public class Variable extends SymbolDefinition { /** 元となるASTノード */
public final ASTVariableDeclaration astNode;
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/PreProcessorSymbolTable.java
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorDefine.java // public // class ASTPreProcessorDefine extends SimpleNode { // public ASTPreProcessorDefine(int id) { // super(id); // } // // public ASTPreProcessorDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorUnDefine.java // public // class ASTPreProcessorUnDefine extends SimpleNode { // public ASTPreProcessorUnDefine(int id) { // super(id); // } // // public ASTPreProcessorUnDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // }
import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorDefine; import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorUnDefine; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants;
/** * プリプロセッサシンボルテーブルへの追加 */ @Override public boolean add( ASTPreProcessorDefine decl ) { return add( new PreProcessorSymbol( decl ) ); } /** * プリプロセッサシンボルテーブルへの追加 */ public boolean add( PreProcessorSymbol c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++; c.symbolType = SymbolType.UserFunction; table.put( name, c ); return true; } /** * UNDEFによるプリプロセッサシンボルテーブルからの除去 */
// Path: src/java/net/rkoubou/kspparser/analyzer/SymbolDefinition.java // public enum SymbolType // { // Unknown, // Callback, // Command, // UserFunction, // Variable, // Literal, // Expression, // PreprocessorSymbol, // }; // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorDefine.java // public // class ASTPreProcessorDefine extends SimpleNode { // public ASTPreProcessorDefine(int id) { // super(id); // } // // public ASTPreProcessorDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTPreProcessorUnDefine.java // public // class ASTPreProcessorUnDefine extends SimpleNode { // public ASTPreProcessorUnDefine(int id) { // super(id); // } // // public ASTPreProcessorUnDefine(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // } // Path: src/java/net/rkoubou/kspparser/analyzer/PreProcessorSymbolTable.java import net.rkoubou.kspparser.analyzer.SymbolDefinition.SymbolType; import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorDefine; import net.rkoubou.kspparser.javacc.generated.ASTPreProcessorUnDefine; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants; /** * プリプロセッサシンボルテーブルへの追加 */ @Override public boolean add( ASTPreProcessorDefine decl ) { return add( new PreProcessorSymbol( decl ) ); } /** * プリプロセッサシンボルテーブルへの追加 */ public boolean add( PreProcessorSymbol c ) { final String name = c.getName(); if( table.containsKey( name ) ) { return false; } c.index = index; index++; c.symbolType = SymbolType.UserFunction; table.put( name, c ); return true; } /** * UNDEFによるプリプロセッサシンボルテーブルからの除去 */
public boolean remove( ASTPreProcessorUnDefine undef )
r-koubou/KSPSyntaxParser
src/java/net/rkoubou/kspparser/analyzer/Command.java
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallCommand.java // public // class ASTCallCommand extends SimpleNode { // public ASTCallCommand(int id) { // super(id); // } // // public ASTCallCommand(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // }
import java.util.ArrayList; import java.util.HashMap; import net.rkoubou.kspparser.javacc.generated.ASTCallCommand; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants;
/* ========================================================================= Command.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * コマンドの中間表現を示す */ public class Command extends SymbolDefinition implements KSPParserTreeConstants { /** 元となるASTノード */
// Path: src/java/net/rkoubou/kspparser/javacc/generated/ASTCallCommand.java // public // class ASTCallCommand extends SimpleNode { // public ASTCallCommand(int id) { // super(id); // } // // public ASTCallCommand(KSPParser p, int id) { // super(p, id); // } // // // /** Accept the visitor. **/ // public Object jjtAccept(KSPParserVisitor visitor, Object data) { // // return // visitor.visit(this, data); // } // } // // Path: src/java/net/rkoubou/kspparser/javacc/generated/KSPParserTreeConstants.java // public interface KSPParserTreeConstants // { // public int JJTROOTNODE = 0; // public int JJTVOID = 1; // public int JJTVARIABLEDECLARATION = 2; // public int JJTVARIABLEINITIALIZER = 3; // public int JJTPRIMITIVEINITITALIZER = 4; // public int JJTARRAYINITIALIZER = 5; // public int JJTCALLBACKDECLARATION = 6; // public int JJTCALLBACKARGUMENTLIST = 7; // public int JJTUSERFUNCTIONDECLARATION = 8; // public int JJTBLOCK = 9; // public int JJTPREPROCESSORDEFINE = 10; // public int JJTPREPROCESSORUNDEFINE = 11; // public int JJTPREPROCESSORIFDEFINED = 12; // public int JJTPREPROCESSORIFUNDEFINED = 13; // public int JJTIFSTATEMENT = 14; // public int JJTSELECTSTATEMENT = 15; // public int JJTCASESTATEMENT = 16; // public int JJTCASECONDITION = 17; // public int JJTWHILESTATEMENT = 18; // public int JJTCALLUSERFUNCTIONSTATEMENT = 19; // public int JJTASSIGNMENT = 20; // public int JJTCONDITIONALOR = 21; // public int JJTCONDITIONALAND = 22; // public int JJTSTRADD = 23; // public int JJTBITWISEOR = 24; // public int JJTBITWISEAND = 25; // public int JJTEQUAL = 26; // public int JJTNOTEQUAL = 27; // public int JJTLT = 28; // public int JJTGT = 29; // public int JJTLE = 30; // public int JJTGE = 31; // public int JJTADD = 32; // public int JJTSUB = 33; // public int JJTMUL = 34; // public int JJTDIV = 35; // public int JJTMOD = 36; // public int JJTNEG = 37; // public int JJTNOT = 38; // public int JJTLOGICALNOT = 39; // public int JJTLITERAL = 40; // public int JJTREFVARIABLE = 41; // public int JJTARRAYINDEX = 42; // public int JJTCALLCOMMAND = 43; // public int JJTCOMMANDARGUMENTLIST = 44; // // // public String[] jjtNodeName = { // "RootNode", // "void", // "VariableDeclaration", // "VariableInitializer", // "PrimitiveInititalizer", // "ArrayInitializer", // "CallbackDeclaration", // "CallbackArgumentList", // "UserFunctionDeclaration", // "Block", // "PreProcessorDefine", // "PreProcessorUnDefine", // "PreProcessorIfDefined", // "PreProcessorIfUnDefined", // "IfStatement", // "SelectStatement", // "CaseStatement", // "CaseCondition", // "WhileStatement", // "CallUserFunctionStatement", // "Assignment", // "ConditionalOr", // "ConditionalAnd", // "StrAdd", // "BitwiseOr", // "BitwiseAnd", // "Equal", // "NotEqual", // "LT", // "GT", // "LE", // "GE", // "Add", // "Sub", // "Mul", // "Div", // "Mod", // "Neg", // "Not", // "LogicalNot", // "Literal", // "RefVariable", // "ArrayIndex", // "CallCommand", // "CommandArgumentList", // }; // } // Path: src/java/net/rkoubou/kspparser/analyzer/Command.java import java.util.ArrayList; import java.util.HashMap; import net.rkoubou.kspparser.javacc.generated.ASTCallCommand; import net.rkoubou.kspparser.javacc.generated.KSPParserTreeConstants; /* ========================================================================= Command.java Copyright (c) R-Koubou ======================================================================== */ package net.rkoubou.kspparser.analyzer; /** * コマンドの中間表現を示す */ public class Command extends SymbolDefinition implements KSPParserTreeConstants { /** 元となるASTノード */
public final ASTCallCommand astNode;
xbacinsk/White-box_cipher_java
src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/GTBox8to32.java
// Path: src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/Generator.java // public static class W08x32Coding extends W08xZZCODING{ // public W08x32Coding() { // super(4); // } // } // // Path: src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/Generator.java // public static class XORCODING { // public Coding xtb[]; // public final int width; // // public XORCODING(Coding[] xtb) { // this.xtb = xtb; // this.width = xtb.length; // } // // public XORCODING(int width) { // this.width = width; // this.xtb = new Coding[width]; // for(int i=0; i<width; i++){ // this.xtb[i] = new Coding(); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(int i=0; xtb!=null && i<width && xtb[i]!=null; i++){ // sb.append(i).append(':').append(xtb[i]).append(";\n"); // } // return "XORCODING{width=" + width + "; xtb=\n"+sb.toString()+"}"; // } // }
import cz.muni.fi.xklinec.whiteboxAES.generator.Generator.W08x32Coding; import cz.muni.fi.xklinec.whiteboxAES.generator.Generator.XORCODING;
/* * Copyright (c) 2014, Dusan (Ph4r05) Klinec, Petr Svenda * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package cz.muni.fi.xklinec.whiteboxAES.generator; /** * * @author ph4r05 */ public class GTBox8to32 implements IOEncoding{ protected Generator.W08x32Coding cod; public GTBox8to32() { super(); cod = new Generator.W08x32Coding(); } /** * Allocates IO encodings. * @param idx * @return */ public final int allocate(int idx){ idx = Generator.ALLOCW08x32CodingEx(cod, idx); return idx; } /** * Connects output of this box to input of XOR cascade. * Slot gives particular input slot in XOR cascade. * * @param c * @param slot */ public void connectOut(GXORCascade c, int slot){
// Path: src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/Generator.java // public static class W08x32Coding extends W08xZZCODING{ // public W08x32Coding() { // super(4); // } // } // // Path: src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/Generator.java // public static class XORCODING { // public Coding xtb[]; // public final int width; // // public XORCODING(Coding[] xtb) { // this.xtb = xtb; // this.width = xtb.length; // } // // public XORCODING(int width) { // this.width = width; // this.xtb = new Coding[width]; // for(int i=0; i<width; i++){ // this.xtb[i] = new Coding(); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(int i=0; xtb!=null && i<width && xtb[i]!=null; i++){ // sb.append(i).append(':').append(xtb[i]).append(";\n"); // } // return "XORCODING{width=" + width + "; xtb=\n"+sb.toString()+"}"; // } // } // Path: src/main/java/cz/muni/fi/xklinec/whiteboxAES/generator/GTBox8to32.java import cz.muni.fi.xklinec.whiteboxAES.generator.Generator.W08x32Coding; import cz.muni.fi.xklinec.whiteboxAES.generator.Generator.XORCODING; /* * Copyright (c) 2014, Dusan (Ph4r05) Klinec, Petr Svenda * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holders nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package cz.muni.fi.xklinec.whiteboxAES.generator; /** * * @author ph4r05 */ public class GTBox8to32 implements IOEncoding{ protected Generator.W08x32Coding cod; public GTBox8to32() { super(); cod = new Generator.W08x32Coding(); } /** * Allocates IO encodings. * @param idx * @return */ public final int allocate(int idx){ idx = Generator.ALLOCW08x32CodingEx(cod, idx); return idx; } /** * Connects output of this box to input of XOR cascade. * Slot gives particular input slot in XOR cascade. * * @param c * @param slot */ public void connectOut(GXORCascade c, int slot){
XORCODING[] xcod = c.getCod();
leelit/STUer-client
app/src/androidTest/java/com/leelit/stuer/dao/SellDaoTest.java
// Path: app/src/main/java/com/leelit/stuer/bean/SellInfo.java // public class SellInfo { // int id; // String name; // String tel; // String shortTel; // String wechat; // String datetime; // String imei; // String picAddress; // String state; // String uniquecode; // attention 这里的flag和carpool/date模块不同,唯一订单号,相当于前两个的uniquecode // String status; // on // off // // @Override // public String toString() { // return "SellInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", datetime='" + datetime + '\'' + // ", imei='" + imei + '\'' + // ", picAddress='" + picAddress + '\'' + // ", state='" + state + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", status='" + status + '\'' + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTel() { // return tel; // } // // public void setTel(String tel) { // this.tel = tel; // } // // public String getShortTel() { // return shortTel; // } // // public void setShortTel(String shortTel) { // this.shortTel = shortTel; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public String getImei() { // return imei; // } // // public void setImei(String imei) { // this.imei = imei; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // }
import android.util.Log; import com.leelit.stuer.bean.SellInfo; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List;
package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/16. */ public class SellDaoTest extends TestCase { private static final String[] keys = {"name", "tel", "shorttel", "wechat", "dt", "imei", "picaddress", "state", "flag", "status"}; public void testSave() throws Exception { SellDao sellDao = new SellDao();
// Path: app/src/main/java/com/leelit/stuer/bean/SellInfo.java // public class SellInfo { // int id; // String name; // String tel; // String shortTel; // String wechat; // String datetime; // String imei; // String picAddress; // String state; // String uniquecode; // attention 这里的flag和carpool/date模块不同,唯一订单号,相当于前两个的uniquecode // String status; // on // off // // @Override // public String toString() { // return "SellInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", datetime='" + datetime + '\'' + // ", imei='" + imei + '\'' + // ", picAddress='" + picAddress + '\'' + // ", state='" + state + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", status='" + status + '\'' + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTel() { // return tel; // } // // public void setTel(String tel) { // this.tel = tel; // } // // public String getShortTel() { // return shortTel; // } // // public void setShortTel(String shortTel) { // this.shortTel = shortTel; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public String getImei() { // return imei; // } // // public void setImei(String imei) { // this.imei = imei; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // } // Path: app/src/androidTest/java/com/leelit/stuer/dao/SellDaoTest.java import android.util.Log; import com.leelit.stuer.bean.SellInfo; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/16. */ public class SellDaoTest extends TestCase { private static final String[] keys = {"name", "tel", "shorttel", "wechat", "dt", "imei", "picaddress", "state", "flag", "status"}; public void testSave() throws Exception { SellDao sellDao = new SellDao();
List<SellInfo> list = new ArrayList<>();
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/carpool/model/CarpoolService.java
// Path: app/src/main/java/com/leelit/stuer/bean/CarpoolingInfo.java // public class CarpoolingInfo extends BaseInfo { // // String route; // // @Override // public String toString() { // return "CarpoolingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", route='" + route + '\'' + // '}'; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(route); // // } // // }
import com.leelit.stuer.bean.CarpoolingInfo; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.http.QueryMap; import rx.Observable;
package com.leelit.stuer.module_baseinfo.carpool.model; /** * Created by Leelit on 2016/3/8. */ public interface CarpoolService { @GET("query")
// Path: app/src/main/java/com/leelit/stuer/bean/CarpoolingInfo.java // public class CarpoolingInfo extends BaseInfo { // // String route; // // @Override // public String toString() { // return "CarpoolingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", route='" + route + '\'' + // '}'; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(route); // // } // // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/carpool/model/CarpoolService.java import com.leelit.stuer.bean.CarpoolingInfo; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.http.QueryMap; import rx.Observable; package com.leelit.stuer.module_baseinfo.carpool.model; /** * Created by Leelit on 2016/3/8. */ public interface CarpoolService { @GET("query")
Observable<List<CarpoolingInfo>> getGroupRecords();
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_stu/StuWebViewActivity.java
// Path: app/src/main/java/com/leelit/stuer/utils/UiUtils.java // public class UiUtils { // // @TargetApi(19) // public static void setTranslucentStatusBar(Activity activity, NavigationView navigationView) { // if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && navigationView != null) { // // fix 天坑 4.4 + drawerlayout + navigationView // tianKeng(activity, activity.getResources().getColor(R.color.primary), navigationView); // } else { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // SystemBarTintManager tintManager = new SystemBarTintManager(activity); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintColor(activity.getResources().getColor(R.color.primary)); // } // } // } // // @TargetApi(19) // public static void setTranslucentStatusBar(Activity activity) { // setTranslucentStatusBar(activity, null); // } // // /** // * snippet from https://github.com/niorgai/StatusBarCompat // * <p/> // * 直接使用会引起NavigationView上面空白一部分,需要将其margin - statusBarHeight // */ // @TargetApi(19) // private static void tianKeng(Activity activity, int statusColor, NavigationView navigationView) { // Window window = activity.getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // // int statusBarHeight = getStatusBarHeight(activity); // // ViewGroup mContentView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT); // // View mChildView = mContentView.getChildAt(0); // if (mChildView != null) { // FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mChildView.getLayoutParams(); // //if margin top has already set, just skip. // if (lp != null && lp.topMargin < statusBarHeight && lp.height != statusBarHeight) { // //do not use fitsSystemWindows // ViewCompat.setFitsSystemWindows(mChildView, false); // //add margin to content // lp.topMargin += statusBarHeight; // mChildView.setLayoutParams(lp); // } // } // // View statusBarView = mContentView.getChildAt(0); // if (statusBarView != null && statusBarView.getLayoutParams() != null && statusBarView.getLayoutParams().height == statusBarHeight) { // //if fake status bar view exist, we can setBackgroundColor and return. // statusBarView.setBackgroundColor(statusColor); // return; // } // statusBarView = new View(activity); // ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight); // statusBarView.setBackgroundColor(statusColor); // mContentView.addView(statusBarView, 0, lp); // // DrawerLayout.LayoutParams nvLp = (DrawerLayout.LayoutParams) navigationView.getLayoutParams(); // nvLp.topMargin -= statusBarHeight; // navigationView.setLayoutParams(nvLp); // } // // public static int getStatusBarHeight(Context context) { // int result = 0; // int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // if (resId > 0) { // result = context.getResources().getDimensionPixelOffset(resId); // } // return result; // } // // public static void initBaseToolBar(final AppCompatActivity activity, Toolbar mToolbar, String title) { // activity.setSupportActionBar(mToolbar); // mToolbar.setTitle(title); // mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); // mToolbar.setNavigationOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // activity.finish(); // } // }); // } // // public static boolean isNightMode(AppCompatActivity activity) { // int uiMode = activity.getResources().getConfiguration().uiMode; // int dayNightUiMode = uiMode & Configuration.UI_MODE_NIGHT_MASK; // if (SPUtils.getBoolean(MainActivity.CURRENT_NIGHT_MODE) && dayNightUiMode != Configuration.UI_MODE_NIGHT_YES) { // activity.getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES); // activity.recreate(); // return true; // } // return false; // } // }
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.DownloadListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import com.leelit.stuer.R; import com.leelit.stuer.utils.UiUtils; import butterknife.ButterKnife; import butterknife.InjectView;
package com.leelit.stuer.module_stu; public class StuWebViewActivity extends AppCompatActivity { @InjectView(R.id.webView) WebView mWebView; @InjectView(R.id.btn_back) ImageView mBtnBack; @InjectView(R.id.btn_forward) ImageView mBtnForward; @InjectView(R.id.toolbar) Toolbar mToolbar; @InjectView(R.id.progressBar) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stu); ButterKnife.inject(this);
// Path: app/src/main/java/com/leelit/stuer/utils/UiUtils.java // public class UiUtils { // // @TargetApi(19) // public static void setTranslucentStatusBar(Activity activity, NavigationView navigationView) { // if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && navigationView != null) { // // fix 天坑 4.4 + drawerlayout + navigationView // tianKeng(activity, activity.getResources().getColor(R.color.primary), navigationView); // } else { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // SystemBarTintManager tintManager = new SystemBarTintManager(activity); // tintManager.setStatusBarTintEnabled(true); // tintManager.setStatusBarTintColor(activity.getResources().getColor(R.color.primary)); // } // } // } // // @TargetApi(19) // public static void setTranslucentStatusBar(Activity activity) { // setTranslucentStatusBar(activity, null); // } // // /** // * snippet from https://github.com/niorgai/StatusBarCompat // * <p/> // * 直接使用会引起NavigationView上面空白一部分,需要将其margin - statusBarHeight // */ // @TargetApi(19) // private static void tianKeng(Activity activity, int statusColor, NavigationView navigationView) { // Window window = activity.getWindow(); // window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // // int statusBarHeight = getStatusBarHeight(activity); // // ViewGroup mContentView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT); // // View mChildView = mContentView.getChildAt(0); // if (mChildView != null) { // FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mChildView.getLayoutParams(); // //if margin top has already set, just skip. // if (lp != null && lp.topMargin < statusBarHeight && lp.height != statusBarHeight) { // //do not use fitsSystemWindows // ViewCompat.setFitsSystemWindows(mChildView, false); // //add margin to content // lp.topMargin += statusBarHeight; // mChildView.setLayoutParams(lp); // } // } // // View statusBarView = mContentView.getChildAt(0); // if (statusBarView != null && statusBarView.getLayoutParams() != null && statusBarView.getLayoutParams().height == statusBarHeight) { // //if fake status bar view exist, we can setBackgroundColor and return. // statusBarView.setBackgroundColor(statusColor); // return; // } // statusBarView = new View(activity); // ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight); // statusBarView.setBackgroundColor(statusColor); // mContentView.addView(statusBarView, 0, lp); // // DrawerLayout.LayoutParams nvLp = (DrawerLayout.LayoutParams) navigationView.getLayoutParams(); // nvLp.topMargin -= statusBarHeight; // navigationView.setLayoutParams(nvLp); // } // // public static int getStatusBarHeight(Context context) { // int result = 0; // int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // if (resId > 0) { // result = context.getResources().getDimensionPixelOffset(resId); // } // return result; // } // // public static void initBaseToolBar(final AppCompatActivity activity, Toolbar mToolbar, String title) { // activity.setSupportActionBar(mToolbar); // mToolbar.setTitle(title); // mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); // mToolbar.setNavigationOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // activity.finish(); // } // }); // } // // public static boolean isNightMode(AppCompatActivity activity) { // int uiMode = activity.getResources().getConfiguration().uiMode; // int dayNightUiMode = uiMode & Configuration.UI_MODE_NIGHT_MASK; // if (SPUtils.getBoolean(MainActivity.CURRENT_NIGHT_MODE) && dayNightUiMode != Configuration.UI_MODE_NIGHT_YES) { // activity.getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES); // activity.recreate(); // return true; // } // return false; // } // } // Path: app/src/main/java/com/leelit/stuer/module_stu/StuWebViewActivity.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.DownloadListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.ProgressBar; import com.leelit.stuer.R; import com.leelit.stuer.utils.UiUtils; import butterknife.ButterKnife; import butterknife.InjectView; package com.leelit.stuer.module_stu; public class StuWebViewActivity extends AppCompatActivity { @InjectView(R.id.webView) WebView mWebView; @InjectView(R.id.btn_back) ImageView mBtnBack; @InjectView(R.id.btn_forward) ImageView mBtnForward; @InjectView(R.id.toolbar) Toolbar mToolbar; @InjectView(R.id.progressBar) ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stu); ButterKnife.inject(this);
UiUtils.setTranslucentStatusBar(this);
leelit/STUer-client
app/src/main/java/com/leelit/stuer/dao/SellDao.java
// Path: app/src/main/java/com/leelit/stuer/bean/SellInfo.java // public class SellInfo { // int id; // String name; // String tel; // String shortTel; // String wechat; // String datetime; // String imei; // String picAddress; // String state; // String uniquecode; // attention 这里的flag和carpool/date模块不同,唯一订单号,相当于前两个的uniquecode // String status; // on // off // // @Override // public String toString() { // return "SellInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", datetime='" + datetime + '\'' + // ", imei='" + imei + '\'' + // ", picAddress='" + picAddress + '\'' + // ", state='" + state + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", status='" + status + '\'' + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTel() { // return tel; // } // // public void setTel(String tel) { // this.tel = tel; // } // // public String getShortTel() { // return shortTel; // } // // public void setShortTel(String shortTel) { // this.shortTel = shortTel; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public String getImei() { // return imei; // } // // public void setImei(String imei) { // this.imei = imei; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.leelit.stuer.bean.SellInfo; import java.util.ArrayList; import java.util.List;
package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/16. */ public class SellDao { public static final String[] TABLES = {"sell", "sell_collector"};
// Path: app/src/main/java/com/leelit/stuer/bean/SellInfo.java // public class SellInfo { // int id; // String name; // String tel; // String shortTel; // String wechat; // String datetime; // String imei; // String picAddress; // String state; // String uniquecode; // attention 这里的flag和carpool/date模块不同,唯一订单号,相当于前两个的uniquecode // String status; // on // off // // @Override // public String toString() { // return "SellInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", datetime='" + datetime + '\'' + // ", imei='" + imei + '\'' + // ", picAddress='" + picAddress + '\'' + // ", state='" + state + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", status='" + status + '\'' + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getTel() { // return tel; // } // // public void setTel(String tel) { // this.tel = tel; // } // // public String getShortTel() { // return shortTel; // } // // public void setShortTel(String shortTel) { // this.shortTel = shortTel; // } // // public String getWechat() { // return wechat; // } // // public void setWechat(String wechat) { // this.wechat = wechat; // } // // public String getImei() { // return imei; // } // // public void setImei(String imei) { // this.imei = imei; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // } // Path: app/src/main/java/com/leelit/stuer/dao/SellDao.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.leelit.stuer.bean.SellInfo; import java.util.ArrayList; import java.util.List; package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/16. */ public class SellDao { public static final String[] TABLES = {"sell", "sell_collector"};
public void save(String whichTable, SellInfo info) {
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/SupportModelUtils.java // public class SupportModelUtils { // // public static final String HOST = NetConstant.HOST; // // // /** // * 默认线程处理方式 // * // * @param observable // * @param subscriber // */ // public static void toSubscribe(Observable observable, Subscriber subscriber) { // observable.subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // }
import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.utils.SupportModelUtils; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; import retrofit2.RxJavaCallAdapterFactory; import rx.Subscriber;
package com.leelit.stuer.module_baseinfo.date.model; /** * Created by Leelit on 2016/3/8. */ public class DateModel { private static final String BASE_URL = SupportModelUtils.HOST + "date/"; private DateService mService = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(DateService.class);
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/SupportModelUtils.java // public class SupportModelUtils { // // public static final String HOST = NetConstant.HOST; // // // /** // * 默认线程处理方式 // * // * @param observable // * @param subscriber // */ // public static void toSubscribe(Observable observable, Subscriber subscriber) { // observable.subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.utils.SupportModelUtils; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; import retrofit2.RxJavaCallAdapterFactory; import rx.Subscriber; package com.leelit.stuer.module_baseinfo.date.model; /** * Created by Leelit on 2016/3/8. */ public class DateModel { private static final String BASE_URL = SupportModelUtils.HOST + "date/"; private DateService mService = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(DateService.class);
public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) {
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // }
import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber;
package com.leelit.stuer.module_baseinfo.date.presenter; /** * Created by Leelit on 2016/3/8. */ public class DatePresenter implements IPresenter { private DateModel mModel = new DateModel();
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber; package com.leelit.stuer.module_baseinfo.date.presenter; /** * Created by Leelit on 2016/3/8. */ public class DatePresenter implements IPresenter { private DateModel mModel = new DateModel();
private IBaseInfoView mView;
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // }
import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber;
package com.leelit.stuer.module_baseinfo.date.presenter; /** * Created by Leelit on 2016/3/8. */ public class DatePresenter implements IPresenter { private DateModel mModel = new DateModel(); private IBaseInfoView mView;
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber; package com.leelit.stuer.module_baseinfo.date.presenter; /** * Created by Leelit on 2016/3/8. */ public class DatePresenter implements IPresenter { private DateModel mModel = new DateModel(); private IBaseInfoView mView;
private Subscriber<List<DatingInfo>> mSubscriber1;
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // }
import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber;
public void onError(Throwable e) { if (mView != null) { mView.stopRefreshing(); mView.netError(); } } @Override public void onNext(List<DatingInfo> datingInfos) { mView.stopRefreshing(); mView.showData(datingInfos); if (datingInfos.isEmpty()) { mView.noData(); } } }; mModel.getGroupRecords(type, mSubscriber1); } public void doPostData(final DatingInfo info) { mView.showJoinProgressDialog(); mSubscriber2 = new Subscriber<ResponseBody>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) {
// Path: app/src/main/java/com/leelit/stuer/bean/DatingInfo.java // public class DatingInfo extends BaseInfo { // // String type; // String description = ""; // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @Override // public String toString() { // return "DatingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", type='" + type + '\'' + // ", description='" + description + '\'' + // '}'; // } // // @Override // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(type); // } // } // // Path: app/src/main/java/com/leelit/stuer/constant/NetConstant.java // public class NetConstant { // // public static final int NET_ERROR_RECORD_EXISTED = 601; // // // public static final String HOST = "http://192.168.191.1:8080/STUer/"; // public static final String HOST = "http://stuer.applinzi.com/"; // // public static final String IMAGE_HOST = "http://stuer-picture.stor.sinaapp.com/"; // // } // // Path: app/src/main/java/com/leelit/stuer/base_presenter/IPresenter.java // public interface IPresenter { // void doClear(); // // } // // Path: app/src/main/java/com/leelit/stuer/base_view/viewinterface/IBaseInfoView.java // public interface IBaseInfoView { // // void stopRefreshing(); // // void netError(); // // void showData(List<? extends BaseInfo> list); // // void noData(); // // void showJoinProgressDialog(); // // void dismissJoinProgressDialog(); // // void showAlreadyJoin(); // // void doAfterJoinSuccessfully(); // // } // // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/model/DateModel.java // public class DateModel { // // private static final String BASE_URL = SupportModelUtils.HOST + "date/"; // // private DateService mService = new Retrofit.Builder() // .baseUrl(BASE_URL) // .addConverterFactory(GsonConverterFactory.create()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(DateService.class); // // // public void getGroupRecords(String type, Subscriber<List<DatingInfo>> subscriber) { // SupportModelUtils.toSubscribe(mService.getGroupRecords(type), subscriber); // // } // // public void getPersonalRelativeRecords(String imei, Subscriber<List<List<DatingInfo>>> subscriber) { // SupportModelUtils.toSubscribe(mService.getPersonalRelativeRecords(imei), subscriber); // } // // public void addRecord(DatingInfo datingInfo, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.addRecord(datingInfo), subscriber); // } // // public void quitOrder(Map<String, String> map, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.quitOrder(map), subscriber); // } // // public void finishOrder(String uniquecode, Subscriber<ResponseBody> subscriber) { // SupportModelUtils.toSubscribe(mService.finishOrder(uniquecode), subscriber); // } // // // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/date/presenter/DatePresenter.java import com.leelit.stuer.bean.DatingInfo; import com.leelit.stuer.constant.NetConstant; import com.leelit.stuer.base_presenter.IPresenter; import com.leelit.stuer.base_view.viewinterface.IBaseInfoView; import com.leelit.stuer.module_baseinfo.date.model.DateModel; import java.util.List; import okhttp3.ResponseBody; import rx.Subscriber; public void onError(Throwable e) { if (mView != null) { mView.stopRefreshing(); mView.netError(); } } @Override public void onNext(List<DatingInfo> datingInfos) { mView.stopRefreshing(); mView.showData(datingInfos); if (datingInfos.isEmpty()) { mView.noData(); } } }; mModel.getGroupRecords(type, mSubscriber1); } public void doPostData(final DatingInfo info) { mView.showJoinProgressDialog(); mSubscriber2 = new Subscriber<ResponseBody>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) {
if (e.toString().split(" ")[2].equals(String.valueOf(NetConstant.NET_ERROR_RECORD_EXISTED))) {
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_baseinfo/carpool/model/CarpoolModel.java
// Path: app/src/main/java/com/leelit/stuer/bean/CarpoolingInfo.java // public class CarpoolingInfo extends BaseInfo { // // String route; // // @Override // public String toString() { // return "CarpoolingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", route='" + route + '\'' + // '}'; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(route); // // } // // } // // Path: app/src/main/java/com/leelit/stuer/utils/SupportModelUtils.java // public class SupportModelUtils { // // public static final String HOST = NetConstant.HOST; // // // /** // * 默认线程处理方式 // * // * @param observable // * @param subscriber // */ // public static void toSubscribe(Observable observable, Subscriber subscriber) { // observable.subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // }
import com.leelit.stuer.bean.CarpoolingInfo; import com.leelit.stuer.utils.SupportModelUtils; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; import retrofit2.RxJavaCallAdapterFactory; import rx.Subscriber;
package com.leelit.stuer.module_baseinfo.carpool.model; /** * Created by Leelit on 2016/3/8. */ public class CarpoolModel { // model此处无法抽象,因为接口不同; // Retrofit使用Gson进行字符串解析,并且RxJava#Observable<T>不能使用通配符,所以Gson从String-Object时必须指定确切类型,如果指定父类,则会丢失信息。 // 使用Retrofit配合Gson不管是post还是get,解析的类型都是特定的,父类会丢失子类信息。 private static final String BASE_URL = SupportModelUtils.HOST + "carpool/"; private Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); private CarpoolService mService = retrofit.create(CarpoolService.class); /** * can't not be Subscriber<List<BaseInfo>> or Subscriber<List<? extends/super BaseInfo>> * * @param subscriber */
// Path: app/src/main/java/com/leelit/stuer/bean/CarpoolingInfo.java // public class CarpoolingInfo extends BaseInfo { // // String route; // // @Override // public String toString() { // return "CarpoolingInfo{" + // "id=" + id + // ", name='" + name + '\'' + // ", tel='" + tel + '\'' + // ", shortTel='" + shortTel + '\'' + // ", wechat='" + wechat + '\'' + // ", date='" + date + '\'' + // ", time='" + time + '\'' + // ", temporaryCount='" + temporaryCount + '\'' + // ", flag='" + flag + '\'' + // ", imei='" + imei + '\'' + // ", uniquecode='" + uniquecode + '\'' + // ", route='" + route + '\'' + // '}'; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public boolean completedAllInfo() { // return super.completedAllInfo() && // !TextUtils.isEmpty(route); // // } // // } // // Path: app/src/main/java/com/leelit/stuer/utils/SupportModelUtils.java // public class SupportModelUtils { // // public static final String HOST = NetConstant.HOST; // // // /** // * 默认线程处理方式 // * // * @param observable // * @param subscriber // */ // public static void toSubscribe(Observable observable, Subscriber subscriber) { // observable.subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber); // } // } // Path: app/src/main/java/com/leelit/stuer/module_baseinfo/carpool/model/CarpoolModel.java import com.leelit.stuer.bean.CarpoolingInfo; import com.leelit.stuer.utils.SupportModelUtils; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; import retrofit2.RxJavaCallAdapterFactory; import rx.Subscriber; package com.leelit.stuer.module_baseinfo.carpool.model; /** * Created by Leelit on 2016/3/8. */ public class CarpoolModel { // model此处无法抽象,因为接口不同; // Retrofit使用Gson进行字符串解析,并且RxJava#Observable<T>不能使用通配符,所以Gson从String-Object时必须指定确切类型,如果指定父类,则会丢失信息。 // 使用Retrofit配合Gson不管是post还是get,解析的类型都是特定的,父类会丢失子类信息。 private static final String BASE_URL = SupportModelUtils.HOST + "carpool/"; private Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); private CarpoolService mService = retrofit.create(CarpoolService.class); /** * can't not be Subscriber<List<BaseInfo>> or Subscriber<List<? extends/super BaseInfo>> * * @param subscriber */
public void getGroupRecords(Subscriber<List<CarpoolingInfo>> subscriber) {
leelit/STUer-client
app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java
// Path: app/src/main/java/com/leelit/stuer/MyApplication.java // public class MyApplication extends Application { // // public static final String VERSION = "1.1.0"; // // public static Context context; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // } // }
import android.app.Activity; import android.telephony.TelephonyManager; import com.leelit.stuer.MyApplication; import com.leelit.stuer.R; import java.util.Date;
package com.leelit.stuer.utils; /** * Created by Leelit on 2016/1/6. */ public class AppInfoUtils { public static String getAppName() {
// Path: app/src/main/java/com/leelit/stuer/MyApplication.java // public class MyApplication extends Application { // // public static final String VERSION = "1.1.0"; // // public static Context context; // // @Override // public void onCreate() { // super.onCreate(); // context = getApplicationContext(); // } // } // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java import android.app.Activity; import android.telephony.TelephonyManager; import com.leelit.stuer.MyApplication; import com.leelit.stuer.R; import java.util.Date; package com.leelit.stuer.utils; /** * Created by Leelit on 2016/1/6. */ public class AppInfoUtils { public static String getAppName() {
return MyApplication.context.getString(R.string.app_name);
leelit/STUer-client
app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // }
import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List;
package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception {
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // } // Path: app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception {
List<TreeholeInfo> treeholeInfos = new ArrayList<>();
leelit/STUer-client
app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // }
import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List;
package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception { List<TreeholeInfo> treeholeInfos = new ArrayList<>(); for (int i = 0; i < 3; i++) { TreeholeInfo info = new TreeholeInfo(); info.setState("hehe" + i);
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // } // Path: app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception { List<TreeholeInfo> treeholeInfos = new ArrayList<>(); for (int i = 0; i < 3; i++) { TreeholeInfo info = new TreeholeInfo(); info.setState("hehe" + i);
info.setDatetime(TimeUtils.getCurrentTime());
leelit/STUer-client
app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // }
import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List;
package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception { List<TreeholeInfo> treeholeInfos = new ArrayList<>(); for (int i = 0; i < 3; i++) { TreeholeInfo info = new TreeholeInfo(); info.setState("hehe" + i); info.setDatetime(TimeUtils.getCurrentTime());
// Path: app/src/main/java/com/leelit/stuer/bean/TreeholeInfo.java // public class TreeholeInfo { // String datetime; // // String state; // // String picAddress; // // String uniquecode; // // @Override // public String toString() { // return "TreeholeInfo{" + // "datetime='" + datetime + '\'' + // ", state='" + state + '\'' + // ", picAddress='" + picAddress + '\'' + // ", uniquecode='" + uniquecode + '\'' + // '}'; // } // // public String getDatetime() { // return datetime; // } // // public void setDatetime(String datetime) { // this.datetime = datetime; // } // // public String getState() { // return state; // } // // public void setState(String state) { // this.state = state; // } // // public String getPicAddress() { // return picAddress; // } // // public void setPicAddress(String picAddress) { // this.picAddress = picAddress; // } // // public String getUniquecode() { // return uniquecode; // } // // public void setUniquecode(String uniquecode) { // this.uniquecode = uniquecode; // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/AppInfoUtils.java // public class AppInfoUtils { // public static String getAppName() { // return MyApplication.context.getString(R.string.app_name); // } // // public static String getImei() { // TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE)); // String imei = tm.getDeviceId(); // if (imei != null && !imei.isEmpty()) { // return imei; // } // return ""; // } // // /** // * 产生唯一订单号 // * @return // */ // public static String getUniqueCode() { // String imei = AppInfoUtils.getImei(); // Date date = new Date(); // String unique = imei + date.hashCode(); // return String.valueOf(unique.hashCode()); // } // } // // Path: app/src/main/java/com/leelit/stuer/utils/TimeUtils.java // public class TimeUtils { // // private static final int DAY_MS = 24 * 60 * 60 * 1000; // private static final int HOUR_MS = (60 * 60 * 1000); // ; // private static final int MIN_MS = (60 * 1000); // // public static String getCurrentTime() { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String time = df.format(new Date()); // return time; // } // // public static Map<String, String> getDetailTime(String datetime) { // Map<String, String> map = new HashMap<>(); // map.put("year", datetime.substring(0, 4)); // map.put("month", datetime.substring(5, 7)); // map.put("day", datetime.substring(8, 10)); // map.put("hour", datetime.substring(11, 13)); // map.put("minute", datetime.substring(14, 16)); // map.put("second", datetime.substring(17, 19)); // return map; // } // // public static String compareNowWithBefore(String datetime) { // String noSecondDatetime = new StringBuilder(datetime).delete(datetime.length() - 3, datetime.length()).toString(); // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // try { // Map<String, String> detail = getDetailTime(datetime); // Date now = df.parse(getCurrentTime()); // Date date = df.parse(datetime); // long timeGap = now.getTime() - date.getTime(); // long dayGap = timeGap / DAY_MS; // if (dayGap >= 30) { // return noSecondDatetime; // } else if (dayGap > 2) { // return new StringBuilder().append(detail.get("month")).append("-").append(detail.get("day")).append(" ").append(detail.get("hour")).append(":").append(detail.get("minute")).toString(); // } else if (dayGap == 2) { // return "前天 " + detail.get("hour") + ":" + detail.get("minute"); // } else if (dayGap == 1) { // return "昨天 " + detail.get("hour") + ":" + detail.get("minute"); // } // long hourGap = (timeGap / HOUR_MS - dayGap * 24); // if (hourGap > 0) { // return hourGap + "小时前"; // } // long minGap = ((timeGap / MIN_MS) - dayGap * 24 * 60 - hourGap * 60); // if (minGap > 0) { // return minGap + "分钟前"; // } else if (minGap == 0) { // return "刚刚"; // } else { // return noSecondDatetime; // } // } catch (ParseException e) { // e.printStackTrace(); // return noSecondDatetime; // } // } // // public static Date stringToDate(String dateStr, String formatStr) { // DateFormat sdf = new SimpleDateFormat(formatStr); // Date date = null; // try { // date = sdf.parse(dateStr); // } catch (ParseException e) { // e.printStackTrace(); // } // return date; // } // } // Path: app/src/androidTest/java/com/leelit/stuer/dao/TreeholeDaoTest.java import android.util.Log; import com.leelit.stuer.bean.TreeholeInfo; import com.leelit.stuer.utils.AppInfoUtils; import com.leelit.stuer.utils.TimeUtils; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; package com.leelit.stuer.dao; /** * Created by Leelit on 2016/3/25. */ public class TreeholeDaoTest extends TestCase { public void testSave() throws Exception { List<TreeholeInfo> treeholeInfos = new ArrayList<>(); for (int i = 0; i < 3; i++) { TreeholeInfo info = new TreeholeInfo(); info.setState("hehe" + i); info.setDatetime(TimeUtils.getCurrentTime());
info.setUniquecode(AppInfoUtils.getUniqueCode());