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
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/server/entity/helper/EnumDragonLifeStage.java
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/Interpolation.java // public class Interpolation { // // private static final float[][] CR = { // {-0.5f, 1.5f, -1.5f, 0.5f}, // { 1.0f, -2.5f, 2.0f, -0.5f}, // {-0.5f, 0.0f, 0.5f, 0.0f}, // { 0.0f, 1.0f, 0.0f, 0.0f} // }; // // public static float linear(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // return a * (1 - x) + b * x; // } // // public static float smoothStep(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // x = x * x * (3 - 2 * x); // return a * (1 - x) + b * x; // } // // // http://www.java-gaming.org/index.php?topic=24122.0 // public static void catmullRomSpline(float x, float[] result, float[]... knots) { // int nknots = knots.length; // int nspans = nknots - 3; // int knot = 0; // if (nspans < 1) { // throw new IllegalArgumentException("Spline has too few knots"); // } // x = MathX.clamp(x, 0, 0.9999f) * nspans; // // int span = (int) x; // if (span >= nknots - 3) { // span = nknots - 3; // } // // x -= span; // knot += span; // // int dimension = result.length; // for (int i = 0; i < dimension; i++) { // float knot0 = knots[knot][i]; // float knot1 = knots[knot + 1][i]; // float knot2 = knots[knot + 2][i]; // float knot3 = knots[knot + 3][i]; // // float c3 = CR[0][0] * knot0 + CR[0][1] * knot1 + CR[0][2] * knot2 + CR[0][3] * knot3; // float c2 = CR[1][0] * knot0 + CR[1][1] * knot1 + CR[1][2] * knot2 + CR[1][3] * knot3; // float c1 = CR[2][0] * knot0 + CR[2][1] * knot1 + CR[2][2] * knot2 + CR[2][3] * knot3; // float c0 = CR[3][0] * knot0 + CR[3][1] * knot1 + CR[3][2] * knot2 + CR[3][3] * knot3; // // result[i] = ((c3 * x + c2) * x + c1) * x + c0; // } // } // // private Interpolation() { // } // }
import info.ata4.minecraft.dragon.util.math.Interpolation; import net.minecraft.util.math.MathHelper;
/* ** 2012 August 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.entity.helper; /** * Enum for dragon life stages. Used as aliases for the age value of dragons. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public enum EnumDragonLifeStage { EGG(0.25f), HATCHLING(0.33f), JUVENILE(0.66f), ADULT(1); public static final int TICKS_PER_STAGE = 24000; public static final EnumDragonLifeStage[] VALUES = values(); // cached for speed public static EnumDragonLifeStage fromTickCount(int ticksSinceCreation) { return VALUES[clampTickCount(ticksSinceCreation) / TICKS_PER_STAGE]; } public static float progressFromTickCount(int ticksSinceCreation) { EnumDragonLifeStage lifeStage = fromTickCount(ticksSinceCreation); int lifeStageTicks = ticksSinceCreation - lifeStage.startTicks(); return lifeStageTicks / (float) TICKS_PER_STAGE; } public static float scaleFromTickCount(int ticksSinceCreation) { EnumDragonLifeStage lifeStage = fromTickCount(ticksSinceCreation); // constant size for egg and adult stage if (lifeStage == EGG || lifeStage == ADULT) { return lifeStage.scale; } // interpolated size between current and next stage
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/Interpolation.java // public class Interpolation { // // private static final float[][] CR = { // {-0.5f, 1.5f, -1.5f, 0.5f}, // { 1.0f, -2.5f, 2.0f, -0.5f}, // {-0.5f, 0.0f, 0.5f, 0.0f}, // { 0.0f, 1.0f, 0.0f, 0.0f} // }; // // public static float linear(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // return a * (1 - x) + b * x; // } // // public static float smoothStep(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // x = x * x * (3 - 2 * x); // return a * (1 - x) + b * x; // } // // // http://www.java-gaming.org/index.php?topic=24122.0 // public static void catmullRomSpline(float x, float[] result, float[]... knots) { // int nknots = knots.length; // int nspans = nknots - 3; // int knot = 0; // if (nspans < 1) { // throw new IllegalArgumentException("Spline has too few knots"); // } // x = MathX.clamp(x, 0, 0.9999f) * nspans; // // int span = (int) x; // if (span >= nknots - 3) { // span = nknots - 3; // } // // x -= span; // knot += span; // // int dimension = result.length; // for (int i = 0; i < dimension; i++) { // float knot0 = knots[knot][i]; // float knot1 = knots[knot + 1][i]; // float knot2 = knots[knot + 2][i]; // float knot3 = knots[knot + 3][i]; // // float c3 = CR[0][0] * knot0 + CR[0][1] * knot1 + CR[0][2] * knot2 + CR[0][3] * knot3; // float c2 = CR[1][0] * knot0 + CR[1][1] * knot1 + CR[1][2] * knot2 + CR[1][3] * knot3; // float c1 = CR[2][0] * knot0 + CR[2][1] * knot1 + CR[2][2] * knot2 + CR[2][3] * knot3; // float c0 = CR[3][0] * knot0 + CR[3][1] * knot1 + CR[3][2] * knot2 + CR[3][3] * knot3; // // result[i] = ((c3 * x + c2) * x + c1) * x + c0; // } // } // // private Interpolation() { // } // } // Path: src/main/java/info/ata4/minecraft/dragon/server/entity/helper/EnumDragonLifeStage.java import info.ata4.minecraft.dragon.util.math.Interpolation; import net.minecraft.util.math.MathHelper; /* ** 2012 August 23 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.entity.helper; /** * Enum for dragon life stages. Used as aliases for the age value of dragons. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public enum EnumDragonLifeStage { EGG(0.25f), HATCHLING(0.33f), JUVENILE(0.66f), ADULT(1); public static final int TICKS_PER_STAGE = 24000; public static final EnumDragonLifeStage[] VALUES = values(); // cached for speed public static EnumDragonLifeStage fromTickCount(int ticksSinceCreation) { return VALUES[clampTickCount(ticksSinceCreation) / TICKS_PER_STAGE]; } public static float progressFromTickCount(int ticksSinceCreation) { EnumDragonLifeStage lifeStage = fromTickCount(ticksSinceCreation); int lifeStageTicks = ticksSinceCreation - lifeStage.startTicks(); return lifeStageTicks / (float) TICKS_PER_STAGE; } public static float scaleFromTickCount(int ticksSinceCreation) { EnumDragonLifeStage lifeStage = fromTickCount(ticksSinceCreation); // constant size for egg and adult stage if (lifeStage == EGG || lifeStage == ADULT) { return lifeStage.scale; } // interpolated size between current and next stage
return Interpolation.linear(lifeStage.scale, lifeStage.next().scale,
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/server/item/ItemDragonBreedEgg.java
// Path: src/main/java/info/ata4/minecraft/dragon/server/block/BlockDragonBreedEgg.java // public class BlockDragonBreedEgg extends BlockDragonEgg { // // public static final PropertyEnum<EnumDragonBreed> BREED = PropertyEnum.create("breed", EnumDragonBreed.class); // public static final BlockDragonBreedEgg INSTANCE = new BlockDragonBreedEgg(); // // private BlockDragonBreedEgg() { // setUnlocalizedName("dragonEgg"); // setHardness(3); // setResistance(15); // setSoundType(SoundType.WOOD); // setLightLevel(0.125f); // setDefaultState(blockState.getBaseState().withProperty(BREED, EnumDragonBreed.DEFAULT)); // setCreativeTab(CreativeTabs.MISC); // } // // @Override // protected BlockStateContainer createBlockState() { // return new BlockStateContainer(this, new IProperty[]{ BREED }); // } // // @Override // public IBlockState getStateFromMeta(int meta) { // return getDefaultState().withProperty(BREED, // EnumDragonBreed.META_MAPPING.inverse().get(meta)); // } // // @Override // public int getMetaFromState(IBlockState state) { // EnumDragonBreed type = (EnumDragonBreed) state.getValue(BREED); // return EnumDragonBreed.META_MAPPING.get(type); // } // // @Override // public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { // EnumDragonBreed.META_MAPPING.values().forEach(index -> list.add(new ItemStack(itemIn, 1, index))); // } // // @Override // public int damageDropped(IBlockState state) { // return getMetaFromState(state); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/server/entity/breeds/EnumDragonBreed.java // public enum EnumDragonBreed implements IStringSerializable { // // AIR(0, DragonBreedAir::new), // END(1, DragonBreedEnd::new), // FIRE(2, DragonBreedFire::new), // FOREST(3, DragonBreedForest::new), // GHOST(4, DragonBreedGhost::new), // ICE(5, DragonBreedIce::new), // NETHER(6, DragonBreedNether::new), // WATER(7, DragonBreedWater::new); // // public static final EnumDragonBreed DEFAULT = END; // // // create static bimap between enums and meta data for faster and easier // // lookups // public static final BiMap<EnumDragonBreed, Integer> META_MAPPING = // ImmutableBiMap.copyOf(Arrays.asList(values()).stream() // .collect(Collectors.toMap(Function.identity(), EnumDragonBreed::getMeta))); // // private final DragonBreed breed; // // // this field is used for block metadata and is technically the same as // // ordinal(), but it is saved separately to make sure the values stay // // constant after adding more breeds in unexpected orders // private final int meta; // // private EnumDragonBreed(int meta, Supplier<DragonBreed> factory) { // this.breed = factory.get(); // this.meta = meta; // } // // public DragonBreed getBreed() { // return breed; // } // // public int getMeta() { // return meta; // } // // @Override // public String getName() { // return name().toLowerCase(); // } // }
import info.ata4.minecraft.dragon.server.block.BlockDragonBreedEgg; import info.ata4.minecraft.dragon.server.entity.breeds.EnumDragonBreed; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n;
/* ** 2016 March 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.item; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class ItemDragonBreedEgg extends ItemBlock { public static final ItemDragonBreedEgg INSTANCE = new ItemDragonBreedEgg(); public ItemDragonBreedEgg() {
// Path: src/main/java/info/ata4/minecraft/dragon/server/block/BlockDragonBreedEgg.java // public class BlockDragonBreedEgg extends BlockDragonEgg { // // public static final PropertyEnum<EnumDragonBreed> BREED = PropertyEnum.create("breed", EnumDragonBreed.class); // public static final BlockDragonBreedEgg INSTANCE = new BlockDragonBreedEgg(); // // private BlockDragonBreedEgg() { // setUnlocalizedName("dragonEgg"); // setHardness(3); // setResistance(15); // setSoundType(SoundType.WOOD); // setLightLevel(0.125f); // setDefaultState(blockState.getBaseState().withProperty(BREED, EnumDragonBreed.DEFAULT)); // setCreativeTab(CreativeTabs.MISC); // } // // @Override // protected BlockStateContainer createBlockState() { // return new BlockStateContainer(this, new IProperty[]{ BREED }); // } // // @Override // public IBlockState getStateFromMeta(int meta) { // return getDefaultState().withProperty(BREED, // EnumDragonBreed.META_MAPPING.inverse().get(meta)); // } // // @Override // public int getMetaFromState(IBlockState state) { // EnumDragonBreed type = (EnumDragonBreed) state.getValue(BREED); // return EnumDragonBreed.META_MAPPING.get(type); // } // // @Override // public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { // EnumDragonBreed.META_MAPPING.values().forEach(index -> list.add(new ItemStack(itemIn, 1, index))); // } // // @Override // public int damageDropped(IBlockState state) { // return getMetaFromState(state); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/server/entity/breeds/EnumDragonBreed.java // public enum EnumDragonBreed implements IStringSerializable { // // AIR(0, DragonBreedAir::new), // END(1, DragonBreedEnd::new), // FIRE(2, DragonBreedFire::new), // FOREST(3, DragonBreedForest::new), // GHOST(4, DragonBreedGhost::new), // ICE(5, DragonBreedIce::new), // NETHER(6, DragonBreedNether::new), // WATER(7, DragonBreedWater::new); // // public static final EnumDragonBreed DEFAULT = END; // // // create static bimap between enums and meta data for faster and easier // // lookups // public static final BiMap<EnumDragonBreed, Integer> META_MAPPING = // ImmutableBiMap.copyOf(Arrays.asList(values()).stream() // .collect(Collectors.toMap(Function.identity(), EnumDragonBreed::getMeta))); // // private final DragonBreed breed; // // // this field is used for block metadata and is technically the same as // // ordinal(), but it is saved separately to make sure the values stay // // constant after adding more breeds in unexpected orders // private final int meta; // // private EnumDragonBreed(int meta, Supplier<DragonBreed> factory) { // this.breed = factory.get(); // this.meta = meta; // } // // public DragonBreed getBreed() { // return breed; // } // // public int getMeta() { // return meta; // } // // @Override // public String getName() { // return name().toLowerCase(); // } // } // Path: src/main/java/info/ata4/minecraft/dragon/server/item/ItemDragonBreedEgg.java import info.ata4.minecraft.dragon.server.block.BlockDragonBreedEgg; import info.ata4.minecraft.dragon.server.entity.breeds.EnumDragonBreed; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n; /* ** 2016 March 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.item; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class ItemDragonBreedEgg extends ItemBlock { public static final ItemDragonBreedEgg INSTANCE = new ItemDragonBreedEgg(); public ItemDragonBreedEgg() {
super(BlockDragonBreedEgg.INSTANCE);
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/server/item/ItemDragonBreedEgg.java
// Path: src/main/java/info/ata4/minecraft/dragon/server/block/BlockDragonBreedEgg.java // public class BlockDragonBreedEgg extends BlockDragonEgg { // // public static final PropertyEnum<EnumDragonBreed> BREED = PropertyEnum.create("breed", EnumDragonBreed.class); // public static final BlockDragonBreedEgg INSTANCE = new BlockDragonBreedEgg(); // // private BlockDragonBreedEgg() { // setUnlocalizedName("dragonEgg"); // setHardness(3); // setResistance(15); // setSoundType(SoundType.WOOD); // setLightLevel(0.125f); // setDefaultState(blockState.getBaseState().withProperty(BREED, EnumDragonBreed.DEFAULT)); // setCreativeTab(CreativeTabs.MISC); // } // // @Override // protected BlockStateContainer createBlockState() { // return new BlockStateContainer(this, new IProperty[]{ BREED }); // } // // @Override // public IBlockState getStateFromMeta(int meta) { // return getDefaultState().withProperty(BREED, // EnumDragonBreed.META_MAPPING.inverse().get(meta)); // } // // @Override // public int getMetaFromState(IBlockState state) { // EnumDragonBreed type = (EnumDragonBreed) state.getValue(BREED); // return EnumDragonBreed.META_MAPPING.get(type); // } // // @Override // public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { // EnumDragonBreed.META_MAPPING.values().forEach(index -> list.add(new ItemStack(itemIn, 1, index))); // } // // @Override // public int damageDropped(IBlockState state) { // return getMetaFromState(state); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/server/entity/breeds/EnumDragonBreed.java // public enum EnumDragonBreed implements IStringSerializable { // // AIR(0, DragonBreedAir::new), // END(1, DragonBreedEnd::new), // FIRE(2, DragonBreedFire::new), // FOREST(3, DragonBreedForest::new), // GHOST(4, DragonBreedGhost::new), // ICE(5, DragonBreedIce::new), // NETHER(6, DragonBreedNether::new), // WATER(7, DragonBreedWater::new); // // public static final EnumDragonBreed DEFAULT = END; // // // create static bimap between enums and meta data for faster and easier // // lookups // public static final BiMap<EnumDragonBreed, Integer> META_MAPPING = // ImmutableBiMap.copyOf(Arrays.asList(values()).stream() // .collect(Collectors.toMap(Function.identity(), EnumDragonBreed::getMeta))); // // private final DragonBreed breed; // // // this field is used for block metadata and is technically the same as // // ordinal(), but it is saved separately to make sure the values stay // // constant after adding more breeds in unexpected orders // private final int meta; // // private EnumDragonBreed(int meta, Supplier<DragonBreed> factory) { // this.breed = factory.get(); // this.meta = meta; // } // // public DragonBreed getBreed() { // return breed; // } // // public int getMeta() { // return meta; // } // // @Override // public String getName() { // return name().toLowerCase(); // } // }
import info.ata4.minecraft.dragon.server.block.BlockDragonBreedEgg; import info.ata4.minecraft.dragon.server.entity.breeds.EnumDragonBreed; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n;
/* ** 2016 March 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.item; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class ItemDragonBreedEgg extends ItemBlock { public static final ItemDragonBreedEgg INSTANCE = new ItemDragonBreedEgg(); public ItemDragonBreedEgg() { super(BlockDragonBreedEgg.INSTANCE); setMaxDamage(0); setHasSubtypes(true); } @Override public int getMetadata(int metadata) { return metadata; } @Override public String getItemStackDisplayName(ItemStack stack) {
// Path: src/main/java/info/ata4/minecraft/dragon/server/block/BlockDragonBreedEgg.java // public class BlockDragonBreedEgg extends BlockDragonEgg { // // public static final PropertyEnum<EnumDragonBreed> BREED = PropertyEnum.create("breed", EnumDragonBreed.class); // public static final BlockDragonBreedEgg INSTANCE = new BlockDragonBreedEgg(); // // private BlockDragonBreedEgg() { // setUnlocalizedName("dragonEgg"); // setHardness(3); // setResistance(15); // setSoundType(SoundType.WOOD); // setLightLevel(0.125f); // setDefaultState(blockState.getBaseState().withProperty(BREED, EnumDragonBreed.DEFAULT)); // setCreativeTab(CreativeTabs.MISC); // } // // @Override // protected BlockStateContainer createBlockState() { // return new BlockStateContainer(this, new IProperty[]{ BREED }); // } // // @Override // public IBlockState getStateFromMeta(int meta) { // return getDefaultState().withProperty(BREED, // EnumDragonBreed.META_MAPPING.inverse().get(meta)); // } // // @Override // public int getMetaFromState(IBlockState state) { // EnumDragonBreed type = (EnumDragonBreed) state.getValue(BREED); // return EnumDragonBreed.META_MAPPING.get(type); // } // // @Override // public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) { // EnumDragonBreed.META_MAPPING.values().forEach(index -> list.add(new ItemStack(itemIn, 1, index))); // } // // @Override // public int damageDropped(IBlockState state) { // return getMetaFromState(state); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/server/entity/breeds/EnumDragonBreed.java // public enum EnumDragonBreed implements IStringSerializable { // // AIR(0, DragonBreedAir::new), // END(1, DragonBreedEnd::new), // FIRE(2, DragonBreedFire::new), // FOREST(3, DragonBreedForest::new), // GHOST(4, DragonBreedGhost::new), // ICE(5, DragonBreedIce::new), // NETHER(6, DragonBreedNether::new), // WATER(7, DragonBreedWater::new); // // public static final EnumDragonBreed DEFAULT = END; // // // create static bimap between enums and meta data for faster and easier // // lookups // public static final BiMap<EnumDragonBreed, Integer> META_MAPPING = // ImmutableBiMap.copyOf(Arrays.asList(values()).stream() // .collect(Collectors.toMap(Function.identity(), EnumDragonBreed::getMeta))); // // private final DragonBreed breed; // // // this field is used for block metadata and is technically the same as // // ordinal(), but it is saved separately to make sure the values stay // // constant after adding more breeds in unexpected orders // private final int meta; // // private EnumDragonBreed(int meta, Supplier<DragonBreed> factory) { // this.breed = factory.get(); // this.meta = meta; // } // // public DragonBreed getBreed() { // return breed; // } // // public int getMeta() { // return meta; // } // // @Override // public String getName() { // return name().toLowerCase(); // } // } // Path: src/main/java/info/ata4/minecraft/dragon/server/item/ItemDragonBreedEgg.java import info.ata4.minecraft.dragon.server.block.BlockDragonBreedEgg; import info.ata4.minecraft.dragon.server.entity.breeds.EnumDragonBreed; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n; /* ** 2016 March 10 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.server.item; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class ItemDragonBreedEgg extends ItemBlock { public static final ItemDragonBreedEgg INSTANCE = new ItemDragonBreedEgg(); public ItemDragonBreedEgg() { super(BlockDragonBreedEgg.INSTANCE); setMaxDamage(0); setHasSubtypes(true); } @Override public int getMetadata(int metadata) { return metadata; } @Override public String getItemStackDisplayName(ItemStack stack) {
EnumDragonBreed type = EnumDragonBreed.META_MAPPING.inverse().get(stack.getMetadata());
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/DragonMounts.java
// Path: src/main/java/info/ata4/minecraft/dragon/server/CommonProxy.java // public class CommonProxy { // // private final int ENTITY_TRACKING_RANGE = 80; // private final int ENTITY_UPDATE_FREQ = 3; // private final int ENTITY_ID = 0; // private final boolean ENTITY_SEND_VELO_UPDATES = true; // // public void onPreInit(FMLPreInitializationEvent event) { // GameRegistry.register(BlockDragonBreedEgg.INSTANCE.setRegistryName("dragon_egg")); // GameRegistry.register(ItemDragonBreedEgg.INSTANCE.setRegistryName("dragon_egg")); // } // // public void onInit(FMLInitializationEvent evt) { // registerEntities(); // // MinecraftForge.EVENT_BUS.register(new DragonEggBlockHandler()); // } // // public void onPostInit(FMLPostInitializationEvent event) { // } // // public void onServerStarting(FMLServerStartingEvent evt) { // MinecraftServer server = evt.getServer(); // ServerCommandManager cmdman = (ServerCommandManager) server.getCommandManager(); // cmdman.registerCommand(new CommandDragon()); // } // // public void onServerStopped(FMLServerStoppedEvent evt) { // } // // private void registerEntities() { // EntityRegistry.registerModEntity(EntityTameableDragon.class, "DragonMount", // ENTITY_ID, DragonMounts.instance, ENTITY_TRACKING_RANGE, ENTITY_UPDATE_FREQ, // ENTITY_SEND_VELO_UPDATES); // } // }
import info.ata4.minecraft.dragon.server.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.*;
/* ** 2012 August 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon; /** * Main control class for Forge. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ @Mod( modid = DragonMounts.ID, name = DragonMounts.NAME, version = DragonMounts.VERSION, useMetadata = true, guiFactory = "info.ata4.minecraft.dragon.DragonMountsConfigGuiFactory" ) public class DragonMounts { public static final String NAME = "Dragon Mounts"; public static final String ID = "DragonMounts"; public static final String AID = ID.toLowerCase(); public static final String VERSION = "@VERSION@"; @SidedProxy( serverSide = "info.ata4.minecraft.dragon.server.CommonProxy", clientSide = "info.ata4.minecraft.dragon.client.ClientProxy" )
// Path: src/main/java/info/ata4/minecraft/dragon/server/CommonProxy.java // public class CommonProxy { // // private final int ENTITY_TRACKING_RANGE = 80; // private final int ENTITY_UPDATE_FREQ = 3; // private final int ENTITY_ID = 0; // private final boolean ENTITY_SEND_VELO_UPDATES = true; // // public void onPreInit(FMLPreInitializationEvent event) { // GameRegistry.register(BlockDragonBreedEgg.INSTANCE.setRegistryName("dragon_egg")); // GameRegistry.register(ItemDragonBreedEgg.INSTANCE.setRegistryName("dragon_egg")); // } // // public void onInit(FMLInitializationEvent evt) { // registerEntities(); // // MinecraftForge.EVENT_BUS.register(new DragonEggBlockHandler()); // } // // public void onPostInit(FMLPostInitializationEvent event) { // } // // public void onServerStarting(FMLServerStartingEvent evt) { // MinecraftServer server = evt.getServer(); // ServerCommandManager cmdman = (ServerCommandManager) server.getCommandManager(); // cmdman.registerCommand(new CommandDragon()); // } // // public void onServerStopped(FMLServerStoppedEvent evt) { // } // // private void registerEntities() { // EntityRegistry.registerModEntity(EntityTameableDragon.class, "DragonMount", // ENTITY_ID, DragonMounts.instance, ENTITY_TRACKING_RANGE, ENTITY_UPDATE_FREQ, // ENTITY_SEND_VELO_UPDATES); // } // } // Path: src/main/java/info/ata4/minecraft/dragon/DragonMounts.java import info.ata4.minecraft.dragon.server.CommonProxy; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.ModMetadata; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.*; /* ** 2012 August 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon; /** * Main control class for Forge. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ @Mod( modid = DragonMounts.ID, name = DragonMounts.NAME, version = DragonMounts.VERSION, useMetadata = true, guiFactory = "info.ata4.minecraft.dragon.DragonMountsConfigGuiFactory" ) public class DragonMounts { public static final String NAME = "Dragon Mounts"; public static final String ID = "DragonMounts"; public static final String AID = ID.toLowerCase(); public static final String VERSION = "@VERSION@"; @SidedProxy( serverSide = "info.ata4.minecraft.dragon.server.CommonProxy", clientSide = "info.ata4.minecraft.dragon.client.ClientProxy" )
public static CommonProxy proxy;
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/client/model/ModelPart.java
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/MathX.java // public class MathX { // // public static final double PI_D = Math.PI; // public static final float PI_F = (float) Math.PI; // // /** // * You no take constructor! // */ // private MathX() { // } // // // float sine function, may use LUT // public static float sin(float a) { // return (float) Math.sin(a); // } // // // float cosine function, may use LUT // public static float cos(float a) { // return (float) Math.cos(a); // } // // // float tangent function // public static float tan(float a) { // return (float) Math.tan(a); // } // // // float atan2 function // public static float atan2(float y, float x) { // return (float) Math.atan2(y, x); // } // // // float degrees to radians conversion // public static float toRadians(float angdeg) { // return (float) Math.toRadians(angdeg); // } // // // float radians to degrees conversion // public static float toDegrees(float angrad) { // return (float) Math.toDegrees(angrad); // } // // // normalizes a float degrees angle to between +180 and -180 // public static float normDeg(float a) { // a %= 360; // if (a >= 180) { // a -= 360; // } // if (a < -180) { // a += 360; // } // return a; // } // // // normalizes a double degrees angle to between +180 and -180 // public static double normDeg(double a) { // a %= 360; // if (a >= 180) { // a -= 360; // } // if (a < -180) { // a += 360; // } // return a; // } // // // normalizes a float radians angle to between +π and -π // public static float normRad(float a) { // a %= PI_F * 2; // if (a >= PI_F) { // a -= PI_F * 2; // } // if (a < -PI_F) { // a += PI_F * 2; // } // return a; // } // // // normalizes a double radians angle to between +π and -π // public static double normRad(double a) { // a %= PI_D * 2; // if (a >= PI_D) { // a -= PI_D * 2; // } // if (a < -PI_D) { // a += PI_D * 2; // } // return a; // } // // // float square root // public static float sqrtf(float f) { // return (float) Math.sqrt(f); // } // // // numeric float clamp // public static float clamp(float value, float min, float max) { // return (value < min ? min : (value > max ? max : value)); // } // // // numeric double clamp // public static double clamp(double value, double min, double max) { // return (value < min ? min : (value > max ? max : value)); // } // // // numeric integer clamp // public static int clamp(int value, int min, int max) { // return (value < min ? min : (value > max ? max : value)); // } // // public static float updateRotation(float r1, float r2, float step) { // return r1 + clamp(normDeg(r2 - r1), -step, step); // } // }
import info.ata4.minecraft.dragon.util.math.MathX; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import static org.lwjgl.opengl.GL11.*;
compileDisplayList(scale); } GlStateManager.pushMatrix(); postRender(scale); // call display list GlStateManager.callList(displayList); // render child models if (childModels != null) { childModels.forEach(obj -> obj.render(scale)); } GlStateManager.popMatrix(); } @Override public void postRender(float scale) { // skip if hidden if (isHidden || !showModel) { return; } // translate GlStateManager.translate(rotationPointX * scale, rotationPointY * scale, rotationPointZ * scale); // rotate if (preRotateAngleZ != 0) {
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/MathX.java // public class MathX { // // public static final double PI_D = Math.PI; // public static final float PI_F = (float) Math.PI; // // /** // * You no take constructor! // */ // private MathX() { // } // // // float sine function, may use LUT // public static float sin(float a) { // return (float) Math.sin(a); // } // // // float cosine function, may use LUT // public static float cos(float a) { // return (float) Math.cos(a); // } // // // float tangent function // public static float tan(float a) { // return (float) Math.tan(a); // } // // // float atan2 function // public static float atan2(float y, float x) { // return (float) Math.atan2(y, x); // } // // // float degrees to radians conversion // public static float toRadians(float angdeg) { // return (float) Math.toRadians(angdeg); // } // // // float radians to degrees conversion // public static float toDegrees(float angrad) { // return (float) Math.toDegrees(angrad); // } // // // normalizes a float degrees angle to between +180 and -180 // public static float normDeg(float a) { // a %= 360; // if (a >= 180) { // a -= 360; // } // if (a < -180) { // a += 360; // } // return a; // } // // // normalizes a double degrees angle to between +180 and -180 // public static double normDeg(double a) { // a %= 360; // if (a >= 180) { // a -= 360; // } // if (a < -180) { // a += 360; // } // return a; // } // // // normalizes a float radians angle to between +π and -π // public static float normRad(float a) { // a %= PI_F * 2; // if (a >= PI_F) { // a -= PI_F * 2; // } // if (a < -PI_F) { // a += PI_F * 2; // } // return a; // } // // // normalizes a double radians angle to between +π and -π // public static double normRad(double a) { // a %= PI_D * 2; // if (a >= PI_D) { // a -= PI_D * 2; // } // if (a < -PI_D) { // a += PI_D * 2; // } // return a; // } // // // float square root // public static float sqrtf(float f) { // return (float) Math.sqrt(f); // } // // // numeric float clamp // public static float clamp(float value, float min, float max) { // return (value < min ? min : (value > max ? max : value)); // } // // // numeric double clamp // public static double clamp(double value, double min, double max) { // return (value < min ? min : (value > max ? max : value)); // } // // // numeric integer clamp // public static int clamp(int value, int min, int max) { // return (value < min ? min : (value > max ? max : value)); // } // // public static float updateRotation(float r1, float r2, float step) { // return r1 + clamp(normDeg(r2 - r1), -step, step); // } // } // Path: src/main/java/info/ata4/minecraft/dragon/client/model/ModelPart.java import info.ata4.minecraft.dragon.util.math.MathX; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import static org.lwjgl.opengl.GL11.*; compileDisplayList(scale); } GlStateManager.pushMatrix(); postRender(scale); // call display list GlStateManager.callList(displayList); // render child models if (childModels != null) { childModels.forEach(obj -> obj.render(scale)); } GlStateManager.popMatrix(); } @Override public void postRender(float scale) { // skip if hidden if (isHidden || !showModel) { return; } // translate GlStateManager.translate(rotationPointX * scale, rotationPointY * scale, rotationPointZ * scale); // rotate if (preRotateAngleZ != 0) {
GlStateManager.rotate(MathX.toDegrees(preRotateAngleZ), 0, 0, 1);
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/client/model/anim/CircularBuffer.java
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/Interpolation.java // public class Interpolation { // // private static final float[][] CR = { // {-0.5f, 1.5f, -1.5f, 0.5f}, // { 1.0f, -2.5f, 2.0f, -0.5f}, // {-0.5f, 0.0f, 0.5f, 0.0f}, // { 0.0f, 1.0f, 0.0f, 0.0f} // }; // // public static float linear(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // return a * (1 - x) + b * x; // } // // public static float smoothStep(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // x = x * x * (3 - 2 * x); // return a * (1 - x) + b * x; // } // // // http://www.java-gaming.org/index.php?topic=24122.0 // public static void catmullRomSpline(float x, float[] result, float[]... knots) { // int nknots = knots.length; // int nspans = nknots - 3; // int knot = 0; // if (nspans < 1) { // throw new IllegalArgumentException("Spline has too few knots"); // } // x = MathX.clamp(x, 0, 0.9999f) * nspans; // // int span = (int) x; // if (span >= nknots - 3) { // span = nknots - 3; // } // // x -= span; // knot += span; // // int dimension = result.length; // for (int i = 0; i < dimension; i++) { // float knot0 = knots[knot][i]; // float knot1 = knots[knot + 1][i]; // float knot2 = knots[knot + 2][i]; // float knot3 = knots[knot + 3][i]; // // float c3 = CR[0][0] * knot0 + CR[0][1] * knot1 + CR[0][2] * knot2 + CR[0][3] * knot3; // float c2 = CR[1][0] * knot0 + CR[1][1] * knot1 + CR[1][2] * knot2 + CR[1][3] * knot3; // float c1 = CR[2][0] * knot0 + CR[2][1] * knot1 + CR[2][2] * knot2 + CR[2][3] * knot3; // float c0 = CR[3][0] * knot0 + CR[3][1] * knot1 + CR[3][2] * knot2 + CR[3][3] * knot3; // // result[i] = ((c3 * x + c2) * x + c1) * x + c0; // } // } // // private Interpolation() { // } // }
import info.ata4.minecraft.dragon.util.math.Interpolation; import java.util.Arrays;
/* ** 2012 March 19 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.client.model.anim; /** * Very simple fixed size circular buffer implementation for animation purposes. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class CircularBuffer { private float buffer[]; private int index = 0; public CircularBuffer(int size) { buffer = new float[size]; } public void fill(float value) { Arrays.fill(buffer, value); } public void update(float value) { // move forward index++; // restart pointer at the end to form a virtual ring index %= buffer.length; buffer[index] = value; } public float get(float x, int offset) { int i = index - offset; int len = buffer.length - 1;
// Path: src/main/java/info/ata4/minecraft/dragon/util/math/Interpolation.java // public class Interpolation { // // private static final float[][] CR = { // {-0.5f, 1.5f, -1.5f, 0.5f}, // { 1.0f, -2.5f, 2.0f, -0.5f}, // {-0.5f, 0.0f, 0.5f, 0.0f}, // { 0.0f, 1.0f, 0.0f, 0.0f} // }; // // public static float linear(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // return a * (1 - x) + b * x; // } // // public static float smoothStep(float a, float b, float x) { // if (x <= 0) { // return a; // } // if (x >= 1) { // return b; // } // x = x * x * (3 - 2 * x); // return a * (1 - x) + b * x; // } // // // http://www.java-gaming.org/index.php?topic=24122.0 // public static void catmullRomSpline(float x, float[] result, float[]... knots) { // int nknots = knots.length; // int nspans = nknots - 3; // int knot = 0; // if (nspans < 1) { // throw new IllegalArgumentException("Spline has too few knots"); // } // x = MathX.clamp(x, 0, 0.9999f) * nspans; // // int span = (int) x; // if (span >= nknots - 3) { // span = nknots - 3; // } // // x -= span; // knot += span; // // int dimension = result.length; // for (int i = 0; i < dimension; i++) { // float knot0 = knots[knot][i]; // float knot1 = knots[knot + 1][i]; // float knot2 = knots[knot + 2][i]; // float knot3 = knots[knot + 3][i]; // // float c3 = CR[0][0] * knot0 + CR[0][1] * knot1 + CR[0][2] * knot2 + CR[0][3] * knot3; // float c2 = CR[1][0] * knot0 + CR[1][1] * knot1 + CR[1][2] * knot2 + CR[1][3] * knot3; // float c1 = CR[2][0] * knot0 + CR[2][1] * knot1 + CR[2][2] * knot2 + CR[2][3] * knot3; // float c0 = CR[3][0] * knot0 + CR[3][1] * knot1 + CR[3][2] * knot2 + CR[3][3] * knot3; // // result[i] = ((c3 * x + c2) * x + c1) * x + c0; // } // } // // private Interpolation() { // } // } // Path: src/main/java/info/ata4/minecraft/dragon/client/model/anim/CircularBuffer.java import info.ata4.minecraft.dragon.util.math.Interpolation; import java.util.Arrays; /* ** 2012 March 19 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.client.model.anim; /** * Very simple fixed size circular buffer implementation for animation purposes. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class CircularBuffer { private float buffer[]; private int index = 0; public CircularBuffer(int size) { buffer = new float[size]; } public void fill(float value) { Arrays.fill(buffer, value); } public void update(float value) { // move forward index++; // restart pointer at the end to form a virtual ring index %= buffer.length; buffer[index] = value; } public float get(float x, int offset) { int i = index - offset; int len = buffer.length - 1;
return Interpolation.linear(buffer[i - 1 & len], buffer[i & len], x);
ata4/dragon-mounts
src/main/java/info/ata4/minecraft/dragon/client/handler/DragonSplash.java
// Path: src/main/java/info/ata4/minecraft/dragon/DragonMounts.java // @Mod( // modid = DragonMounts.ID, // name = DragonMounts.NAME, // version = DragonMounts.VERSION, // useMetadata = true, // guiFactory = "info.ata4.minecraft.dragon.DragonMountsConfigGuiFactory" // ) // public class DragonMounts { // // public static final String NAME = "Dragon Mounts"; // public static final String ID = "DragonMounts"; // public static final String AID = ID.toLowerCase(); // public static final String VERSION = "@VERSION@"; // // @SidedProxy( // serverSide = "info.ata4.minecraft.dragon.server.CommonProxy", // clientSide = "info.ata4.minecraft.dragon.client.ClientProxy" // ) // public static CommonProxy proxy; // // @Instance(ID) // public static DragonMounts instance; // // private ModMetadata metadata; // private DragonMountsConfig config; // // public DragonMountsConfig getConfig() { // return config; // } // // public ModMetadata getMetadata() { // return metadata; // } // // @EventHandler // public void onPreInit(FMLPreInitializationEvent evt) { // config = new DragonMountsConfig(new Configuration(evt.getSuggestedConfigurationFile())); // metadata = evt.getModMetadata(); // proxy.onPreInit(evt); // } // // @EventHandler // public void onInit(FMLInitializationEvent evt) { // proxy.onInit(evt); // } // // @EventHandler // public void onPostInit(FMLPostInitializationEvent event) { // proxy.onPostInit(event); // } // // @EventHandler // public void onServerStarting(FMLServerStartingEvent evt) { // proxy.onServerStarting(evt); // } // // @EventHandler // public void onServerStopped(FMLServerStoppedEvent evt) { // proxy.onServerStopped(evt); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/util/reflection/PrivateAccessor.java // public interface PrivateAccessor { // // static final String[] GUIMAINMENU_SPLASHTEXT = new String[] {"splashText", "field_73975_c"}; // // default boolean entityIsJumping(EntityLivingBase entity) { // return ReflectionHelper.getPrivateValue(EntityLivingBase.class, entity, // new String[] {"isJumping", "field_70703_bu"}); // } // // default String mainMenuGetSplashText(GuiMainMenu menu) { // return ReflectionHelper.getPrivateValue(GuiMainMenu.class, menu, // GUIMAINMENU_SPLASHTEXT); // } // // default void mainMenuSetSplashText(GuiMainMenu menu, String splash) { // ReflectionHelper.setPrivateValue(GuiMainMenu.class, menu, splash, // GUIMAINMENU_SPLASHTEXT); // } // }
import info.ata4.minecraft.dragon.DragonMounts; import info.ata4.minecraft.dragon.util.reflection.PrivateAccessor; import java.io.InputStream; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* ** 2014 January 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.client.handler; /** * Replaces the splash text with a random custom one sometimes. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class DragonSplash implements PrivateAccessor { private static final Logger L = LogManager.getLogger();
// Path: src/main/java/info/ata4/minecraft/dragon/DragonMounts.java // @Mod( // modid = DragonMounts.ID, // name = DragonMounts.NAME, // version = DragonMounts.VERSION, // useMetadata = true, // guiFactory = "info.ata4.minecraft.dragon.DragonMountsConfigGuiFactory" // ) // public class DragonMounts { // // public static final String NAME = "Dragon Mounts"; // public static final String ID = "DragonMounts"; // public static final String AID = ID.toLowerCase(); // public static final String VERSION = "@VERSION@"; // // @SidedProxy( // serverSide = "info.ata4.minecraft.dragon.server.CommonProxy", // clientSide = "info.ata4.minecraft.dragon.client.ClientProxy" // ) // public static CommonProxy proxy; // // @Instance(ID) // public static DragonMounts instance; // // private ModMetadata metadata; // private DragonMountsConfig config; // // public DragonMountsConfig getConfig() { // return config; // } // // public ModMetadata getMetadata() { // return metadata; // } // // @EventHandler // public void onPreInit(FMLPreInitializationEvent evt) { // config = new DragonMountsConfig(new Configuration(evt.getSuggestedConfigurationFile())); // metadata = evt.getModMetadata(); // proxy.onPreInit(evt); // } // // @EventHandler // public void onInit(FMLInitializationEvent evt) { // proxy.onInit(evt); // } // // @EventHandler // public void onPostInit(FMLPostInitializationEvent event) { // proxy.onPostInit(event); // } // // @EventHandler // public void onServerStarting(FMLServerStartingEvent evt) { // proxy.onServerStarting(evt); // } // // @EventHandler // public void onServerStopped(FMLServerStoppedEvent evt) { // proxy.onServerStopped(evt); // } // } // // Path: src/main/java/info/ata4/minecraft/dragon/util/reflection/PrivateAccessor.java // public interface PrivateAccessor { // // static final String[] GUIMAINMENU_SPLASHTEXT = new String[] {"splashText", "field_73975_c"}; // // default boolean entityIsJumping(EntityLivingBase entity) { // return ReflectionHelper.getPrivateValue(EntityLivingBase.class, entity, // new String[] {"isJumping", "field_70703_bu"}); // } // // default String mainMenuGetSplashText(GuiMainMenu menu) { // return ReflectionHelper.getPrivateValue(GuiMainMenu.class, menu, // GUIMAINMENU_SPLASHTEXT); // } // // default void mainMenuSetSplashText(GuiMainMenu menu, String splash) { // ReflectionHelper.setPrivateValue(GuiMainMenu.class, menu, splash, // GUIMAINMENU_SPLASHTEXT); // } // } // Path: src/main/java/info/ata4/minecraft/dragon/client/handler/DragonSplash.java import info.ata4.minecraft.dragon.DragonMounts; import info.ata4.minecraft.dragon.util.reflection.PrivateAccessor; import java.io.InputStream; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* ** 2014 January 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.minecraft.dragon.client.handler; /** * Replaces the splash text with a random custom one sometimes. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class DragonSplash implements PrivateAccessor { private static final Logger L = LogManager.getLogger();
private static final ResourceLocation RESOURCE_SPLASHES = new ResourceLocation(DragonMounts.AID, "splashes.txt");
strandls/alchemy-rest-client-generator
src/test/java/com/strandls/alchemy/rest/client/TestExceptionMapper.java
// Path: src/main/java/com/strandls/alchemy/rest/client/exception/ThrowableToResponseMapper.java // @Slf4j // @Singleton // public class ThrowableToResponseMapper implements Function<Throwable, Response> { // /** // * The object mapper to be used. // */ // private final ObjectMapper exceptionObjectMapper; // // /** // * @param exceptionObjectMapper // */ // @Inject // public ThrowableToResponseMapper(@ThrowableObjectMapper final ObjectMapper exceptionObjectMapper) { // this.exceptionObjectMapper = exceptionObjectMapper; // } // // /* // * (non-Javadoc) // * @see com.google.common.base.Function#apply(java.lang.Object) // */ // @Override // public Response apply(final Throwable input) { // // final ExceptionPayload payLoad = new ExceptionPayload(input); // try { // final int statusCode = // input instanceof WebApplicationException ? ((WebApplicationException) input) // .getResponse().getStatus() : Status.INTERNAL_SERVER_ERROR // .getStatusCode(); // // return Response.status(Status.fromStatusCode(statusCode)) // .entity(exceptionObjectMapper.writeValueAsString(payLoad)).build(); // } catch (final JsonProcessingException e) { // log.warn("Error deserializing exception.", e); // return Response.status(Status.INTERNAL_SERVER_ERROR).entity(input.getMessage()).build(); // } // } // }
import javax.inject.Inject; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import lombok.RequiredArgsConstructor; import com.strandls.alchemy.rest.client.exception.ThrowableToResponseMapper;
/* * Copyright (C) 2015 Strand Life Sciences. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.strandls.alchemy.rest.client; /** * Mapper for testing exceptions. * * @author Ashish Shinde * */ @Provider @RequiredArgsConstructor(onConstructor = @_(@Inject)) public class TestExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> { /** * The response mapper. */
// Path: src/main/java/com/strandls/alchemy/rest/client/exception/ThrowableToResponseMapper.java // @Slf4j // @Singleton // public class ThrowableToResponseMapper implements Function<Throwable, Response> { // /** // * The object mapper to be used. // */ // private final ObjectMapper exceptionObjectMapper; // // /** // * @param exceptionObjectMapper // */ // @Inject // public ThrowableToResponseMapper(@ThrowableObjectMapper final ObjectMapper exceptionObjectMapper) { // this.exceptionObjectMapper = exceptionObjectMapper; // } // // /* // * (non-Javadoc) // * @see com.google.common.base.Function#apply(java.lang.Object) // */ // @Override // public Response apply(final Throwable input) { // // final ExceptionPayload payLoad = new ExceptionPayload(input); // try { // final int statusCode = // input instanceof WebApplicationException ? ((WebApplicationException) input) // .getResponse().getStatus() : Status.INTERNAL_SERVER_ERROR // .getStatusCode(); // // return Response.status(Status.fromStatusCode(statusCode)) // .entity(exceptionObjectMapper.writeValueAsString(payLoad)).build(); // } catch (final JsonProcessingException e) { // log.warn("Error deserializing exception.", e); // return Response.status(Status.INTERNAL_SERVER_ERROR).entity(input.getMessage()).build(); // } // } // } // Path: src/test/java/com/strandls/alchemy/rest/client/TestExceptionMapper.java import javax.inject.Inject; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import lombok.RequiredArgsConstructor; import com.strandls.alchemy.rest.client.exception.ThrowableToResponseMapper; /* * Copyright (C) 2015 Strand Life Sciences. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.strandls.alchemy.rest.client; /** * Mapper for testing exceptions. * * @author Ashish Shinde * */ @Provider @RequiredArgsConstructor(onConstructor = @_(@Inject)) public class TestExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> { /** * The response mapper. */
private final ThrowableToResponseMapper responseMapper;
strandls/alchemy-rest-client-generator
src/test/java/com/strandls/alchemy/rest/client/ExceptionObjectMapperModule.java
// Path: src/main/java/com/strandls/alchemy/rest/client/exception/ThrowableMaskMixin.java // public abstract class ThrowableMaskMixin { // @JsonIgnore // public abstract Throwable getCause(); // // @JsonIgnore // public abstract StackTraceElement[] getStackTrace(); // // @JsonIgnore // public abstract Throwable[] getSuppressed(); // }
import javax.inject.Singleton; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.strandls.alchemy.rest.client.exception.ThrowableMaskMixin; import com.strandls.alchemy.rest.client.exception.ThrowableObjectMapper;
/* * Copyright (C) 2015 Strand Life Sciences. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.strandls.alchemy.rest.client; /** * Binding for {@link ObjectMapper} used for server side error conversions. * * @author Ashish Shinde * */ public class ExceptionObjectMapperModule extends AbstractModule { /* * (non-Javadoc) * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { } /** * Binding for throwable exception mapper. * * @param mapper * @return */ @Provides @Singleton @ThrowableObjectMapper public ObjectMapper getExceptionObjectMapper(final ObjectMapper mapper) { // can't copy owing to bug - // https://github.com/FasterXML/jackson-databind/issues/245 final ObjectMapper exceptionMapper = mapper; exceptionMapper.registerModule(new SimpleModule() { /** * The serial version id. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * @see * com.fasterxml.jackson.databind.module.SimpleModule#setupModule * (com.fasterxml.jackson.databind.Module.SetupContext) */ @Override public void setupModule(final SetupContext context) {
// Path: src/main/java/com/strandls/alchemy/rest/client/exception/ThrowableMaskMixin.java // public abstract class ThrowableMaskMixin { // @JsonIgnore // public abstract Throwable getCause(); // // @JsonIgnore // public abstract StackTraceElement[] getStackTrace(); // // @JsonIgnore // public abstract Throwable[] getSuppressed(); // } // Path: src/test/java/com/strandls/alchemy/rest/client/ExceptionObjectMapperModule.java import javax.inject.Singleton; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.strandls.alchemy.rest.client.exception.ThrowableMaskMixin; import com.strandls.alchemy.rest.client.exception.ThrowableObjectMapper; /* * Copyright (C) 2015 Strand Life Sciences. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.strandls.alchemy.rest.client; /** * Binding for {@link ObjectMapper} used for server side error conversions. * * @author Ashish Shinde * */ public class ExceptionObjectMapperModule extends AbstractModule { /* * (non-Javadoc) * @see com.google.inject.AbstractModule#configure() */ @Override protected void configure() { } /** * Binding for throwable exception mapper. * * @param mapper * @return */ @Provides @Singleton @ThrowableObjectMapper public ObjectMapper getExceptionObjectMapper(final ObjectMapper mapper) { // can't copy owing to bug - // https://github.com/FasterXML/jackson-databind/issues/245 final ObjectMapper exceptionMapper = mapper; exceptionMapper.registerModule(new SimpleModule() { /** * The serial version id. */ private static final long serialVersionUID = 1L; /* * (non-Javadoc) * @see * com.fasterxml.jackson.databind.module.SimpleModule#setupModule * (com.fasterxml.jackson.databind.Module.SetupContext) */ @Override public void setupModule(final SetupContext context) {
context.setMixInAnnotations(Exception.class, ThrowableMaskMixin.class);
strandls/alchemy-rest-client-generator
src/test/java/com/strandls/alchemy/rest/client/AlchemyRestClientFactoryTest.java
// Path: src/main/java/com/strandls/alchemy/rest/client/reader/VoidMessageBodyReader.java // @Provider // @Produces(MediaType.APPLICATION_OCTET_STREAM) // @Consumes(MediaType.APPLICATION_OCTET_STREAM) // public class VoidMessageBodyReader implements MessageBodyReader<Object> { // // /* // * (non-Javadoc) // * @see javax.ws.rs.ext.MessageBodyReader#isReadable(java.lang.Class, // * java.lang.reflect.Type, java.lang.annotation.Annotation[], // * javax.ws.rs.core.MediaType) // */ // @Override // public boolean isReadable(final Class<?> type, final Type genericType, // final Annotation[] annotations, final MediaType mediaType) { // return Void.TYPE.equals(genericType) // && MediaType.APPLICATION_OCTET_STREAM_TYPE.equals(mediaType); // } // // /* // * (non-Javadoc) // * @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, // * java.lang.reflect.Type, java.lang.annotation.Annotation[], // * javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, // * java.io.InputStream) // */ // @Override // public Void readFrom(final Class<Object> type, final Type genericType, // final Annotation[] annotations, final MediaType mediaType, // final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) // throws IOException, WebApplicationException { // return null; // } // // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import javax.ws.rs.NotFoundException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.core.Application; import lombok.Cleanup; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ObjectUtils; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.BodyPartEntity; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.FormDataParam; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import org.reflections.ReflectionUtils; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.google.common.base.Predicate; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.name.Names; import com.strandls.alchemy.rest.client.reader.VoidMessageBodyReader;
/* * (non-Javadoc) * @see org.glassfish.jersey.test.JerseyTest#configure() */ @Override protected Application configure() { final ResourceConfig application = new ResourceConfig(TestWebserviceWithPath.class, TestWebserviceWithPutDelete.class, TestWebserviceMultipart.class, TestWebserviceExceptionHandling.class, JacksonJsonProvider.class); final Injector injector = Guice.createInjector(new ClientModule(), new ExceptionObjectMapperModule()); // register multi part feature. application.register(MultiPartFeature.class); // register the application mapper. application.register(injector.getInstance(TestExceptionMapper.class)); return application; } /* * (non-Javadoc) * @see * org.glassfish.jersey.test.JerseyTest#configureClient(org.glassfish.jersey * .client.ClientConfig) */ @Override protected void configureClient(final ClientConfig config) { super.configureClient(config);
// Path: src/main/java/com/strandls/alchemy/rest/client/reader/VoidMessageBodyReader.java // @Provider // @Produces(MediaType.APPLICATION_OCTET_STREAM) // @Consumes(MediaType.APPLICATION_OCTET_STREAM) // public class VoidMessageBodyReader implements MessageBodyReader<Object> { // // /* // * (non-Javadoc) // * @see javax.ws.rs.ext.MessageBodyReader#isReadable(java.lang.Class, // * java.lang.reflect.Type, java.lang.annotation.Annotation[], // * javax.ws.rs.core.MediaType) // */ // @Override // public boolean isReadable(final Class<?> type, final Type genericType, // final Annotation[] annotations, final MediaType mediaType) { // return Void.TYPE.equals(genericType) // && MediaType.APPLICATION_OCTET_STREAM_TYPE.equals(mediaType); // } // // /* // * (non-Javadoc) // * @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, // * java.lang.reflect.Type, java.lang.annotation.Annotation[], // * javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, // * java.io.InputStream) // */ // @Override // public Void readFrom(final Class<Object> type, final Type genericType, // final Annotation[] annotations, final MediaType mediaType, // final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) // throws IOException, WebApplicationException { // return null; // } // // } // Path: src/test/java/com/strandls/alchemy/rest/client/AlchemyRestClientFactoryTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import javax.ws.rs.NotFoundException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.core.Application; import lombok.Cleanup; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ObjectUtils; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.BodyPartEntity; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.FormDataParam; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; import org.junit.Before; import org.junit.Test; import org.reflections.ReflectionUtils; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.google.common.base.Predicate; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.name.Names; import com.strandls.alchemy.rest.client.reader.VoidMessageBodyReader; /* * (non-Javadoc) * @see org.glassfish.jersey.test.JerseyTest#configure() */ @Override protected Application configure() { final ResourceConfig application = new ResourceConfig(TestWebserviceWithPath.class, TestWebserviceWithPutDelete.class, TestWebserviceMultipart.class, TestWebserviceExceptionHandling.class, JacksonJsonProvider.class); final Injector injector = Guice.createInjector(new ClientModule(), new ExceptionObjectMapperModule()); // register multi part feature. application.register(MultiPartFeature.class); // register the application mapper. application.register(injector.getInstance(TestExceptionMapper.class)); return application; } /* * (non-Javadoc) * @see * org.glassfish.jersey.test.JerseyTest#configureClient(org.glassfish.jersey * .client.ClientConfig) */ @Override protected void configureClient(final ClientConfig config) { super.configureClient(config);
config.register(VoidMessageBodyReader.class);
ops4j/org.ops4j.pax.shiro
pax-shiro-cdi-web/src/main/java/org/ops4j/pax/shiro/cdi/web/CdiWebIniSecurityManagerFactory.java
// Path: pax-shiro-cdi/src/main/java/org/ops4j/pax/shiro/cdi/impl/NamedBeanMap.java // public class NamedBeanMap implements Map<String, Object> { // // private static Logger log = LoggerFactory.getLogger(NamedBeanMap.class); // // private Map<String, Object> beans = new HashMap<String, Object>(); // // /** // * // */ // public NamedBeanMap(BeanManager beanManager) { // for (Bean<?> bean : beanManager.getBeans(Object.class, ShiroIniLiteral.INSTANCE)) { // String beanName = getShiroBeanName(bean); // if (beanName == null) { // log.warn("Shiro cannot derive a default name for [{}], " // + "so this bean cannot be referenced in shiro.ini. " // + "Consider adding a @Named qualifier.", bean); // } // else { // log.debug("Found @ShiroIni bean with name [{}]", beanName); // CreationalContext<Object> cc = beanManager.createCreationalContext(null); // Object object = beanManager.getReference(bean, Object.class, cc); // beans.put(beanName, object); // } // } // } // // /** // * @param bean // * @return // */ // private String getShiroBeanName(Bean<?> bean) { // String beanName = bean.getName(); // if (beanName == null) { // if (bean.getTypes().contains(bean.getBeanClass())) { // String className = bean.getBeanClass().getSimpleName(); // char first = Character.toLowerCase(className.charAt(0)); // beanName = first + className.substring(1); // } // } // return beanName; // } // // public int size() { // return beans.size(); // } // // public boolean isEmpty() { // return beans.isEmpty(); // } // // public boolean containsKey(Object key) { // return beans.containsKey(key); // } // // public boolean containsValue(Object value) { // throw new UnsupportedOperationException(); // } // // public Object get(Object key) { // return beans.get(key); // } // // public Object put(String key, Object value) { // throw new UnsupportedOperationException(); // } // // public Object remove(Object key) { // throw new UnsupportedOperationException(); // } // // public void putAll(Map<? extends String, ? extends Object> m) { // throw new UnsupportedOperationException(); // } // // public void clear() { // throw new UnsupportedOperationException(); // } // // public Set<String> keySet() { // return beans.keySet(); // } // // public Collection<Object> values() { // return beans.values(); // } // // public Set<java.util.Map.Entry<String, Object>> entrySet() { // return beans.entrySet(); // } // }
import java.util.Map; import javax.enterprise.inject.spi.BeanManager; import org.apache.shiro.config.Ini; import org.apache.shiro.config.Ini.Section; import org.apache.shiro.web.config.WebIniSecurityManagerFactory; import org.ops4j.pax.shiro.cdi.impl.NamedBeanMap;
/* * Copyright 2013 Harald Wellmann * * 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 org.ops4j.pax.shiro.cdi.web; /** * A CDI-aware extension of {@link WebIniSecurityManagerFactory}. Constructs a named bean * map from the CDI BeanManager and uses these beans as additional default for Shiro * bean lookup. * * @author Harald Wellmann * */ public class CdiWebIniSecurityManagerFactory extends WebIniSecurityManagerFactory { private Map<String, ?> namedBeanMap; public CdiWebIniSecurityManagerFactory(BeanManager beanManager) {
// Path: pax-shiro-cdi/src/main/java/org/ops4j/pax/shiro/cdi/impl/NamedBeanMap.java // public class NamedBeanMap implements Map<String, Object> { // // private static Logger log = LoggerFactory.getLogger(NamedBeanMap.class); // // private Map<String, Object> beans = new HashMap<String, Object>(); // // /** // * // */ // public NamedBeanMap(BeanManager beanManager) { // for (Bean<?> bean : beanManager.getBeans(Object.class, ShiroIniLiteral.INSTANCE)) { // String beanName = getShiroBeanName(bean); // if (beanName == null) { // log.warn("Shiro cannot derive a default name for [{}], " // + "so this bean cannot be referenced in shiro.ini. " // + "Consider adding a @Named qualifier.", bean); // } // else { // log.debug("Found @ShiroIni bean with name [{}]", beanName); // CreationalContext<Object> cc = beanManager.createCreationalContext(null); // Object object = beanManager.getReference(bean, Object.class, cc); // beans.put(beanName, object); // } // } // } // // /** // * @param bean // * @return // */ // private String getShiroBeanName(Bean<?> bean) { // String beanName = bean.getName(); // if (beanName == null) { // if (bean.getTypes().contains(bean.getBeanClass())) { // String className = bean.getBeanClass().getSimpleName(); // char first = Character.toLowerCase(className.charAt(0)); // beanName = first + className.substring(1); // } // } // return beanName; // } // // public int size() { // return beans.size(); // } // // public boolean isEmpty() { // return beans.isEmpty(); // } // // public boolean containsKey(Object key) { // return beans.containsKey(key); // } // // public boolean containsValue(Object value) { // throw new UnsupportedOperationException(); // } // // public Object get(Object key) { // return beans.get(key); // } // // public Object put(String key, Object value) { // throw new UnsupportedOperationException(); // } // // public Object remove(Object key) { // throw new UnsupportedOperationException(); // } // // public void putAll(Map<? extends String, ? extends Object> m) { // throw new UnsupportedOperationException(); // } // // public void clear() { // throw new UnsupportedOperationException(); // } // // public Set<String> keySet() { // return beans.keySet(); // } // // public Collection<Object> values() { // return beans.values(); // } // // public Set<java.util.Map.Entry<String, Object>> entrySet() { // return beans.entrySet(); // } // } // Path: pax-shiro-cdi-web/src/main/java/org/ops4j/pax/shiro/cdi/web/CdiWebIniSecurityManagerFactory.java import java.util.Map; import javax.enterprise.inject.spi.BeanManager; import org.apache.shiro.config.Ini; import org.apache.shiro.config.Ini.Section; import org.apache.shiro.web.config.WebIniSecurityManagerFactory; import org.ops4j.pax.shiro.cdi.impl.NamedBeanMap; /* * Copyright 2013 Harald Wellmann * * 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 org.ops4j.pax.shiro.cdi.web; /** * A CDI-aware extension of {@link WebIniSecurityManagerFactory}. Constructs a named bean * map from the CDI BeanManager and uses these beans as additional default for Shiro * bean lookup. * * @author Harald Wellmann * */ public class CdiWebIniSecurityManagerFactory extends WebIniSecurityManagerFactory { private Map<String, ?> namedBeanMap; public CdiWebIniSecurityManagerFactory(BeanManager beanManager) {
this.namedBeanMap = new NamedBeanMap(beanManager);
ops4j/org.ops4j.pax.shiro
pax-shiro-cdi-web/src/main/java/org/ops4j/pax/shiro/cdi/web/CdiIniWebEnvironment.java
// Path: pax-shiro-cdi/src/main/java/org/ops4j/pax/shiro/cdi/impl/BeanManagerProvider.java // public class BeanManagerProvider { // // private static BeanManager beanManager; // // // /** Hidden constructor. */ // private BeanManagerProvider() { // } // // /** // * Looks up the current bean manager in JNDI, or returns the value set by // * {@link #setBeanManager(BeanManager)} as fallback. // * // * @return // */ // public static BeanManager getBeanManager() { // try { // InitialContext initialContext = new InitialContext(); // return (BeanManager) initialContext.lookup("java:comp/BeanManager"); // } // catch (NamingException e) { // if (beanManager != null) { // return beanManager; // } // throw new IllegalStateException( // "BeanManager not found in JNDI and not set via setBeanManager()"); // } // } // // /** // * @param beanManager // * the beanManager to set // */ // public static void setBeanManager(BeanManager beanManager) { // BeanManagerProvider.beanManager = beanManager; // } // // }
import java.util.Map; import javax.enterprise.inject.spi.BeanManager; import org.apache.shiro.config.Ini; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.util.CollectionUtils; import org.apache.shiro.web.env.IniWebEnvironment; import org.apache.shiro.web.mgt.WebSecurityManager; import org.ops4j.pax.shiro.cdi.impl.BeanManagerProvider;
/* * Copyright 2013 Harald Wellmann * * 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 org.ops4j.pax.shiro.cdi.web; /** * An extension of {@link IniWebEnvironment} which makes CDI beans qualified with * {@code @ShiroIni} available to Shiro, to be referenced in INI files. * * @author Harald Wellmann */ public class CdiIniWebEnvironment extends IniWebEnvironment { @Override protected WebSecurityManager createWebSecurityManager() { Ini ini = getIni(); if (CollectionUtils.isEmpty(ini)) { ini = null; }
// Path: pax-shiro-cdi/src/main/java/org/ops4j/pax/shiro/cdi/impl/BeanManagerProvider.java // public class BeanManagerProvider { // // private static BeanManager beanManager; // // // /** Hidden constructor. */ // private BeanManagerProvider() { // } // // /** // * Looks up the current bean manager in JNDI, or returns the value set by // * {@link #setBeanManager(BeanManager)} as fallback. // * // * @return // */ // public static BeanManager getBeanManager() { // try { // InitialContext initialContext = new InitialContext(); // return (BeanManager) initialContext.lookup("java:comp/BeanManager"); // } // catch (NamingException e) { // if (beanManager != null) { // return beanManager; // } // throw new IllegalStateException( // "BeanManager not found in JNDI and not set via setBeanManager()"); // } // } // // /** // * @param beanManager // * the beanManager to set // */ // public static void setBeanManager(BeanManager beanManager) { // BeanManagerProvider.beanManager = beanManager; // } // // } // Path: pax-shiro-cdi-web/src/main/java/org/ops4j/pax/shiro/cdi/web/CdiIniWebEnvironment.java import java.util.Map; import javax.enterprise.inject.spi.BeanManager; import org.apache.shiro.config.Ini; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.util.CollectionUtils; import org.apache.shiro.web.env.IniWebEnvironment; import org.apache.shiro.web.mgt.WebSecurityManager; import org.ops4j.pax.shiro.cdi.impl.BeanManagerProvider; /* * Copyright 2013 Harald Wellmann * * 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 org.ops4j.pax.shiro.cdi.web; /** * An extension of {@link IniWebEnvironment} which makes CDI beans qualified with * {@code @ShiroIni} available to Shiro, to be referenced in INI files. * * @author Harald Wellmann */ public class CdiIniWebEnvironment extends IniWebEnvironment { @Override protected WebSecurityManager createWebSecurityManager() { Ini ini = getIni(); if (CollectionUtils.isEmpty(ini)) { ini = null; }
BeanManager beanManager = BeanManagerProvider.getBeanManager();
shevek/tftp4j
tftp-server-mina/src/test/java/org/anarres/tftp/server/mina/TftpServerTest.java
// Path: tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java // public class TftpServerTester { // // private static final Random RANDOM = new Random(); // private final TftpMemoryDataProvider provider = new TftpMemoryDataProvider(); // private final TFTPClient client = new TFTPClient(); // // @Nonnull // public TftpMemoryDataProvider getProvider() { // return provider; // } // // @Nonnegative // public int getPort() { // return 1067; // } // // private void assertSucceeds(String path, int mode) throws Exception { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // client.receiveFile(path, mode, out, InetAddress.getLoopbackAddress(), getPort()); // assertArrayEquals(provider.getData(path), out.toByteArray()); // } // // private void assertFails(String path, int mode) throws Exception { // try { // client.receiveFile(path, mode, ByteStreams.nullOutputStream(), InetAddress.getLoopbackAddress(), getPort()); // fail("Receive file " + path + "/" + mode + " succeeded unexpectedly."); // } catch (IOException e) { // } // } // // @Nonnull // public static byte[] newRandomBytes(int length) { // byte[] data = new byte[length]; // RANDOM.nextBytes(data); // return data; // } // // public void run() throws Exception { // client.open(); // // provider.setData("/hello", "Hello, world."); // // assertFails("/nonexistent", TFTPClient.BINARY_MODE); // assertFails("/nonexistent", TFTPClient.ASCII_MODE); // // assertSucceeds("/hello", TFTPClient.BINARY_MODE); // assertSucceeds("/hello", TFTPClient.ASCII_MODE); // // int[] sizes = new int[]{ // 0, // 1, // 8, // 511, // 512, // 513, // 1 * 1024 - 1, // 1 * 1024, // 1 * 1024 + 1, // 4 * 1024 - 1, // 4 * 1024, // 4 * 1024 + 1, // 1024 * 1024 - 1, // 1024 * 1024, // 1024 * 1024 + 1 // }; // // for (int size : sizes) { // byte[] data = newRandomBytes(size); // provider.setData("/binary", data); // assertSucceeds("/binary", TFTPClient.BINARY_MODE); // // provider.setData("/ascii", Base64.encodeBase64(data)); // assertSucceeds("/ascii", TFTPClient.ASCII_MODE); // } // // client.close(); // // } // }
import org.anarres.tftp.protocol.engine.TftpServerTester; import org.junit.Test;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpServerTest { @Test public void testServer() throws Exception {
// Path: tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java // public class TftpServerTester { // // private static final Random RANDOM = new Random(); // private final TftpMemoryDataProvider provider = new TftpMemoryDataProvider(); // private final TFTPClient client = new TFTPClient(); // // @Nonnull // public TftpMemoryDataProvider getProvider() { // return provider; // } // // @Nonnegative // public int getPort() { // return 1067; // } // // private void assertSucceeds(String path, int mode) throws Exception { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // client.receiveFile(path, mode, out, InetAddress.getLoopbackAddress(), getPort()); // assertArrayEquals(provider.getData(path), out.toByteArray()); // } // // private void assertFails(String path, int mode) throws Exception { // try { // client.receiveFile(path, mode, ByteStreams.nullOutputStream(), InetAddress.getLoopbackAddress(), getPort()); // fail("Receive file " + path + "/" + mode + " succeeded unexpectedly."); // } catch (IOException e) { // } // } // // @Nonnull // public static byte[] newRandomBytes(int length) { // byte[] data = new byte[length]; // RANDOM.nextBytes(data); // return data; // } // // public void run() throws Exception { // client.open(); // // provider.setData("/hello", "Hello, world."); // // assertFails("/nonexistent", TFTPClient.BINARY_MODE); // assertFails("/nonexistent", TFTPClient.ASCII_MODE); // // assertSucceeds("/hello", TFTPClient.BINARY_MODE); // assertSucceeds("/hello", TFTPClient.ASCII_MODE); // // int[] sizes = new int[]{ // 0, // 1, // 8, // 511, // 512, // 513, // 1 * 1024 - 1, // 1 * 1024, // 1 * 1024 + 1, // 4 * 1024 - 1, // 4 * 1024, // 4 * 1024 + 1, // 1024 * 1024 - 1, // 1024 * 1024, // 1024 * 1024 + 1 // }; // // for (int size : sizes) { // byte[] data = newRandomBytes(size); // provider.setData("/binary", data); // assertSucceeds("/binary", TFTPClient.BINARY_MODE); // // provider.setData("/ascii", Base64.encodeBase64(data)); // assertSucceeds("/ascii", TFTPClient.ASCII_MODE); // } // // client.close(); // // } // } // Path: tftp-server-mina/src/test/java/org/anarres/tftp/server/mina/TftpServerTest.java import org.anarres.tftp.protocol.engine.TftpServerTester; import org.junit.Test; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpServerTest { @Test public void testServer() throws Exception {
TftpServerTester tester = new TftpServerTester();
shevek/tftp4j
tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpTransferProtocolHandler.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // }
import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.service.IoService; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ // TODO: Re-code this to use a window of (say) 8 packets. public class TftpTransferProtocolHandler extends IoHandlerAdapter implements IoFutureListener<ConnectFuture> { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferProtocolHandler.class); private final IoService connector;
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // Path: tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpTransferProtocolHandler.java import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.service.IoService; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ // TODO: Re-code this to use a window of (say) 8 packets. public class TftpTransferProtocolHandler extends IoHandlerAdapter implements IoFutureListener<ConnectFuture> { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferProtocolHandler.class); private final IoService connector;
private final TftpTransfer<IoSession> transfer;
shevek/tftp4j
tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpTransferProtocolHandler.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // }
import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.service.IoService; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ // TODO: Re-code this to use a window of (say) 8 packets. public class TftpTransferProtocolHandler extends IoHandlerAdapter implements IoFutureListener<ConnectFuture> { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferProtocolHandler.class); private final IoService connector; private final TftpTransfer<IoSession> transfer; public TftpTransferProtocolHandler(@Nonnull IoService connector, @Nonnull TftpTransfer<IoSession> transfer) { this.connector = connector; this.transfer = transfer; } @Override public void operationComplete(ConnectFuture future) { if (!future.isConnected()) { connector.dispose(false); return; } final IoSession session = future.getSession(); try { // This does "real" I/O, so can really throw an exception. transfer.open(session); } catch (Exception e) { session.close(true); } } @Override public void messageReceived(IoSession session, Object message) throws Exception {
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // Path: tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpTransferProtocolHandler.java import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.IoFutureListener; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.service.IoService; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ // TODO: Re-code this to use a window of (say) 8 packets. public class TftpTransferProtocolHandler extends IoHandlerAdapter implements IoFutureListener<ConnectFuture> { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferProtocolHandler.class); private final IoService connector; private final TftpTransfer<IoSession> transfer; public TftpTransferProtocolHandler(@Nonnull IoService connector, @Nonnull TftpTransfer<IoSession> transfer) { this.connector = connector; this.transfer = transfer; } @Override public void operationComplete(ConnectFuture future) { if (!future.isConnected()) { connector.dispose(false); return; } final IoSession session = future.getSession(); try { // This does "real" I/O, so can really throw an exception. transfer.open(session); } catch (Exception e) { session.close(true); } } @Override public void messageReceived(IoSession session, Object message) throws Exception {
TftpPacket packet = (TftpPacket) message;
shevek/tftp4j
tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpTransferHandler.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpTransferHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferHandler.class);
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpTransferHandler.java import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpTransferHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferHandler.class);
private final TftpTransfer<Channel> transfer;
shevek/tftp4j
tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpTransferHandler.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpTransferHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferHandler.class); private final TftpTransfer<Channel> transfer; public TftpTransferHandler(@Nonnull TftpTransfer<Channel> transfer) throws IOException { this.transfer = transfer; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); transfer.open(ctx.channel()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try {
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java // public interface TftpTransfer<TftpTransferContext> { // // /** // * Opens this TftpTransfer and sends the initial packets. // * // * Implemented by the transfer. // */ // public void open(@Nonnull TftpTransferContext context) throws Exception; // // /** // * Responds to an incoming packet on this transfer. // * // * Implemented by the transfer. // */ // public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the transfer. */ // public void timeout(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void send(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception; // // /** Implemented by the channel. */ // public void flush(@Nonnull TftpTransferContext context) throws Exception; // // /** Implemented by the channel. */ // public void close(@Nonnull TftpTransferContext context) throws Exception; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpTransferHandler.java import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.TftpTransfer; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpTransferHandler extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpTransferHandler.class); private final TftpTransfer<Channel> transfer; public TftpTransferHandler(@Nonnull TftpTransfer<Channel> transfer) throws IOException { this.transfer = transfer; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); transfer.open(ctx.channel()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try {
transfer.handle(ctx.channel(), (TftpPacket) msg);
shevek/tftp4j
tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketEncoder.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import org.anarres.tftp.protocol.packet.TftpPacket; import java.nio.ByteBuffer; import javax.annotation.Nonnull;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.codec; /** * This is an example which uses {@link ByteBuffer#allocate(int)}. * * You may wish to use your own allocator and call * {@link TftpPacket#toWire(java.nio.ByteBuffer)} yourself. * * @author shevek */ public class TftpPacketEncoder { @Nonnull
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketEncoder.java import org.anarres.tftp.protocol.packet.TftpPacket; import java.nio.ByteBuffer; import javax.annotation.Nonnull; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.codec; /** * This is an example which uses {@link ByteBuffer#allocate(int)}. * * You may wish to use your own allocator and call * {@link TftpPacket#toWire(java.nio.ByteBuffer)} yourself. * * @author shevek */ public class TftpPacketEncoder { @Nonnull
public ByteBuffer encode(@Nonnull TftpPacket packet) {
shevek/tftp4j
tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public interface TftpTransfer<TftpTransferContext> { /** * Opens this TftpTransfer and sends the initial packets. * * Implemented by the transfer. */ public void open(@Nonnull TftpTransferContext context) throws Exception; /** * Responds to an incoming packet on this transfer. * * Implemented by the transfer. */
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/TftpTransfer.java import javax.annotation.Nonnull; import org.anarres.tftp.protocol.packet.TftpPacket; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public interface TftpTransfer<TftpTransferContext> { /** * Opens this TftpTransfer and sends the initial packets. * * Implemented by the transfer. */ public void open(@Nonnull TftpTransferContext context) throws Exception; /** * Responds to an incoming packet on this transfer. * * Implemented by the transfer. */
public void handle(@Nonnull TftpTransferContext context, @Nonnull TftpPacket packet) throws Exception;
shevek/tftp4j
tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpServer.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java // public abstract class AbstractTftpServer { // // public static final int DEFAULT_SERVER_PORT = 69; // // private final TftpDataProvider dataProvider; // private final int port; // // public AbstractTftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) { // this.dataProvider = dataProvider; // this.port = port; // } // // @Nonnull // public TftpDataProvider getDataProvider() { // return dataProvider; // } // // @Nonnegative // public int getPort() { // return port; // } // // @PostConstruct // public abstract void start() throws IOException, InterruptedException; // // @PreDestroy // public abstract void stop() throws IOException, InterruptedException; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // }
import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.util.concurrent.ThreadFactory; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.AbstractTftpServer; import org.anarres.tftp.protocol.resource.TftpDataProvider;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpServer extends AbstractTftpServer { private Channel channel; private final TftpPipelineInitializer.SharedHandlers sharedHandlers = new TftpPipelineInitializer.SharedHandlers(); private TftpChannelType channelType = TftpChannelType.NIO;
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java // public abstract class AbstractTftpServer { // // public static final int DEFAULT_SERVER_PORT = 69; // // private final TftpDataProvider dataProvider; // private final int port; // // public AbstractTftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) { // this.dataProvider = dataProvider; // this.port = port; // } // // @Nonnull // public TftpDataProvider getDataProvider() { // return dataProvider; // } // // @Nonnegative // public int getPort() { // return port; // } // // @PostConstruct // public abstract void start() throws IOException, InterruptedException; // // @PreDestroy // public abstract void stop() throws IOException, InterruptedException; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // } // Path: tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpServer.java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.util.concurrent.ThreadFactory; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.AbstractTftpServer; import org.anarres.tftp.protocol.resource.TftpDataProvider; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpServer extends AbstractTftpServer { private Channel channel; private final TftpPipelineInitializer.SharedHandlers sharedHandlers = new TftpPipelineInitializer.SharedHandlers(); private TftpChannelType channelType = TftpChannelType.NIO;
public TftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) {
shevek/tftp4j
tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpServer.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java // public abstract class AbstractTftpServer { // // public static final int DEFAULT_SERVER_PORT = 69; // // private final TftpDataProvider dataProvider; // private final int port; // // public AbstractTftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) { // this.dataProvider = dataProvider; // this.port = port; // } // // @Nonnull // public TftpDataProvider getDataProvider() { // return dataProvider; // } // // @Nonnegative // public int getPort() { // return port; // } // // @PostConstruct // public abstract void start() throws IOException, InterruptedException; // // @PreDestroy // public abstract void stop() throws IOException, InterruptedException; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // }
import java.io.IOException; import java.net.InetSocketAddress; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.AbstractTftpServer; import org.anarres.tftp.protocol.resource.TftpDataProvider; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpServer extends AbstractTftpServer { private NioDatagramAcceptor acceptor;
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java // public abstract class AbstractTftpServer { // // public static final int DEFAULT_SERVER_PORT = 69; // // private final TftpDataProvider dataProvider; // private final int port; // // public AbstractTftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) { // this.dataProvider = dataProvider; // this.port = port; // } // // @Nonnull // public TftpDataProvider getDataProvider() { // return dataProvider; // } // // @Nonnegative // public int getPort() { // return port; // } // // @PostConstruct // public abstract void start() throws IOException, InterruptedException; // // @PreDestroy // public abstract void stop() throws IOException, InterruptedException; // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // } // Path: tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpServer.java import java.io.IOException; import java.net.InetSocketAddress; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.engine.AbstractTftpServer; import org.anarres.tftp.protocol.resource.TftpDataProvider; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.DatagramSessionConfig; import org.apache.mina.transport.socket.nio.NioDatagramAcceptor; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpServer extends AbstractTftpServer { private NioDatagramAcceptor acceptor;
public TftpServer(@Nonnull TftpDataProvider dataProvider, @Nonnegative int port) {
shevek/tftp4j
tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpProtocolCodecFactory.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpProtocolCodecFactory implements ProtocolCodecFactory { private static TftpProtocolCodecFactory INSTANCE = new TftpProtocolCodecFactory(); /** * Returns the singleton instance of {@link TftpProtocolCodecFactory}. * * @return The singleton instance of {@link TftpProtocolCodecFactory}. */ @Nonnull public static TftpProtocolCodecFactory getInstance() { return INSTANCE; } private static class TftpEncoder implements ProtocolEncoder { public static final TftpEncoder INSTANCE = new TftpEncoder(); @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException {
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpProtocolCodecFactory.java import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpProtocolCodecFactory implements ProtocolCodecFactory { private static TftpProtocolCodecFactory INSTANCE = new TftpProtocolCodecFactory(); /** * Returns the singleton instance of {@link TftpProtocolCodecFactory}. * * @return The singleton instance of {@link TftpProtocolCodecFactory}. */ @Nonnull public static TftpProtocolCodecFactory getInstance() { return INSTANCE; } private static class TftpEncoder implements ProtocolEncoder { public static final TftpEncoder INSTANCE = new TftpEncoder(); @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException {
TftpPacket packet = (TftpPacket) message;
shevek/tftp4j
tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpProtocolCodecFactory.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpProtocolCodecFactory implements ProtocolCodecFactory { private static TftpProtocolCodecFactory INSTANCE = new TftpProtocolCodecFactory(); /** * Returns the singleton instance of {@link TftpProtocolCodecFactory}. * * @return The singleton instance of {@link TftpProtocolCodecFactory}. */ @Nonnull public static TftpProtocolCodecFactory getInstance() { return INSTANCE; } private static class TftpEncoder implements ProtocolEncoder { public static final TftpEncoder INSTANCE = new TftpEncoder(); @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException { TftpPacket packet = (TftpPacket) message; IoBuffer buf = IoBuffer.allocate(packet.getWireLength()); packet.toWire(buf.buf()); buf.flip(); out.write(buf); } @Override public void dispose(IoSession session) throws Exception { } } @Nonnull @Override public ProtocolEncoder getEncoder(@Nonnull IoSession session) { return TftpEncoder.INSTANCE; }
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-mina/src/main/java/org/anarres/tftp/server/mina/TftpProtocolCodecFactory.java import java.io.IOException; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.apache.mina.filter.codec.ProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.mina; /** * * @author shevek */ public class TftpProtocolCodecFactory implements ProtocolCodecFactory { private static TftpProtocolCodecFactory INSTANCE = new TftpProtocolCodecFactory(); /** * Returns the singleton instance of {@link TftpProtocolCodecFactory}. * * @return The singleton instance of {@link TftpProtocolCodecFactory}. */ @Nonnull public static TftpProtocolCodecFactory getInstance() { return INSTANCE; } private static class TftpEncoder implements ProtocolEncoder { public static final TftpEncoder INSTANCE = new TftpEncoder(); @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException { TftpPacket packet = (TftpPacket) message; IoBuffer buf = IoBuffer.allocate(packet.getWireLength()); packet.toWire(buf.buf()); buf.flip(); out.write(buf); } @Override public void dispose(IoSession session) throws Exception { } } @Nonnull @Override public ProtocolEncoder getEncoder(@Nonnull IoSession session) { return TftpEncoder.INSTANCE; }
private static class TftpDecoder extends TftpPacketDecoder implements ProtocolDecoder {
shevek/tftp4j
tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // }
import java.io.IOException; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.anarres.tftp.protocol.resource.TftpDataProvider;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public abstract class AbstractTftpServer { public static final int DEFAULT_SERVER_PORT = 69;
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpDataProvider.java // public interface TftpDataProvider { // // /** // * Returns the resource with the given name. // */ // @CheckForNull // public TftpData open(@Nonnull String filename) throws IOException; // } // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/engine/AbstractTftpServer.java import java.io.IOException; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.anarres.tftp.protocol.resource.TftpDataProvider; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public abstract class AbstractTftpServer { public static final int DEFAULT_SERVER_PORT = 69;
private final TftpDataProvider dataProvider;
shevek/tftp4j
tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpMemoryDataProvider.java // public class TftpMemoryDataProvider extends AbstractTftpDataProvider { // // private final Map<String, byte[]> map = new HashMap<String, byte[]>(); // // public void setData(@Nonnull String name, @CheckForNull byte[] data) { // if (data == null) // map.remove(name); // else // map.put(name, data); // } // // public void setData(@Nonnull String name, @Nonnull String data) { // setData(name, data.getBytes(Charsets.ISO_8859_1)); // } // // @CheckForNull // public byte[] getData(String name) { // return map.get(name); // } // // @Override // public TftpData open(String filename) throws IOException { // byte[] data = getData(filename); // if (data == null) // return null; // return new TftpByteArrayData(data); // } // }
import com.google.common.io.ByteStreams; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetAddress; import java.util.Random; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.resource.TftpMemoryDataProvider; import org.apache.commons.net.tftp.TFTPClient; import org.apache.commons.net.util.Base64; import static org.junit.Assert.*;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public class TftpServerTester { private static final Random RANDOM = new Random();
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/resource/TftpMemoryDataProvider.java // public class TftpMemoryDataProvider extends AbstractTftpDataProvider { // // private final Map<String, byte[]> map = new HashMap<String, byte[]>(); // // public void setData(@Nonnull String name, @CheckForNull byte[] data) { // if (data == null) // map.remove(name); // else // map.put(name, data); // } // // public void setData(@Nonnull String name, @Nonnull String data) { // setData(name, data.getBytes(Charsets.ISO_8859_1)); // } // // @CheckForNull // public byte[] getData(String name) { // return map.get(name); // } // // @Override // public TftpData open(String filename) throws IOException { // byte[] data = getData(filename); // if (data == null) // return null; // return new TftpByteArrayData(data); // } // } // Path: tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java import com.google.common.io.ByteStreams; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetAddress; import java.util.Random; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.resource.TftpMemoryDataProvider; import org.apache.commons.net.tftp.TFTPClient; import org.apache.commons.net.util.Base64; import static org.junit.Assert.*; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.protocol.engine; /** * * @author shevek */ public class TftpServerTester { private static final Random RANDOM = new Random();
private final TftpMemoryDataProvider provider = new TftpMemoryDataProvider();
shevek/tftp4j
tftp-server-netty/src/test/java/org/anarres/tftp/server/netty/TftpServerTest.java
// Path: tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java // public class TftpServerTester { // // private static final Random RANDOM = new Random(); // private final TftpMemoryDataProvider provider = new TftpMemoryDataProvider(); // private final TFTPClient client = new TFTPClient(); // // @Nonnull // public TftpMemoryDataProvider getProvider() { // return provider; // } // // @Nonnegative // public int getPort() { // return 1067; // } // // private void assertSucceeds(String path, int mode) throws Exception { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // client.receiveFile(path, mode, out, InetAddress.getLoopbackAddress(), getPort()); // assertArrayEquals(provider.getData(path), out.toByteArray()); // } // // private void assertFails(String path, int mode) throws Exception { // try { // client.receiveFile(path, mode, ByteStreams.nullOutputStream(), InetAddress.getLoopbackAddress(), getPort()); // fail("Receive file " + path + "/" + mode + " succeeded unexpectedly."); // } catch (IOException e) { // } // } // // @Nonnull // public static byte[] newRandomBytes(int length) { // byte[] data = new byte[length]; // RANDOM.nextBytes(data); // return data; // } // // public void run() throws Exception { // client.open(); // // provider.setData("/hello", "Hello, world."); // // assertFails("/nonexistent", TFTPClient.BINARY_MODE); // assertFails("/nonexistent", TFTPClient.ASCII_MODE); // // assertSucceeds("/hello", TFTPClient.BINARY_MODE); // assertSucceeds("/hello", TFTPClient.ASCII_MODE); // // int[] sizes = new int[]{ // 0, // 1, // 8, // 511, // 512, // 513, // 1 * 1024 - 1, // 1 * 1024, // 1 * 1024 + 1, // 4 * 1024 - 1, // 4 * 1024, // 4 * 1024 + 1, // 1024 * 1024 - 1, // 1024 * 1024, // 1024 * 1024 + 1 // }; // // for (int size : sizes) { // byte[] data = newRandomBytes(size); // provider.setData("/binary", data); // assertSucceeds("/binary", TFTPClient.BINARY_MODE); // // provider.setData("/ascii", Base64.encodeBase64(data)); // assertSucceeds("/ascii", TFTPClient.ASCII_MODE); // } // // client.close(); // // } // }
import org.junit.Before; import org.junit.Test; import io.netty.util.ResourceLeakDetector; import org.anarres.tftp.protocol.engine.TftpServerTester;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpServerTest { @Before public void setUp() { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); } @Test public void testServer() throws Exception {
// Path: tftp-protocol/src/test/java/org/anarres/tftp/protocol/engine/TftpServerTester.java // public class TftpServerTester { // // private static final Random RANDOM = new Random(); // private final TftpMemoryDataProvider provider = new TftpMemoryDataProvider(); // private final TFTPClient client = new TFTPClient(); // // @Nonnull // public TftpMemoryDataProvider getProvider() { // return provider; // } // // @Nonnegative // public int getPort() { // return 1067; // } // // private void assertSucceeds(String path, int mode) throws Exception { // ByteArrayOutputStream out = new ByteArrayOutputStream(); // client.receiveFile(path, mode, out, InetAddress.getLoopbackAddress(), getPort()); // assertArrayEquals(provider.getData(path), out.toByteArray()); // } // // private void assertFails(String path, int mode) throws Exception { // try { // client.receiveFile(path, mode, ByteStreams.nullOutputStream(), InetAddress.getLoopbackAddress(), getPort()); // fail("Receive file " + path + "/" + mode + " succeeded unexpectedly."); // } catch (IOException e) { // } // } // // @Nonnull // public static byte[] newRandomBytes(int length) { // byte[] data = new byte[length]; // RANDOM.nextBytes(data); // return data; // } // // public void run() throws Exception { // client.open(); // // provider.setData("/hello", "Hello, world."); // // assertFails("/nonexistent", TFTPClient.BINARY_MODE); // assertFails("/nonexistent", TFTPClient.ASCII_MODE); // // assertSucceeds("/hello", TFTPClient.BINARY_MODE); // assertSucceeds("/hello", TFTPClient.ASCII_MODE); // // int[] sizes = new int[]{ // 0, // 1, // 8, // 511, // 512, // 513, // 1 * 1024 - 1, // 1 * 1024, // 1 * 1024 + 1, // 4 * 1024 - 1, // 4 * 1024, // 4 * 1024 + 1, // 1024 * 1024 - 1, // 1024 * 1024, // 1024 * 1024 + 1 // }; // // for (int size : sizes) { // byte[] data = newRandomBytes(size); // provider.setData("/binary", data); // assertSucceeds("/binary", TFTPClient.BINARY_MODE); // // provider.setData("/ascii", Base64.encodeBase64(data)); // assertSucceeds("/ascii", TFTPClient.ASCII_MODE); // } // // client.close(); // // } // } // Path: tftp-server-netty/src/test/java/org/anarres/tftp/server/netty/TftpServerTest.java import org.junit.Before; import org.junit.Test; import io.netty.util.ResourceLeakDetector; import org.anarres.tftp.protocol.engine.TftpServerTester; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ public class TftpServerTest { @Before public void setUp() { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); } @Test public void testServer() throws Exception {
TftpServerTester tester = new TftpServerTester();
shevek/tftp4j
tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpCodec.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.socket.DatagramPacket; import io.netty.util.ReferenceCountUtil; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ @ChannelHandler.Sharable public class TftpCodec extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpCodec.class);
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpCodec.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.socket.DatagramPacket; import io.netty.util.ReferenceCountUtil; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ @ChannelHandler.Sharable public class TftpCodec extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpCodec.class);
private final TftpPacketDecoder decoder = new TftpPacketDecoder();
shevek/tftp4j
tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpCodec.java
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // }
import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.socket.DatagramPacket; import io.netty.util.ReferenceCountUtil; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ @ChannelHandler.Sharable public class TftpCodec extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpCodec.class); private final TftpPacketDecoder decoder = new TftpPacketDecoder(); @Nonnull
// Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/codec/TftpPacketDecoder.java // public class TftpPacketDecoder { // // private static final Logger LOG = LoggerFactory.getLogger(TftpPacketDecoder.class); // // @Nonnull // public TftpPacket decode(@Nonnull SocketAddress remoteAddress, @Nonnull ByteBuffer buf) { // TftpOpcode opcode = TftpOpcode.forCode(buf.getShort()); // TftpPacket packet; // switch (opcode) { // case RRQ: // packet = new TftpReadRequestPacket(); // break; // case WRQ: // packet = new TftpWriteRequestPacket(); // break; // case DATA: // packet = new TftpDataPacket(); // break; // case ACK: // packet = new TftpAckPacket(); // break; // case ERROR: // packet = new TftpErrorPacket(); // break; // case ACK_WITH_OPTIONS: // default: // throw new IllegalStateException("Unknown TftpOpcode in decoder: " + opcode); // } // packet.setRemoteAddress(remoteAddress); // packet.fromWire(buf); // if (buf.position() < buf.limit()) { // LOG.warn("Discarded " + (buf.limit() - buf.position()) + " trailing bytes in TFTP packet: " + buf); // buf.position(buf.limit()); // } // return packet; // } // } // // Path: tftp-protocol/src/main/java/org/anarres/tftp/protocol/packet/TftpPacket.java // public abstract class TftpPacket { // // // Substitute for netascii in the RFC. ISO_8859_1 is 8-bit transparent. // public static final Charset CHARSET = Charsets.ISO_8859_1; // private SocketAddress remoteAddress; // // @Nonnull // public SocketAddress getRemoteAddress() { // return remoteAddress; // } // // public void setRemoteAddress(@Nonnull SocketAddress remoteAddress) { // this.remoteAddress = Preconditions.checkNotNull(remoteAddress, "Remote address was null."); // } // // /** At most this long, possibly less. */ // @Nonnegative // public int getWireLength() { // return 256; // } // // @Nonnull // public abstract TftpOpcode getOpcode(); // // @Nonnull // protected Objects.ToStringHelper toStringHelper() { // return Objects.toStringHelper(this).add("opcode", getOpcode()); // } // // public void toWire(@Nonnull ByteBuffer buffer) { // buffer.putShort(getOpcode().getCode()); // } // // /** This is called after the opcode has already been read. */ // public abstract void fromWire(@Nonnull ByteBuffer buffer); // // protected static void putString(@Nonnull ByteBuffer buffer, @Nonnull String text) { // buffer.put(text.getBytes(CHARSET)); // buffer.put((byte) 0); // } // // @Nonnull // protected static String getString(@Nonnull ByteBuffer buffer) { // int start = buffer.position(); // int finish; // int end = -1; // for (finish = start; finish < buffer.limit(); finish++) { // if (buffer.get(finish) == 0) { // end = finish; // finish++; // break; // } // } // // We didn't find a zero byte. // if (end == -1) // end = buffer.limit(); // // byte[] bytes = new byte[end - start]; // buffer.get(bytes); // buffer.position(finish); // return new String(bytes, CHARSET); // } // // @Override // public String toString() { // return toStringHelper().toString(); // } // } // Path: tftp-server-netty/src/main/java/org/anarres/tftp/server/netty/TftpCodec.java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.channel.socket.DatagramPacket; import io.netty.util.ReferenceCountUtil; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import javax.annotation.Nonnull; import org.anarres.tftp.protocol.codec.TftpPacketDecoder; import org.anarres.tftp.protocol.packet.TftpPacket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.anarres.tftp.server.netty; /** * * @author shevek */ @ChannelHandler.Sharable public class TftpCodec extends ChannelDuplexHandler { private static final Logger LOG = LoggerFactory.getLogger(TftpCodec.class); private final TftpPacketDecoder decoder = new TftpPacketDecoder(); @Nonnull
public TftpPacket decode(@Nonnull ChannelHandlerContext ctx, @Nonnull DatagramPacket packet) throws Exception {
bigjelly/AndFast
app/src/main/java/com/andfast/app/util/FragmentUtils.java
// Path: app/src/main/java/com/andfast/app/view/base/BaseFragment.java // public abstract class BaseFragment extends Fragment { // private static final String TAG = "BaseFragment"; // protected Context mContext; // protected View mRoot; // protected Bundle mBundle; // protected LayoutInflater mInflater; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // mContext = context; // } // // @Override // public void onDetach() { // super.onDetach(); // mContext = null; // } // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mBundle = getArguments(); // initBundle(mBundle); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (mRoot != null) { // ViewGroup parent = (ViewGroup) mRoot.getParent(); // if (parent != null) // parent.removeView(mRoot); // } else { // mRoot = inflater.inflate(getLayoutId(), container, false); // mInflater = inflater; // // Do something // onBindViewBefore(mRoot); // // Get savedInstanceState // if (savedInstanceState != null) // onRestartInstance(savedInstanceState); // // Init // initWidget(mRoot); // initData(); // } // return mRoot; // } // // @Override // public void onHiddenChanged(boolean hidden) { // super.onHiddenChanged(hidden); // if (!hidden) { // showFragmet(); // } else { // hiddenFragment(); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // super.setUserVisibleHint(isVisibleToUser); // if (isVisibleToUser) { // showFragmet(); // } else { // hiddenFragment(); // } // } // // protected void showFragmet() {} // // protected void hiddenFragment(){} // // protected abstract int getLayoutId(); // // protected void onBindViewBefore(View root) { // } // // protected void initBundle(Bundle bundle) { // // } // // protected void initWidget(View root) { // // } // // protected void initData() { // // } // // protected void onRestartInstance(Bundle bundle) { // // } // // private boolean isEventBusRegisted(Object subscribe) { // return EventBus.getDefault().isRegistered(subscribe); // } // // public void registerEventBus(Object subscribe) { // if (!isEventBusRegisted(subscribe)) { // EventBus.getDefault().register(subscribe); // } // } // // public void unregisterEventBus(Object subscribe) { // if (isEventBusRegisted(subscribe)) { // EventBus.getDefault().unregister(subscribe); // } // } // // protected <A extends Activity> A getParentActivity(){ // return (A) getActivity(); // } // // protected <V extends View> V findView(int viewId) { // return (V) mRoot.findViewById(viewId); // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.andfast.app.R; import com.andfast.app.view.base.BaseFragment; import java.util.List;
package com.andfast.app.util; /** *fragment管理类 **/ public class FragmentUtils { public static void replace(FragmentManager manager, int containerId, Fragment fragment, boolean addBackStack, String tag) { FragmentTransaction transaction = manager.beginTransaction(); if (addBackStack) { transaction.addToBackStack(tag); } transaction.replace(containerId, fragment, tag).commitAllowingStateLoss(); } public static void add(FragmentManager manager, int containerId, Fragment fragment, boolean addBackStack, String tag) { FragmentTransaction transaction = manager.beginTransaction(); if (addBackStack) { transaction.addToBackStack(tag); } transaction.add(containerId, fragment, tag).commitAllowingStateLoss(); }
// Path: app/src/main/java/com/andfast/app/view/base/BaseFragment.java // public abstract class BaseFragment extends Fragment { // private static final String TAG = "BaseFragment"; // protected Context mContext; // protected View mRoot; // protected Bundle mBundle; // protected LayoutInflater mInflater; // // @Override // public void onAttach(Context context) { // super.onAttach(context); // mContext = context; // } // // @Override // public void onDetach() { // super.onDetach(); // mContext = null; // } // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mBundle = getArguments(); // initBundle(mBundle); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // if (mRoot != null) { // ViewGroup parent = (ViewGroup) mRoot.getParent(); // if (parent != null) // parent.removeView(mRoot); // } else { // mRoot = inflater.inflate(getLayoutId(), container, false); // mInflater = inflater; // // Do something // onBindViewBefore(mRoot); // // Get savedInstanceState // if (savedInstanceState != null) // onRestartInstance(savedInstanceState); // // Init // initWidget(mRoot); // initData(); // } // return mRoot; // } // // @Override // public void onHiddenChanged(boolean hidden) { // super.onHiddenChanged(hidden); // if (!hidden) { // showFragmet(); // } else { // hiddenFragment(); // } // } // // @Override // public void setUserVisibleHint(boolean isVisibleToUser) { // super.setUserVisibleHint(isVisibleToUser); // if (isVisibleToUser) { // showFragmet(); // } else { // hiddenFragment(); // } // } // // protected void showFragmet() {} // // protected void hiddenFragment(){} // // protected abstract int getLayoutId(); // // protected void onBindViewBefore(View root) { // } // // protected void initBundle(Bundle bundle) { // // } // // protected void initWidget(View root) { // // } // // protected void initData() { // // } // // protected void onRestartInstance(Bundle bundle) { // // } // // private boolean isEventBusRegisted(Object subscribe) { // return EventBus.getDefault().isRegistered(subscribe); // } // // public void registerEventBus(Object subscribe) { // if (!isEventBusRegisted(subscribe)) { // EventBus.getDefault().register(subscribe); // } // } // // public void unregisterEventBus(Object subscribe) { // if (isEventBusRegisted(subscribe)) { // EventBus.getDefault().unregister(subscribe); // } // } // // protected <A extends Activity> A getParentActivity(){ // return (A) getActivity(); // } // // protected <V extends View> V findView(int viewId) { // return (V) mRoot.findViewById(viewId); // } // } // Path: app/src/main/java/com/andfast/app/util/FragmentUtils.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import com.andfast.app.R; import com.andfast.app.view.base.BaseFragment; import java.util.List; package com.andfast.app.util; /** *fragment管理类 **/ public class FragmentUtils { public static void replace(FragmentManager manager, int containerId, Fragment fragment, boolean addBackStack, String tag) { FragmentTransaction transaction = manager.beginTransaction(); if (addBackStack) { transaction.addToBackStack(tag); } transaction.replace(containerId, fragment, tag).commitAllowingStateLoss(); } public static void add(FragmentManager manager, int containerId, Fragment fragment, boolean addBackStack, String tag) { FragmentTransaction transaction = manager.beginTransaction(); if (addBackStack) { transaction.addToBackStack(tag); } transaction.add(containerId, fragment, tag).commitAllowingStateLoss(); }
public static void addMultiple(FragmentManager manager, int containerId, int showPosition, BaseFragment... fragments) {
bigjelly/AndFast
app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // }
import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List;
package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // } // Path: app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List; package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){
addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() {
bigjelly/AndFast
app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // }
import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List;
package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // } // Path: app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List; package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){
addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() {
bigjelly/AndFast
app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // }
import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List;
package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){ addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() { @Override
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // } // Path: app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List; package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){ addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() { @Override
protected void onFailure(ResultResponse response) {
bigjelly/AndFast
app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // }
import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List;
package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){ addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() { @Override protected void onFailure(ResultResponse response) {
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java // public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { // private static final String TAG = "SubscriberCallBack"; // @Override // public void onNext(ResultResponse<T> resultResponse) { // if (resultResponse.success){ // onSuccess(resultResponse.data); // }else { // onFailure(resultResponse); // } // } // // @Override // public void onError(Throwable e) { // super.onError(e); // onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e)); // } // // protected abstract void onFailure(ResultResponse response); // protected abstract void onSuccess(T response); // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BasePresenter.java // public class BasePresenter<V> { // // protected ApiService mApiService = ApiRetrofit.getInstance().getApiService(); // protected V mView; // private CompositeSubscription mCompositeSubscription; // // public BasePresenter(V view) { // attachView(view); // } // // public void attachView(V view) { // mView = view; // } // // public void detachView() { // mView = null; // onUnsubscribe(); // } // // public void addSubscription(Observable observable, Subscriber subscriber) { // if (mCompositeSubscription == null) { // mCompositeSubscription = new CompositeSubscription(); // } // if (!NetworkUtils.isAvailable(AndFastApplication.getContext())){ // observable = Observable.create(new Observable.OnSubscribe<ResultResponse<V>>() { // @Override // public void call(Subscriber<? super ResultResponse<V>> subscriber) { // subscriber.onNext(new ResultResponse<V>("", GeneralID.TYPE_NET_UNAVAILABLE_CODE,false,"",null)); // } // }); // } // mCompositeSubscription.add(observable // .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe(subscriber)); // } // // //RXjava取消注册,以避免内存泄露 // public void onUnsubscribe() { // if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) { // mCompositeSubscription.unsubscribe(); // } // } // } // // Path: app/src/main/java/com/andfast/app/view/home/Impl/IHomeListView.java // public interface IHomeListView extends IBasePullListView<List<Topic>> { // } // Path: app/src/main/java/com/andfast/app/presenter/home/HomePresenter.java import com.andfast.app.constant.GeneralID; import com.andfast.app.model.Topic; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.SubscriberCallBack; import com.andfast.app.presenter.base.BasePresenter; import com.andfast.app.view.home.Impl.IHomeListView; import java.util.List; package com.andfast.app.presenter.home; /** * Created by mby on 17-8-8. */ public class HomePresenter extends BasePresenter<IHomeListView> { public HomePresenter(IHomeListView view) { super(view); } public void getPullRefresh(){ addSubscription(mApiService.getTopicPage(1,20,true), new SubscriberCallBack<List<Topic>>() { @Override protected void onFailure(ResultResponse response) {
mView.onError(GeneralID.TYPE_PULL_REFRESH,response);
bigjelly/AndFast
app/src/main/java/com/andfast/app/view/common/MainTab.java
// Path: app/src/main/java/com/andfast/app/view/home/HomeFragment.java // public class HomeFragment extends BaseListViewFragment<HomePresenter> implements IHomeListView { // // private static final String TAG = "HomeFragment"; // // @Override // protected void initWidget(View root) { // super.initWidget(root); // setToolBarCenterTitle(R.string.tab_name_home); // } // // @Override // protected HomePresenter createPresenter() { // return new HomePresenter(this); // } // // @Override // public BaseRecyclerAdapter getListAdapter() { // return new HomeListAdapter(mContext, R.layout.lay_item_topic, new ArrayList<Topic>()); // } // // @Override // protected void initData() { // super.initData(); // mPullRecyclerView.postRefreshing(); // } // // @Override // public void onRefreshDetailSuccess(List<Topic> refreshDetail) { // mAdapter.replaceAll(refreshDetail); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onLoadMoreSuccess(List<Topic> loadMore) { // mAdapter.addAll(loadMore); // mAdapter.notifyDataSetChanged(); // mPullRecyclerView.stopLoadMore(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onError(int type, ResultResponse response) { // switch (type) { // case TYPE_PULL_REFRESH: // mEmptyView.setVisibility(View.VISIBLE); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(false); // break; // case TYPE_LOAD_MORE: // mPullRecyclerView.enableLoadMore(false); // break; // } // } // // @Override // public void onPullRefresh() { // mvpPresenter.getPullRefresh(); // } // // @Override // public void onLoadMore() { // mvpPresenter.getLoadMore(); // } // } // // Path: app/src/main/java/com/andfast/app/view/me/MeFragment.java // public class MeFragment extends BaseFragment { // // private static final String TAG = "MeFragment"; // private NWebView mWebView; // // @Override // protected int getLayoutId() { // return R.layout.frg_me; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView toolbarTitle = findView(R.id.toolbar_title); // toolbarTitle.setText(R.string.tab_name_my); // // mWebView = findView(R.id.webview); // mWebView.loadUrl("https://github.com/bigjelly/AndFast"); // // mWebView.openCache(StorageUtils.getCacheDir()+"webcache"); // // mWebView.setOnKeyListener(new View.OnKeyListener() { // @Override // public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { // LogUtils.i(TAG,"keyCode:"+keyCode); // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return false; // } // }); // // FloatingActionButton faButton = findView(R.id.fab); // faButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(mContext, WebViewActivity.class); // startActivity(intent); // } // }); // } // // @Override // public void onDestroy() { // super.onDestroy(); // if (mWebView != null) { // mWebView.stopLoading(); // mWebView.destroy(); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventTest(Entity entity){ // LogUtils.i(TAG,"entity.eventCode -->"+entity.eventCode); // } // // @Override // protected void showFragmet() { // super.showFragmet(); // registerEventBus(this); // } // // @Override // protected void hiddenFragment() { // super.hiddenFragment(); // unregisterEventBus(this); // } // } // // Path: app/src/main/java/com/andfast/app/view/video/VideoFragment.java // public class VideoFragment extends BaseFragment { // // private TabLayout mTabLayout; // private ViewPager mViewPager; // // @Override // protected int getLayoutId() { // return R.layout.frg_video; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView textView =findView(R.id.toolbar_title); // textView.setText(R.string.tab_name_video); // mTabLayout = findView(R.id.tablayout); // mViewPager = findView(R.id.homeviewpager); // mTabLayout.setupWithViewPager(mViewPager); // } // // @Override // protected void initData() { // super.initData(); // String[] titles = getResources().getStringArray(R.array.tabs_home); // List<Fragment> fragments = new ArrayList<>(); // fragments.add(new VideoHotFragment()); // fragments.add(new VideoTopFragment()); // VideoPageAdapter adapter = new VideoPageAdapter(this.getChildFragmentManager(), // fragments, titles); // mViewPager.setAdapter(adapter); // // // } // }
import com.andfast.app.R; import com.andfast.app.view.home.HomeFragment; import com.andfast.app.view.me.MeFragment; import com.andfast.app.view.video.VideoFragment;
package com.andfast.app.view.common; /** * Created by mby on 17-7-31. */ public enum MainTab { HOME(0, R.string.tab_name_home, R.drawable.tab_home_selector, HomeFragment.class),
// Path: app/src/main/java/com/andfast/app/view/home/HomeFragment.java // public class HomeFragment extends BaseListViewFragment<HomePresenter> implements IHomeListView { // // private static final String TAG = "HomeFragment"; // // @Override // protected void initWidget(View root) { // super.initWidget(root); // setToolBarCenterTitle(R.string.tab_name_home); // } // // @Override // protected HomePresenter createPresenter() { // return new HomePresenter(this); // } // // @Override // public BaseRecyclerAdapter getListAdapter() { // return new HomeListAdapter(mContext, R.layout.lay_item_topic, new ArrayList<Topic>()); // } // // @Override // protected void initData() { // super.initData(); // mPullRecyclerView.postRefreshing(); // } // // @Override // public void onRefreshDetailSuccess(List<Topic> refreshDetail) { // mAdapter.replaceAll(refreshDetail); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onLoadMoreSuccess(List<Topic> loadMore) { // mAdapter.addAll(loadMore); // mAdapter.notifyDataSetChanged(); // mPullRecyclerView.stopLoadMore(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onError(int type, ResultResponse response) { // switch (type) { // case TYPE_PULL_REFRESH: // mEmptyView.setVisibility(View.VISIBLE); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(false); // break; // case TYPE_LOAD_MORE: // mPullRecyclerView.enableLoadMore(false); // break; // } // } // // @Override // public void onPullRefresh() { // mvpPresenter.getPullRefresh(); // } // // @Override // public void onLoadMore() { // mvpPresenter.getLoadMore(); // } // } // // Path: app/src/main/java/com/andfast/app/view/me/MeFragment.java // public class MeFragment extends BaseFragment { // // private static final String TAG = "MeFragment"; // private NWebView mWebView; // // @Override // protected int getLayoutId() { // return R.layout.frg_me; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView toolbarTitle = findView(R.id.toolbar_title); // toolbarTitle.setText(R.string.tab_name_my); // // mWebView = findView(R.id.webview); // mWebView.loadUrl("https://github.com/bigjelly/AndFast"); // // mWebView.openCache(StorageUtils.getCacheDir()+"webcache"); // // mWebView.setOnKeyListener(new View.OnKeyListener() { // @Override // public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { // LogUtils.i(TAG,"keyCode:"+keyCode); // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return false; // } // }); // // FloatingActionButton faButton = findView(R.id.fab); // faButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(mContext, WebViewActivity.class); // startActivity(intent); // } // }); // } // // @Override // public void onDestroy() { // super.onDestroy(); // if (mWebView != null) { // mWebView.stopLoading(); // mWebView.destroy(); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventTest(Entity entity){ // LogUtils.i(TAG,"entity.eventCode -->"+entity.eventCode); // } // // @Override // protected void showFragmet() { // super.showFragmet(); // registerEventBus(this); // } // // @Override // protected void hiddenFragment() { // super.hiddenFragment(); // unregisterEventBus(this); // } // } // // Path: app/src/main/java/com/andfast/app/view/video/VideoFragment.java // public class VideoFragment extends BaseFragment { // // private TabLayout mTabLayout; // private ViewPager mViewPager; // // @Override // protected int getLayoutId() { // return R.layout.frg_video; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView textView =findView(R.id.toolbar_title); // textView.setText(R.string.tab_name_video); // mTabLayout = findView(R.id.tablayout); // mViewPager = findView(R.id.homeviewpager); // mTabLayout.setupWithViewPager(mViewPager); // } // // @Override // protected void initData() { // super.initData(); // String[] titles = getResources().getStringArray(R.array.tabs_home); // List<Fragment> fragments = new ArrayList<>(); // fragments.add(new VideoHotFragment()); // fragments.add(new VideoTopFragment()); // VideoPageAdapter adapter = new VideoPageAdapter(this.getChildFragmentManager(), // fragments, titles); // mViewPager.setAdapter(adapter); // // // } // } // Path: app/src/main/java/com/andfast/app/view/common/MainTab.java import com.andfast.app.R; import com.andfast.app.view.home.HomeFragment; import com.andfast.app.view.me.MeFragment; import com.andfast.app.view.video.VideoFragment; package com.andfast.app.view.common; /** * Created by mby on 17-7-31. */ public enum MainTab { HOME(0, R.string.tab_name_home, R.drawable.tab_home_selector, HomeFragment.class),
VIDEO(0, R.string.tab_name_video, R.drawable.tab_home_selector, VideoFragment.class),
bigjelly/AndFast
app/src/main/java/com/andfast/app/view/common/MainTab.java
// Path: app/src/main/java/com/andfast/app/view/home/HomeFragment.java // public class HomeFragment extends BaseListViewFragment<HomePresenter> implements IHomeListView { // // private static final String TAG = "HomeFragment"; // // @Override // protected void initWidget(View root) { // super.initWidget(root); // setToolBarCenterTitle(R.string.tab_name_home); // } // // @Override // protected HomePresenter createPresenter() { // return new HomePresenter(this); // } // // @Override // public BaseRecyclerAdapter getListAdapter() { // return new HomeListAdapter(mContext, R.layout.lay_item_topic, new ArrayList<Topic>()); // } // // @Override // protected void initData() { // super.initData(); // mPullRecyclerView.postRefreshing(); // } // // @Override // public void onRefreshDetailSuccess(List<Topic> refreshDetail) { // mAdapter.replaceAll(refreshDetail); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onLoadMoreSuccess(List<Topic> loadMore) { // mAdapter.addAll(loadMore); // mAdapter.notifyDataSetChanged(); // mPullRecyclerView.stopLoadMore(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onError(int type, ResultResponse response) { // switch (type) { // case TYPE_PULL_REFRESH: // mEmptyView.setVisibility(View.VISIBLE); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(false); // break; // case TYPE_LOAD_MORE: // mPullRecyclerView.enableLoadMore(false); // break; // } // } // // @Override // public void onPullRefresh() { // mvpPresenter.getPullRefresh(); // } // // @Override // public void onLoadMore() { // mvpPresenter.getLoadMore(); // } // } // // Path: app/src/main/java/com/andfast/app/view/me/MeFragment.java // public class MeFragment extends BaseFragment { // // private static final String TAG = "MeFragment"; // private NWebView mWebView; // // @Override // protected int getLayoutId() { // return R.layout.frg_me; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView toolbarTitle = findView(R.id.toolbar_title); // toolbarTitle.setText(R.string.tab_name_my); // // mWebView = findView(R.id.webview); // mWebView.loadUrl("https://github.com/bigjelly/AndFast"); // // mWebView.openCache(StorageUtils.getCacheDir()+"webcache"); // // mWebView.setOnKeyListener(new View.OnKeyListener() { // @Override // public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { // LogUtils.i(TAG,"keyCode:"+keyCode); // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return false; // } // }); // // FloatingActionButton faButton = findView(R.id.fab); // faButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(mContext, WebViewActivity.class); // startActivity(intent); // } // }); // } // // @Override // public void onDestroy() { // super.onDestroy(); // if (mWebView != null) { // mWebView.stopLoading(); // mWebView.destroy(); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventTest(Entity entity){ // LogUtils.i(TAG,"entity.eventCode -->"+entity.eventCode); // } // // @Override // protected void showFragmet() { // super.showFragmet(); // registerEventBus(this); // } // // @Override // protected void hiddenFragment() { // super.hiddenFragment(); // unregisterEventBus(this); // } // } // // Path: app/src/main/java/com/andfast/app/view/video/VideoFragment.java // public class VideoFragment extends BaseFragment { // // private TabLayout mTabLayout; // private ViewPager mViewPager; // // @Override // protected int getLayoutId() { // return R.layout.frg_video; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView textView =findView(R.id.toolbar_title); // textView.setText(R.string.tab_name_video); // mTabLayout = findView(R.id.tablayout); // mViewPager = findView(R.id.homeviewpager); // mTabLayout.setupWithViewPager(mViewPager); // } // // @Override // protected void initData() { // super.initData(); // String[] titles = getResources().getStringArray(R.array.tabs_home); // List<Fragment> fragments = new ArrayList<>(); // fragments.add(new VideoHotFragment()); // fragments.add(new VideoTopFragment()); // VideoPageAdapter adapter = new VideoPageAdapter(this.getChildFragmentManager(), // fragments, titles); // mViewPager.setAdapter(adapter); // // // } // }
import com.andfast.app.R; import com.andfast.app.view.home.HomeFragment; import com.andfast.app.view.me.MeFragment; import com.andfast.app.view.video.VideoFragment;
package com.andfast.app.view.common; /** * Created by mby on 17-7-31. */ public enum MainTab { HOME(0, R.string.tab_name_home, R.drawable.tab_home_selector, HomeFragment.class), VIDEO(0, R.string.tab_name_video, R.drawable.tab_home_selector, VideoFragment.class),
// Path: app/src/main/java/com/andfast/app/view/home/HomeFragment.java // public class HomeFragment extends BaseListViewFragment<HomePresenter> implements IHomeListView { // // private static final String TAG = "HomeFragment"; // // @Override // protected void initWidget(View root) { // super.initWidget(root); // setToolBarCenterTitle(R.string.tab_name_home); // } // // @Override // protected HomePresenter createPresenter() { // return new HomePresenter(this); // } // // @Override // public BaseRecyclerAdapter getListAdapter() { // return new HomeListAdapter(mContext, R.layout.lay_item_topic, new ArrayList<Topic>()); // } // // @Override // protected void initData() { // super.initData(); // mPullRecyclerView.postRefreshing(); // } // // @Override // public void onRefreshDetailSuccess(List<Topic> refreshDetail) { // mAdapter.replaceAll(refreshDetail); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onLoadMoreSuccess(List<Topic> loadMore) { // mAdapter.addAll(loadMore); // mAdapter.notifyDataSetChanged(); // mPullRecyclerView.stopLoadMore(); // mPullRecyclerView.enableLoadMore(true); // } // // @Override // public void onError(int type, ResultResponse response) { // switch (type) { // case TYPE_PULL_REFRESH: // mEmptyView.setVisibility(View.VISIBLE); // mPullRecyclerView.stopRefresh(); // mPullRecyclerView.enableLoadMore(false); // break; // case TYPE_LOAD_MORE: // mPullRecyclerView.enableLoadMore(false); // break; // } // } // // @Override // public void onPullRefresh() { // mvpPresenter.getPullRefresh(); // } // // @Override // public void onLoadMore() { // mvpPresenter.getLoadMore(); // } // } // // Path: app/src/main/java/com/andfast/app/view/me/MeFragment.java // public class MeFragment extends BaseFragment { // // private static final String TAG = "MeFragment"; // private NWebView mWebView; // // @Override // protected int getLayoutId() { // return R.layout.frg_me; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView toolbarTitle = findView(R.id.toolbar_title); // toolbarTitle.setText(R.string.tab_name_my); // // mWebView = findView(R.id.webview); // mWebView.loadUrl("https://github.com/bigjelly/AndFast"); // // mWebView.openCache(StorageUtils.getCacheDir()+"webcache"); // // mWebView.setOnKeyListener(new View.OnKeyListener() { // @Override // public boolean onKey(View view, int keyCode, KeyEvent keyEvent) { // LogUtils.i(TAG,"keyCode:"+keyCode); // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return false; // } // }); // // FloatingActionButton faButton = findView(R.id.fab); // faButton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Intent intent = new Intent(mContext, WebViewActivity.class); // startActivity(intent); // } // }); // } // // @Override // public void onDestroy() { // super.onDestroy(); // if (mWebView != null) { // mWebView.stopLoading(); // mWebView.destroy(); // } // } // // @Subscribe(threadMode = ThreadMode.MAIN) // public void onEventTest(Entity entity){ // LogUtils.i(TAG,"entity.eventCode -->"+entity.eventCode); // } // // @Override // protected void showFragmet() { // super.showFragmet(); // registerEventBus(this); // } // // @Override // protected void hiddenFragment() { // super.hiddenFragment(); // unregisterEventBus(this); // } // } // // Path: app/src/main/java/com/andfast/app/view/video/VideoFragment.java // public class VideoFragment extends BaseFragment { // // private TabLayout mTabLayout; // private ViewPager mViewPager; // // @Override // protected int getLayoutId() { // return R.layout.frg_video; // } // // @Override // protected void initWidget(View root) { // super.initWidget(root); // TextView textView =findView(R.id.toolbar_title); // textView.setText(R.string.tab_name_video); // mTabLayout = findView(R.id.tablayout); // mViewPager = findView(R.id.homeviewpager); // mTabLayout.setupWithViewPager(mViewPager); // } // // @Override // protected void initData() { // super.initData(); // String[] titles = getResources().getStringArray(R.array.tabs_home); // List<Fragment> fragments = new ArrayList<>(); // fragments.add(new VideoHotFragment()); // fragments.add(new VideoTopFragment()); // VideoPageAdapter adapter = new VideoPageAdapter(this.getChildFragmentManager(), // fragments, titles); // mViewPager.setAdapter(adapter); // // // } // } // Path: app/src/main/java/com/andfast/app/view/common/MainTab.java import com.andfast.app.R; import com.andfast.app.view.home.HomeFragment; import com.andfast.app.view.me.MeFragment; import com.andfast.app.view.video.VideoFragment; package com.andfast.app.view.common; /** * Created by mby on 17-7-31. */ public enum MainTab { HOME(0, R.string.tab_name_home, R.drawable.tab_home_selector, HomeFragment.class), VIDEO(0, R.string.tab_name_video, R.drawable.tab_home_selector, VideoFragment.class),
ME(0, R.string.tab_name_my, R.drawable.tab_home_selector, MeFragment.class);
bigjelly/AndFast
app/src/main/java/com/andfast/app/net/ApiService.java
// Path: app/src/main/java/com/andfast/app/model/TestModel.java // public class TestModel extends Entity{ // public int id; // public String name; // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // }
import com.andfast.app.model.NewsData; import com.andfast.app.model.TestModel; import com.andfast.app.model.Topic; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; import rx.Observable;
package com.andfast.app.net; /** * Created by mby on 17-8-5. */ public interface ApiService { String HOST = "https://"; String API_SERVER_URL = HOST + "cnodejs.org/api/v1/"; String URL_ARTICLE_FEED = "/api/article/recent/"; String GET_ARTICLE_LIST = "api/news/feed/v54/?refer=1&count=20&loc_mode=4&device_id=34960436458"; /** * 获取新闻详情 */ @GET
// Path: app/src/main/java/com/andfast/app/model/TestModel.java // public class TestModel extends Entity{ // public int id; // public String name; // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // Path: app/src/main/java/com/andfast/app/net/ApiService.java import com.andfast.app.model.NewsData; import com.andfast.app.model.TestModel; import com.andfast.app.model.Topic; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; import rx.Observable; package com.andfast.app.net; /** * Created by mby on 17-8-5. */ public interface ApiService { String HOST = "https://"; String API_SERVER_URL = HOST + "cnodejs.org/api/v1/"; String URL_ARTICLE_FEED = "/api/article/recent/"; String GET_ARTICLE_LIST = "api/news/feed/v54/?refer=1&count=20&loc_mode=4&device_id=34960436458"; /** * 获取新闻详情 */ @GET
Observable<ResultResponse<TestModel>> getNewsDetail(@Url String url);
bigjelly/AndFast
app/src/main/java/com/andfast/app/net/ApiService.java
// Path: app/src/main/java/com/andfast/app/model/TestModel.java // public class TestModel extends Entity{ // public int id; // public String name; // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // }
import com.andfast.app.model.NewsData; import com.andfast.app.model.TestModel; import com.andfast.app.model.Topic; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; import rx.Observable;
package com.andfast.app.net; /** * Created by mby on 17-8-5. */ public interface ApiService { String HOST = "https://"; String API_SERVER_URL = HOST + "cnodejs.org/api/v1/"; String URL_ARTICLE_FEED = "/api/article/recent/"; String GET_ARTICLE_LIST = "api/news/feed/v54/?refer=1&count=20&loc_mode=4&device_id=34960436458"; /** * 获取新闻详情 */ @GET Observable<ResultResponse<TestModel>> getNewsDetail(@Url String url); /** * 获取新闻列表 * * @param category 频道 * @return */ @GET(GET_ARTICLE_LIST) Observable<ResultResponse<List<NewsData>>> getNewsList(@Query("category") String category, @Query("min_behot_time") long lastTime, @Query("last_refresh_sub_entrance_interval") long currentTime); /** * 获取首页文章列表 * * @param pageIndex * @param limit * @param mdrender * @return */ @GET("topics")
// Path: app/src/main/java/com/andfast/app/model/TestModel.java // public class TestModel extends Entity{ // public int id; // public String name; // } // // Path: app/src/main/java/com/andfast/app/model/Topic.java // public class Topic { // public String id; // public String author_id; // public String tab; // public String content; // public String title; // public Date last_reply_at; // public boolean good; // public boolean top; // public Integer reply_count; // public Integer visit_count; // public Date create_at; // public Author author; // // public class Author{ // public String loginname; // public String avatar_url; // } // } // Path: app/src/main/java/com/andfast/app/net/ApiService.java import com.andfast.app.model.NewsData; import com.andfast.app.model.TestModel; import com.andfast.app.model.Topic; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Url; import rx.Observable; package com.andfast.app.net; /** * Created by mby on 17-8-5. */ public interface ApiService { String HOST = "https://"; String API_SERVER_URL = HOST + "cnodejs.org/api/v1/"; String URL_ARTICLE_FEED = "/api/article/recent/"; String GET_ARTICLE_LIST = "api/news/feed/v54/?refer=1&count=20&loc_mode=4&device_id=34960436458"; /** * 获取新闻详情 */ @GET Observable<ResultResponse<TestModel>> getNewsDetail(@Url String url); /** * 获取新闻列表 * * @param category 频道 * @return */ @GET(GET_ARTICLE_LIST) Observable<ResultResponse<List<NewsData>>> getNewsList(@Query("category") String category, @Query("min_behot_time") long lastTime, @Query("last_refresh_sub_entrance_interval") long currentTime); /** * 获取首页文章列表 * * @param pageIndex * @param limit * @param mdrender * @return */ @GET("topics")
Observable<ResultResponse<List<Topic>>> getTopicPage(@Query("page") Integer pageIndex, @Query("limit") Integer limit, @Query("mdrender") Boolean mdrender);
bigjelly/AndFast
app/src/main/java/com/andfast/app/util/ResourceReader.java
// Path: app/src/main/java/com/andfast/app/AndFastApplication.java // public class AndFastApplication extends Application { // // private final static String TAG = "AndFastApplication"; // private static Context mContext; // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // StorageUtils.initExtDir(getApplicationContext()); // initLog(); // CrashHandler.getInstance().init(getApplicationContext()); // LogUtils.i(TAG,"<><><><><><><><><>"); // LogUtils.i(TAG," app is start!"); // LogUtils.i(TAG,"<><><><><><><><><>"); // } // // private void initLog() { // LogUtils.setRootTag("andfast"); // LogUtils.setLogPath(StorageUtils.getLogDir()); // LogUtils.setSaveRuntimeInfo(true); // LogUtils.setAutoSave(true); // LogUtils.setDebug(BuildConfig.LOG_DEBUG); // } // // public static Context getContext(){ // return mContext; // } // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.view.View; import com.andfast.app.AndFastApplication; import java.io.IOException; import java.io.InputStream;
package com.andfast.app.util; /** * 文件获取 * * @author: boyuma * @datetime: 2020/6/16 */ public class ResourceReader { public static String getString(int id) {
// Path: app/src/main/java/com/andfast/app/AndFastApplication.java // public class AndFastApplication extends Application { // // private final static String TAG = "AndFastApplication"; // private static Context mContext; // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // StorageUtils.initExtDir(getApplicationContext()); // initLog(); // CrashHandler.getInstance().init(getApplicationContext()); // LogUtils.i(TAG,"<><><><><><><><><>"); // LogUtils.i(TAG," app is start!"); // LogUtils.i(TAG,"<><><><><><><><><>"); // } // // private void initLog() { // LogUtils.setRootTag("andfast"); // LogUtils.setLogPath(StorageUtils.getLogDir()); // LogUtils.setSaveRuntimeInfo(true); // LogUtils.setAutoSave(true); // LogUtils.setDebug(BuildConfig.LOG_DEBUG); // } // // public static Context getContext(){ // return mContext; // } // } // Path: app/src/main/java/com/andfast/app/util/ResourceReader.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.view.View; import com.andfast.app.AndFastApplication; import java.io.IOException; import java.io.InputStream; package com.andfast.app.util; /** * 文件获取 * * @author: boyuma * @datetime: 2020/6/16 */ public class ResourceReader { public static String getString(int id) {
return AndFastApplication.getContext().getResources().getString(id);
bigjelly/AndFast
pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/LoadMoreRecyclerView.java
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // }
import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager;
package com.andfast.pullrecyclerview; /** * Created by holenzhou on 16/5/26. * 只支持上拉加载更多的LoadMoreRecyclerView * 直接继承自RecyclerView,适用于需要将SwipeRefreshLayout和RecyclerView分开使用的场景 */ public class LoadMoreRecyclerView extends RecyclerView { private OnScrollListener scrollListener;
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // } // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/LoadMoreRecyclerView.java import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager; package com.andfast.pullrecyclerview; /** * Created by holenzhou on 16/5/26. * 只支持上拉加载更多的LoadMoreRecyclerView * 直接继承自RecyclerView,适用于需要将SwipeRefreshLayout和RecyclerView分开使用的场景 */ public class LoadMoreRecyclerView extends RecyclerView { private OnScrollListener scrollListener;
private ILayoutManager layoutManager;
bigjelly/AndFast
pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/LoadMoreRecyclerView.java
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // }
import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager;
checkIfCanLoadMore(); } } }); } public void setScrollListener(OnScrollListener listener) { scrollListener = listener; } private boolean checkIfScrollToFooter() { return layoutManager.isScrollToFooter(adapter.getItemCount()); } private void checkIfCanLoadMore() { if (isLoadMoreEnable && !adapter.isShowLoadMoreFooter()) { post(new Runnable() { @Override public void run() { adapter.showLoadMoreFooter(true); } }); } } public void setAdapter(Adapter adapter) { super.setAdapter(adapter); if (adapter instanceof BaseRecyclerAdapter) { this.adapter = (BaseRecyclerAdapter) adapter; if (layoutManager == null) {
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // } // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/LoadMoreRecyclerView.java import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager; checkIfCanLoadMore(); } } }); } public void setScrollListener(OnScrollListener listener) { scrollListener = listener; } private boolean checkIfScrollToFooter() { return layoutManager.isScrollToFooter(adapter.getItemCount()); } private void checkIfCanLoadMore() { if (isLoadMoreEnable && !adapter.isShowLoadMoreFooter()) { post(new Runnable() { @Override public void run() { adapter.showLoadMoreFooter(true); } }); } } public void setAdapter(Adapter adapter) { super.setAdapter(adapter); if (adapter instanceof BaseRecyclerAdapter) { this.adapter = (BaseRecyclerAdapter) adapter; if (layoutManager == null) {
layoutManager = new XLinearLayoutManager(getContext());
bigjelly/AndFast
app/src/main/java/com/andfast/app/util/ScreenUtil.java
// Path: app/src/main/java/com/andfast/app/AndFastApplication.java // public class AndFastApplication extends Application { // // private final static String TAG = "AndFastApplication"; // private static Context mContext; // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // StorageUtils.initExtDir(getApplicationContext()); // initLog(); // CrashHandler.getInstance().init(getApplicationContext()); // LogUtils.i(TAG,"<><><><><><><><><>"); // LogUtils.i(TAG," app is start!"); // LogUtils.i(TAG,"<><><><><><><><><>"); // } // // private void initLog() { // LogUtils.setRootTag("andfast"); // LogUtils.setLogPath(StorageUtils.getLogDir()); // LogUtils.setSaveRuntimeInfo(true); // LogUtils.setAutoSave(true); // LogUtils.setDebug(BuildConfig.LOG_DEBUG); // } // // public static Context getContext(){ // return mContext; // } // }
import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Point; import android.os.Build; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.Display; import android.view.Surface; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import com.andfast.app.AndFastApplication; import java.lang.reflect.Method;
package com.andfast.app.util; /** * 屏幕属性获取 * * @author: boyuma * @datetime: 2020/6/16 */ public class ScreenUtil { private static final String NAVIGATION_GESTURE = "navigation_gesture_on"; private static final int NAVIGATION_GESTURE_OFF = 0; private static final String XIAOMI_FULLSCREEN_GESTURE = "force_fsg_nav_bar"; public static boolean sDeviceDataInit = false; private static float sDisplayMetricsDensity; static int sDisplayMetricsWidthPixels; static int sDisplayMetricsHeightPixels; private static int realScreenHeight = 0; private static float sDisplayRate = 0.f; public static void initDeviceData() { DisplayMetrics metric = new DisplayMetrics();
// Path: app/src/main/java/com/andfast/app/AndFastApplication.java // public class AndFastApplication extends Application { // // private final static String TAG = "AndFastApplication"; // private static Context mContext; // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // StorageUtils.initExtDir(getApplicationContext()); // initLog(); // CrashHandler.getInstance().init(getApplicationContext()); // LogUtils.i(TAG,"<><><><><><><><><>"); // LogUtils.i(TAG," app is start!"); // LogUtils.i(TAG,"<><><><><><><><><>"); // } // // private void initLog() { // LogUtils.setRootTag("andfast"); // LogUtils.setLogPath(StorageUtils.getLogDir()); // LogUtils.setSaveRuntimeInfo(true); // LogUtils.setAutoSave(true); // LogUtils.setDebug(BuildConfig.LOG_DEBUG); // } // // public static Context getContext(){ // return mContext; // } // } // Path: app/src/main/java/com/andfast/app/util/ScreenUtil.java import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Point; import android.os.Build; import android.provider.Settings; import android.util.DisplayMetrics; import android.view.Display; import android.view.Surface; import android.view.View; import android.view.WindowInsets; import android.view.WindowManager; import com.andfast.app.AndFastApplication; import java.lang.reflect.Method; package com.andfast.app.util; /** * 屏幕属性获取 * * @author: boyuma * @datetime: 2020/6/16 */ public class ScreenUtil { private static final String NAVIGATION_GESTURE = "navigation_gesture_on"; private static final int NAVIGATION_GESTURE_OFF = 0; private static final String XIAOMI_FULLSCREEN_GESTURE = "force_fsg_nav_bar"; public static boolean sDeviceDataInit = false; private static float sDisplayMetricsDensity; static int sDisplayMetricsWidthPixels; static int sDisplayMetricsHeightPixels; private static int realScreenHeight = 0; private static float sDisplayRate = 0.f; public static void initDeviceData() { DisplayMetrics metric = new DisplayMetrics();
WindowManager manager = (WindowManager) AndFastApplication
bigjelly/AndFast
app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BaseCallBack.java // public abstract class BaseCallBack<T> extends Subscriber<T> { // // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // // } // }
import com.andfast.app.constant.GeneralID; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.base.BaseCallBack;
package com.andfast.app.presenter; /** * Created by mby on 17-8-6. */ public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { private static final String TAG = "SubscriberCallBack"; @Override public void onNext(ResultResponse<T> resultResponse) { if (resultResponse.success){ onSuccess(resultResponse.data); }else { onFailure(resultResponse); } } @Override public void onError(Throwable e) { super.onError(e);
// Path: app/src/main/java/com/andfast/app/constant/GeneralID.java // public class GeneralID { // // /**接口根地址*/ // public static final String BASE_SERVER_URL = "http://is.snssdk.com/"; // // /** // * 页面间参数传递KEY值 // */ // public class Extra { // public static final String TAB = "tab"; // } // // public final static int TYPE_PULL_REFRESH = 1; // public final static int TYPE_LOAD_MORE = TYPE_PULL_REFRESH + 1; // // /**网络请求异常code*/ // public final static int TYPE_NET_UNAVAILABLE_CODE = 1004; // public final static int TYPE_NET_ERROR_CODE = TYPE_NET_UNAVAILABLE_CODE+1; // // // EventBus Code // public static final class EventCode { // public static final int TEST = 0x8858111; // } // } // // Path: app/src/main/java/com/andfast/app/net/ResultResponse.java // public class ResultResponse <T> { // // public String has_more; // public String message; // public boolean success; // public int error_code; // public T data; // // public ResultResponse(String more, int code,boolean success,String _message, T result) { // error_code = code; // has_more = more; // message = _message; // data = result; // this.success = success; // } // } // // Path: app/src/main/java/com/andfast/app/presenter/base/BaseCallBack.java // public abstract class BaseCallBack<T> extends Subscriber<T> { // // @Override // public void onCompleted() { // // } // // @Override // public void onError(Throwable e) { // // } // } // Path: app/src/main/java/com/andfast/app/presenter/SubscriberCallBack.java import com.andfast.app.constant.GeneralID; import com.andfast.app.net.ResultResponse; import com.andfast.app.presenter.base.BaseCallBack; package com.andfast.app.presenter; /** * Created by mby on 17-8-6. */ public abstract class SubscriberCallBack<T> extends BaseCallBack<ResultResponse<T>> { private static final String TAG = "SubscriberCallBack"; @Override public void onNext(ResultResponse<T> resultResponse) { if (resultResponse.success){ onSuccess(resultResponse.data); }else { onFailure(resultResponse); } } @Override public void onError(Throwable e) { super.onError(e);
onFailure(new ResultResponse("", GeneralID.TYPE_NET_ERROR_CODE,false,"",e));
bigjelly/AndFast
pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/PullRecyclerView.java
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // }
import android.content.Context; import android.support.annotation.ColorRes; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager;
package com.andfast.pullrecyclerview; /** * Created by holenzhou on 16/5/10. * 基于RecyclerView和SwipeRefreshLayout进行封装,提供下拉刷新、上拉加载更多、添加header和footer、 * 设置空页面等多种功能的组合控件 */ public class PullRecyclerView extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener { protected RecyclerView recyclerView; protected SwipeRefreshLayout swipeRefreshLayout; private OnRecyclerRefreshListener listener; public static final int RECYCLER_ACTION_PULL_REFRESH = 1; public static final int RECYCLER_ACTION_LOAD_MORE = 2; public static final int RECYCLER_ACTION_IDLE = 0; int mCurrentAction = RECYCLER_ACTION_IDLE; private boolean isLoadMoreEnable; private boolean isPullRefreshEnabled = true; private boolean isShowLoadDoneTipEnable;
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // } // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/PullRecyclerView.java import android.content.Context; import android.support.annotation.ColorRes; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager; package com.andfast.pullrecyclerview; /** * Created by holenzhou on 16/5/10. * 基于RecyclerView和SwipeRefreshLayout进行封装,提供下拉刷新、上拉加载更多、添加header和footer、 * 设置空页面等多种功能的组合控件 */ public class PullRecyclerView extends FrameLayout implements SwipeRefreshLayout.OnRefreshListener { protected RecyclerView recyclerView; protected SwipeRefreshLayout swipeRefreshLayout; private OnRecyclerRefreshListener listener; public static final int RECYCLER_ACTION_PULL_REFRESH = 1; public static final int RECYCLER_ACTION_LOAD_MORE = 2; public static final int RECYCLER_ACTION_IDLE = 0; int mCurrentAction = RECYCLER_ACTION_IDLE; private boolean isLoadMoreEnable; private boolean isPullRefreshEnabled = true; private boolean isShowLoadDoneTipEnable;
private ILayoutManager layoutManager;
bigjelly/AndFast
pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/PullRecyclerView.java
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // }
import android.content.Context; import android.support.annotation.ColorRes; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager;
public int getFirstVisibleItemPosition() { return layoutManager.getFirstVisibleItemPosition(); } public RecyclerView getRecycler() { return recyclerView; } /** * 触发PullRecyclerView的下拉刷新 */ public void postRefreshing() { swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); onRefresh(); } }); } /** * 设置adapter,需要使用BaseRecyclerAdapter的子类 * @param adapter */ public void setAdapter(BaseRecyclerAdapter adapter) { this.adapter = adapter; recyclerView.setAdapter(adapter); if (layoutManager == null) {
// Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/ILayoutManager.java // public interface ILayoutManager { // // int getFirstVisibleItemPosition(); // // int getLastVisibleItemPosition(); // // RecyclerView.LayoutManager getLayoutManager(); // // void setRecyclerAdapter(BaseRecyclerAdapter adapter); // // boolean isScrollToFooter(int itemCount); // // } // // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/layoutmanager/XLinearLayoutManager.java // public class XLinearLayoutManager extends LinearLayoutManager implements ILayoutManager { // // public XLinearLayoutManager(Context context) { // super(context); // } // // public XLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { // super(context, orientation, reverseLayout); // } // // public XLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { // super(context, attrs, defStyleAttr, defStyleRes); // } // // @Override // public int getFirstVisibleItemPosition() { // return this.findFirstVisibleItemPosition(); // } // // @Override // public int getLastVisibleItemPosition() { // return this.findLastVisibleItemPosition(); // } // // @Override // public RecyclerView.LayoutManager getLayoutManager() { // return this; // } // // @Override // public void setRecyclerAdapter(BaseRecyclerAdapter adapter) { // // } // // @Override // public boolean isScrollToFooter(int itemCount) { // int position = findLastVisibleItemPosition(); // return position == itemCount - 1; // } // } // Path: pullrecyclerview/src/main/java/com/andfast/pullrecyclerview/PullRecyclerView.java import android.content.Context; import android.support.annotation.ColorRes; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import com.andfast.pullrecyclerview.layoutmanager.ILayoutManager; import com.andfast.pullrecyclerview.layoutmanager.XLinearLayoutManager; public int getFirstVisibleItemPosition() { return layoutManager.getFirstVisibleItemPosition(); } public RecyclerView getRecycler() { return recyclerView; } /** * 触发PullRecyclerView的下拉刷新 */ public void postRefreshing() { swipeRefreshLayout.post(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(true); onRefresh(); } }); } /** * 设置adapter,需要使用BaseRecyclerAdapter的子类 * @param adapter */ public void setAdapter(BaseRecyclerAdapter adapter) { this.adapter = adapter; recyclerView.setAdapter(adapter); if (layoutManager == null) {
layoutManager = new XLinearLayoutManager(getContext());
objectstyle/graphql
graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E3.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // }
import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E2;
package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E3 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E3 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E2_ID = new Property<Integer>("e2_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E3.java import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E2; package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E3 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E3 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E2_ID = new Property<Integer>("e2_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<E2> E2 = new Property<E2>("e2");
objectstyle/graphql
graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E3.java
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // }
import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E2;
package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E3 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E3 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E2_ID = new Property<Integer>("e2_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E3.java import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E2; package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E3 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E3 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E2_ID = new Property<Integer>("e2_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<org.objectstyle.graphql.example.cayenne.E2> E2 = new Property<E2>("e2");
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/ExecutionResultWriter.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // }
import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; import graphql.ExecutionResult;
package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class ExecutionResultWriter implements MessageBodyWriter<ExecutionResult> { @Context Configuration config; @Override public long getSize(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ExecutionResult.class.isAssignableFrom(type); } @Override public void writeTo(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/ExecutionResultWriter.java import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; import graphql.ExecutionResult; package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class ExecutionResultWriter implements MessageBodyWriter<ExecutionResult> { @Context Configuration config; @Override public long getSize(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ExecutionResult.class.isAssignableFrom(type); } @Override public void writeTo(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JsonWriter writer = (JsonWriter) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/ExecutionResultWriter.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // }
import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; import graphql.ExecutionResult;
package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class ExecutionResultWriter implements MessageBodyWriter<ExecutionResult> { @Context Configuration config; @Override public long getSize(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ExecutionResult.class.isAssignableFrom(type); } @Override public void writeTo(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/ExecutionResultWriter.java import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; import graphql.ExecutionResult; package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class ExecutionResultWriter implements MessageBodyWriter<ExecutionResult> { @Context Configuration config; @Override public long getSize(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ExecutionResult.class.isAssignableFrom(type); } @Override public void writeTo(ExecutionResult t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
JsonWriter writer = (JsonWriter) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // }
import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals;
package org.objectstyle.graphql.cayenne; public class GraphQLTest { private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTest.class); private void incudeOneEntityTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); assertEquals(null, r.getData()); assertEquals(ValidationError, r.getErrors().get(0).getErrorType()); assertEquals("Validation error of type FieldUndefined: Field E2 is undefined", r.getErrors().get(0).getMessage()); r = graphQL.execute("query { E3 (id:6) { id name}}"); assertEquals(null, r.getData()); assertEquals(ValidationError, r.getErrors().get(0).getErrorType()); assertEquals("Validation error of type FieldUndefined: Field E3 is undefined", r.getErrors().get(0).getMessage()); } @Test public void incudeOneEntityClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext());
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals; package org.objectstyle.graphql.cayenne; public class GraphQLTest { private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTest.class); private void incudeOneEntityTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); assertEquals(null, r.getData()); assertEquals(ValidationError, r.getErrors().get(0).getErrorType()); assertEquals("Validation error of type FieldUndefined: Field E2 is undefined", r.getErrors().get(0).getMessage()); r = graphQL.execute("query { E3 (id:6) { id name}}"); assertEquals(null, r.getData()); assertEquals(ValidationError, r.getErrors().get(0).getErrorType()); assertEquals("Validation error of type FieldUndefined: Field E3 is undefined", r.getErrors().get(0).getMessage()); } @Test public void incudeOneEntityClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext());
queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E1.class);
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // }
import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals;
QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, "E1"); GraphQLSchema schema = SchemaBuilder.builder(testFactory.getObjectContext()) .queryType(queryType.build()) .build(); incudeOneEntityTest(new GraphQL(schema)); } private void incudeAllEntitiesTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E2=[{id=3, name=c}]}", r.getData().toString()); r = graphQL.execute("query { E3 (id:6) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E3=[{id=6, name=f}]}", r.getData().toString()); } @Test public void incudeAllEntitiesClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E1.class)
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals; QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, "E1"); GraphQLSchema schema = SchemaBuilder.builder(testFactory.getObjectContext()) .queryType(queryType.build()) .build(); incudeOneEntityTest(new GraphQL(schema)); } private void incudeAllEntitiesTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E2=[{id=3, name=c}]}", r.getData().toString()); r = graphQL.execute("query { E3 (id:6) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E3=[{id=6, name=f}]}", r.getData().toString()); } @Test public void incudeAllEntitiesClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E1.class)
.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E2.class)
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // }
import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals;
queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, "E1"); GraphQLSchema schema = SchemaBuilder.builder(testFactory.getObjectContext()) .queryType(queryType.build()) .build(); incudeOneEntityTest(new GraphQL(schema)); } private void incudeAllEntitiesTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E2=[{id=3, name=c}]}", r.getData().toString()); r = graphQL.execute("query { E3 (id:6) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E3=[{id=6, name=f}]}", r.getData().toString()); } @Test public void incudeAllEntitiesClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E1.class) .configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E2.class)
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/GraphQLTest.java import graphql.ExecutionResult; import graphql.GraphQL; import graphql.schema.GraphQLSchema; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.*; import org.junit.Test; import org.objectstyle.graphql.cayenne.orm.*; import org.objectstyle.graphql.test.TestFactory; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E2; import org.objectstyle.graphql.test.cayenne.E3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import static graphql.ErrorType.ValidationError; import static org.junit.Assert.assertEquals; queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, "E1"); GraphQLSchema schema = SchemaBuilder.builder(testFactory.getObjectContext()) .queryType(queryType.build()) .build(); incudeOneEntityTest(new GraphQL(schema)); } private void incudeAllEntitiesTest(GraphQL graphQL) { ExecutionResult r = graphQL.execute("query { E1 (id:1) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E1=[{id=1, name=a}]}", r.getData().toString()); r = graphQL.execute("query { E2 (id:3) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E2=[{id=3, name=c}]}", r.getData().toString()); r = graphQL.execute("query { E3 (id:6) { id name}}"); LOGGER.info(r.getData().toString()); assertEquals("{E3=[{id=6, name=f}]}", r.getData().toString()); } @Test public void incudeAllEntitiesClassTest() { QueryType.Builder queryType = QueryType.builder(testFactory.getObjectContext()); queryType.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E1.class) .configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E2.class)
.configureEntities(EntityBuilder.ConfigureType.INCLUDE_OBJECT, E3.class);
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLFeatureProvider.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLFeature.java // public class GraphQLFeature implements Feature { // // private GraphQL graphQL; // private JacksonReaderWriter jacksonReaderWriter; // // @Override // public boolean configure(FeatureContext context) { // context.register(MessageResponseWriter.class); // context.register(GraphQLRestExceptionMapper.class); // context.register(GraphQLRestQueryReader.class); // context.register(ExecutionResultWriter.class); // context.register(GraphQLResource.class); // // context.property(GraphQL.class.getName(), graphQL); // context.property(JacksonReaderWriter.class.getName(), jacksonReaderWriter); // // return true; // } // // public static Builder newBuilder() { // return new Builder(); // } // // public static class Builder { // private GraphQLFeature graphQLFeature; // // // private Builder() { // this.graphQLFeature = new GraphQLFeature(); // } // // public Builder graphQL(GraphQL graphQL) { // graphQLFeature.graphQL = graphQL; // return this; // } // // public Builder jacksonReaderWriter(JacksonReaderWriter jacksonReaderWriter) { // graphQLFeature.jacksonReaderWriter = jacksonReaderWriter; // return this; // } // // public GraphQLFeature build() { // return graphQLFeature; // } // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // }
import com.google.inject.Inject; import com.google.inject.Provider; import graphql.GraphQL; import org.objectstyle.graphql.rest.GraphQLFeature; import org.objectstyle.graphql.rest.json.JacksonReaderWriter;
package org.objectstyle.graphql.bootique; class GraphQLFeatureProvider implements Provider<GraphQLFeature> { @Inject private GraphQL graphQL; @Inject
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLFeature.java // public class GraphQLFeature implements Feature { // // private GraphQL graphQL; // private JacksonReaderWriter jacksonReaderWriter; // // @Override // public boolean configure(FeatureContext context) { // context.register(MessageResponseWriter.class); // context.register(GraphQLRestExceptionMapper.class); // context.register(GraphQLRestQueryReader.class); // context.register(ExecutionResultWriter.class); // context.register(GraphQLResource.class); // // context.property(GraphQL.class.getName(), graphQL); // context.property(JacksonReaderWriter.class.getName(), jacksonReaderWriter); // // return true; // } // // public static Builder newBuilder() { // return new Builder(); // } // // public static class Builder { // private GraphQLFeature graphQLFeature; // // // private Builder() { // this.graphQLFeature = new GraphQLFeature(); // } // // public Builder graphQL(GraphQL graphQL) { // graphQLFeature.graphQL = graphQL; // return this; // } // // public Builder jacksonReaderWriter(JacksonReaderWriter jacksonReaderWriter) { // graphQLFeature.jacksonReaderWriter = jacksonReaderWriter; // return this; // } // // public GraphQLFeature build() { // return graphQLFeature; // } // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLFeatureProvider.java import com.google.inject.Inject; import com.google.inject.Provider; import graphql.GraphQL; import org.objectstyle.graphql.rest.GraphQLFeature; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; package org.objectstyle.graphql.bootique; class GraphQLFeatureProvider implements Provider<GraphQLFeature> { @Inject private GraphQL graphQL; @Inject
private JacksonReaderWriter jacksonReaderWriter;
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/MessageResponseWriter.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // }
import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import org.objectstyle.graphql.rest.MessageResponse; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter;
package org.objectstyle.graphql.rest.provider; public class MessageResponseWriter implements MessageBodyWriter<MessageResponse> { @Context Configuration config; @Override public long getSize(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MessageResponse.class.isAssignableFrom(type); } @Override public void writeTo(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/MessageResponseWriter.java import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import org.objectstyle.graphql.rest.MessageResponse; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; package org.objectstyle.graphql.rest.provider; public class MessageResponseWriter implements MessageBodyWriter<MessageResponse> { @Context Configuration config; @Override public long getSize(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MessageResponse.class.isAssignableFrom(type); } @Override public void writeTo(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
JsonWriter writer = (JsonWriter) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/MessageResponseWriter.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // }
import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import org.objectstyle.graphql.rest.MessageResponse; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter;
package org.objectstyle.graphql.rest.provider; public class MessageResponseWriter implements MessageBodyWriter<MessageResponse> { @Context Configuration config; @Override public long getSize(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MessageResponse.class.isAssignableFrom(type); } @Override public void writeTo(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/MessageResponseWriter.java import java.io.IOException; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyWriter; import org.objectstyle.graphql.rest.MessageResponse; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonWriter; package org.objectstyle.graphql.rest.provider; public class MessageResponseWriter implements MessageBodyWriter<MessageResponse> { @Context Configuration config; @Override public long getSize(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return MessageResponse.class.isAssignableFrom(type); } @Override public void writeTo(MessageResponse t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
JsonWriter writer = (JsonWriter) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E1.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E2;
package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E1 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E1 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E1.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E2; package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E1 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E1 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<List<E2>> E2S = new Property<List<E2>>("e2s");
objectstyle/graphql
graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E2.java
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E3; import org.objectstyle.graphql.example.cayenne.E1;
package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E2.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E3; import org.objectstyle.graphql.example.cayenne.E1; package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<E1> E1 = new Property<E1>("e1");
objectstyle/graphql
graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E2.java
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E3; import org.objectstyle.graphql.example.cayenne.E1;
package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name"); public static final Property<E1> E1 = new Property<E1>("e1");
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E2.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E3; import org.objectstyle.graphql.example.cayenne.E1; package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name"); public static final Property<E1> E1 = new Property<E1>("e1");
public static final Property<List<E3>> E3S = new Property<List<E3>>("e3s");
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap;
package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL;
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL;
private static TestFactory testFactory = new TestFactory();
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap;
package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL; private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTestFactory.class); GraphQLTestFactory() { graphQL = createGraphQL(createSchemaTranslator()); } @AfterClass public static void tearDownClass() { testFactory.stopServerRuntime(); }
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL; private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTestFactory.class); GraphQLTestFactory() { graphQL = createGraphQL(createSchemaTranslator()); } @AfterClass public static void tearDownClass() { testFactory.stopServerRuntime(); }
private static GraphQL createGraphQL(SchemaTranslator translator) {
objectstyle/graphql
graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap;
package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL; private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTestFactory.class); GraphQLTestFactory() { graphQL = createGraphQL(createSchemaTranslator()); } @AfterClass public static void tearDownClass() { testFactory.stopServerRuntime(); } private static GraphQL createGraphQL(SchemaTranslator translator) { return new GraphQL(translator.toGraphQL()); } private static SchemaTranslator createSchemaTranslator() {
// Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/TestFactory.java // public class TestFactory { // // private ServerRuntime serverRuntime; // private ObjectContext objectContext; // // public TestFactory(){ // createServerRuntime(); // } // // private void createServerRuntime() { // removeDerbyDirectory(); // // serverRuntime = ServerRuntimeBuilder.builder().addConfig("cayenne-tests.xml") // .url("jdbc:derby:target/derby;create=true").jdbcDriver("org.apache.derby.jdbc.EmbeddedDriver") // .addModule(cayenneExtensions()).build(); // // objectContext = serverRuntime.newContext(); // // insertTestData(); // } // // public void stopServerRuntime() { // serverRuntime.shutdown(); // serverRuntime = null; // // stopDerby(); // } // // private static org.apache.cayenne.di.Module cayenneExtensions() { // return (b) -> b.bind(SchemaUpdateStrategy.class).to(CreateIfNoSchemaStrategy.class); // } // // private void insertTestData() { // insert("e1", "id, name", "1, 'a'"); // insert("e1", "id, name", "2, 'b'"); // // insert("e2", "id, name, e1_id", "3, 'c', 1"); // insert("e2", "id, name, e1_id", "4, 'd', 2"); // insert("e2", "id, name, e1_id", "5, 'e', 2"); // // insert("e3", "id, name, e2_id", "6, 'f', 4"); // insert("e3", "id, name, e2_id", "7, 'g', 4"); // insert("e3", "id, name, e2_id", "8, 'h', 5"); // } // // private void insert(String table, String columns, String values) { // String insertSql = "INSERT INTO utest." + table + " (" + columns + ") VALUES (" + values + ")"; // objectContext.performGenericQuery(new SQLTemplate(table, insertSql)); // } // // private void removeDerbyDirectory() { // // File derbyDir = new File("target/derby"); // if (derbyDir.isDirectory()) { // try { // FileUtils.deleteDirectory(derbyDir); // } catch (IOException e) { // throw new RuntimeException(e); // } // } // } // // private void stopDerby() { // try { // DriverManager.getConnection("jdbc:derby:;shutdown=true"); // } catch (SQLException ignored) { // } // } // // public ObjectContext getObjectContext() { // return objectContext; // } // // public ServerRuntime getServerRuntime() { // return serverRuntime; // } // } // Path: graphql-cayenne/src/test/java/org/objectstyle/graphql/cayenne/it/GraphQLTestFactory.java import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.junit.AfterClass; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import org.objectstyle.graphql.test.TestFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.HashMap; package org.objectstyle.graphql.cayenne.it; class GraphQLTestFactory { private static GraphQL graphQL; private static TestFactory testFactory = new TestFactory(); private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLTestFactory.class); GraphQLTestFactory() { graphQL = createGraphQL(createSchemaTranslator()); } @AfterClass public static void tearDownClass() { testFactory.stopServerRuntime(); } private static GraphQL createGraphQL(SchemaTranslator translator) { return new GraphQL(translator.toGraphQL()); } private static SchemaTranslator createSchemaTranslator() {
return new DefaultSchemaTranslator(testFactory.getObjectContext());
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // }
import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema;
package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema; package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) {
binder.bind(JacksonReaderWriter.class).in(Singleton.class);
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // }
import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema;
package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class);
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema; package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class);
binder.bind(JsonReader.class).to(JacksonReaderWriter.class);
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // }
import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema;
package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class);
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema; package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class);
binder.bind(JsonWriter.class).to(JacksonReaderWriter.class);
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // }
import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema;
package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class); binder.bind(JsonWriter.class).to(JacksonReaderWriter.class); JerseyModule.contributeFeatures(binder).addBinding().toProvider(GraphQLFeatureProvider.class); } @Provides @Singleton
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema; package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class); binder.bind(JsonWriter.class).to(JacksonReaderWriter.class); JerseyModule.contributeFeatures(binder).addBinding().toProvider(GraphQLFeatureProvider.class); } @Provides @Singleton
GraphQL createGraphQL( SchemaTranslator translator) {
objectstyle/graphql
graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // }
import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema;
package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class); binder.bind(JsonWriter.class).to(JacksonReaderWriter.class); JerseyModule.contributeFeatures(binder).addBinding().toProvider(GraphQLFeatureProvider.class); } @Provides @Singleton GraphQL createGraphQL( SchemaTranslator translator) { GraphQLSchema schema = translator.toGraphQL(); return new GraphQL(schema); } @Provides @Singleton SchemaTranslator createSchemaTranslator(ServerRuntime cayenneRuntime) {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonWriter.java // public interface JsonWriter { // // void write(OutputStream out, JacksonWriterDelegate delegate); // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/DefaultSchemaTranslator.java // public class DefaultSchemaTranslator implements SchemaTranslator { // // private ObjectContext selectContext; // // public DefaultSchemaTranslator(ObjectContext selectContext) { // this.selectContext = selectContext; // } // // @Override // public GraphQLSchema toGraphQL() { // return SchemaBuilder.builder(selectContext).mutationType(MutationType.builder(selectContext).build()) // .build(); // } // } // // Path: graphql-cayenne/src/main/java/org/objectstyle/graphql/cayenne/orm/SchemaTranslator.java // public interface SchemaTranslator { // // GraphQLSchema toGraphQL(); // } // Path: graphql-bootique/src/main/java/org/objectstyle/graphql/bootique/GraphQLModule.java import com.google.inject.*; import io.bootique.jersey.JerseyModule; import io.bootique.ConfigModule; import org.apache.cayenne.configuration.server.ServerRuntime; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; import org.objectstyle.graphql.rest.json.JsonWriter; import org.objectstyle.graphql.cayenne.orm.DefaultSchemaTranslator; import org.objectstyle.graphql.cayenne.orm.SchemaTranslator; import graphql.GraphQL; import graphql.schema.GraphQLSchema; package org.objectstyle.graphql.bootique; public class GraphQLModule extends ConfigModule { @Override public void configure(Binder binder) { binder.bind(JacksonReaderWriter.class).in(Singleton.class); binder.bind(JsonReader.class).to(JacksonReaderWriter.class); binder.bind(JsonWriter.class).to(JacksonReaderWriter.class); JerseyModule.contributeFeatures(binder).addBinding().toProvider(GraphQLFeatureProvider.class); } @Provides @Singleton GraphQL createGraphQL( SchemaTranslator translator) { GraphQLSchema schema = translator.toGraphQL(); return new GraphQL(schema); } @Provides @Singleton SchemaTranslator createSchemaTranslator(ServerRuntime cayenneRuntime) {
return new DefaultSchemaTranslator(cayenneRuntime.newContext());
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // }
import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader;
package org.objectstyle.graphql.rest.provider; @Singleton @Provider
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; package org.objectstyle.graphql.rest.provider; @Singleton @Provider
public class GraphQLRestQueryReader implements MessageBodyReader<GraphQLRestQuery> {
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // }
import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader;
package org.objectstyle.graphql.rest.provider; @Singleton @Provider public class GraphQLRestQueryReader implements MessageBodyReader<GraphQLRestQuery> { @Context Configuration config; @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return GraphQLRestQuery.class.isAssignableFrom(type); } @Override public GraphQLRestQuery readFrom(Class<GraphQLRestQuery> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; package org.objectstyle.graphql.rest.provider; @Singleton @Provider public class GraphQLRestQueryReader implements MessageBodyReader<GraphQLRestQuery> { @Context Configuration config; @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return GraphQLRestQuery.class.isAssignableFrom(type); } @Override public GraphQLRestQuery readFrom(Class<GraphQLRestQuery> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
JsonReader jsonReader = (JsonReader) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // }
import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader;
package org.objectstyle.graphql.rest.provider; @Singleton @Provider public class GraphQLRestQueryReader implements MessageBodyReader<GraphQLRestQuery> { @Context Configuration config; @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return GraphQLRestQuery.class.isAssignableFrom(type); } @Override public GraphQLRestQuery readFrom(Class<GraphQLRestQuery> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestQuery.java // public class GraphQLRestQuery { // // private String query; // private String variables; // // public String getQuery() { // return query; // } // // public void setQuery(String query) { // this.query = query; // } // // public String getVariables() { // return variables; // } // // public void setVariables(String variables) { // this.variables = variables; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java // public class JacksonReaderWriter implements JsonReader, JsonWriter { // // private ObjectMapper sharedMapper; // private JsonFactory sharedFactory; // // public JacksonReaderWriter() { // // // fun Jackson API with circular dependencies ... so we create a mapper // // first, and grab implicitly created factory from it // this.sharedMapper = new ObjectMapper(); // this.sharedFactory = sharedMapper.getFactory(); // // // make sure mapper does not attempt closing streams it does not // // manage... why is this even a default in jackson? // sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // // // do not flush every time. why would we want to do that? // // this is having a HUGE impact on extrest serializers (5x speedup) // sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); // } // // private JsonNode parseJson(InputStream jsonStream) { // Objects.requireNonNull(jsonStream); // // try { // com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); // return new ObjectMapper().readTree(parser); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e); // } // } // // @Override // public <T> T read(Class<T> type, InputStream jsonStream) { // JsonNode jsonNode = parseJson(jsonStream); // try { // return new ObjectMapper().readValue(new TreeTraversingParser(jsonNode), type); // } catch (IOException e) { // throw new GraphQLRestException(Status.BAD_REQUEST, "Error mapping JSON to object", e); // } // } // // @Override // public void write(OutputStream out, JacksonWriterDelegate delegate) { // // TODO: UTF-8 is hardcoded... // try (JsonGenerator generator = sharedFactory.createGenerator(out, JsonEncoding.UTF8)) { // delegate.write(generator); // } catch (IOException e) { // throw new GraphQLRestException(Status.INTERNAL_SERVER_ERROR, "Error writing JSON", e); // } // } // // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JsonReader.java // public interface JsonReader { // // <T> T read(Class<T> type, InputStream jsonStream); // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestQueryReader.java import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestQuery; import org.objectstyle.graphql.rest.json.JacksonReaderWriter; import org.objectstyle.graphql.rest.json.JsonReader; package org.objectstyle.graphql.rest.provider; @Singleton @Provider public class GraphQLRestQueryReader implements MessageBodyReader<GraphQLRestQuery> { @Context Configuration config; @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return GraphQLRestQuery.class.isAssignableFrom(type); } @Override public GraphQLRestQuery readFrom(Class<GraphQLRestQuery> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
JsonReader jsonReader = (JsonReader) config.getProperty(JacksonReaderWriter.class.getName());
objectstyle/graphql
graphql-example/src/main/java/org/objectstyle/graphql/example/Main.java
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // }
import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.apache.cayenne.query.SQLTemplate; import org.objectstyle.graphql.example.cayenne.E1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Module; import io.bootique.Bootique;
package org.objectstyle.graphql.example; /** * GraphQL server runner with example schema. */ public class Main implements Module { private static Logger LOGGER = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { Bootique.app(args).autoLoadModules().module(Main.class).run(); } @Override public void configure(Binder binder) { binder.bind(TestDataLoader.class).asEagerSingleton(); } static class TestDataLoader { @Inject public TestDataLoader(ServerRuntime runtime) { createDummyData(runtime.newContext()); } private void createDummyData(ObjectContext context) {
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/Main.java import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.apache.cayenne.query.SQLTemplate; import org.objectstyle.graphql.example.cayenne.E1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Binder; import com.google.inject.Inject; import com.google.inject.Module; import io.bootique.Bootique; package org.objectstyle.graphql.example; /** * GraphQL server runner with example schema. */ public class Main implements Module { private static Logger LOGGER = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { Bootique.app(args).autoLoadModules().module(Main.class).run(); } @Override public void configure(Binder binder) { binder.bind(TestDataLoader.class).asEagerSingleton(); } static class TestDataLoader { @Inject public TestDataLoader(ServerRuntime runtime) { createDummyData(runtime.newContext()); } private void createDummyData(ObjectContext context) {
if (ObjectSelect.query(E1.class).selectFirst(context) == null) {
objectstyle/graphql
graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E2.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E3;
package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E2.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E3; package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<E1> E1 = new Property<E1>("e1");
objectstyle/graphql
graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E2.java
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E3;
package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name"); public static final Property<E1> E1 = new Property<E1>("e1");
// Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E1.java // public class E1 extends _E1 { // // private static final long serialVersionUID = 1L; // // } // // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/E3.java // public class E3 extends _E3 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-test/src/main/java/org/objectstyle/graphql/test/cayenne/auto/_E2.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.test.cayenne.E1; import org.objectstyle.graphql.test.cayenne.E3; package org.objectstyle.graphql.test.cayenne.auto; /** * Class _E2 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E2 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> E1_ID = new Property<Integer>("e1_id"); public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name"); public static final Property<E1> E1 = new Property<E1>("e1");
public static final Property<List<E3>> E3S = new Property<List<E3>>("e3s");
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Objects; import javax.ws.rs.core.Response.Status; import org.objectstyle.graphql.rest.GraphQLRestException; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.TreeTraversingParser;
package org.objectstyle.graphql.rest.json; public class JacksonReaderWriter implements JsonReader, JsonWriter { private ObjectMapper sharedMapper; private JsonFactory sharedFactory; public JacksonReaderWriter() { // fun Jackson API with circular dependencies ... so we create a mapper // first, and grab implicitly created factory from it this.sharedMapper = new ObjectMapper(); this.sharedFactory = sharedMapper.getFactory(); // make sure mapper does not attempt closing streams it does not // manage... why is this even a default in jackson? sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // do not flush every time. why would we want to do that? // this is having a HUGE impact on extrest serializers (5x speedup) sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); } private JsonNode parseJson(InputStream jsonStream) { Objects.requireNonNull(jsonStream); try { com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); return new ObjectMapper().readTree(parser); } catch (IOException e) {
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/json/JacksonReaderWriter.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Objects; import javax.ws.rs.core.Response.Status; import org.objectstyle.graphql.rest.GraphQLRestException; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.TreeTraversingParser; package org.objectstyle.graphql.rest.json; public class JacksonReaderWriter implements JsonReader, JsonWriter { private ObjectMapper sharedMapper; private JsonFactory sharedFactory; public JacksonReaderWriter() { // fun Jackson API with circular dependencies ... so we create a mapper // first, and grab implicitly created factory from it this.sharedMapper = new ObjectMapper(); this.sharedFactory = sharedMapper.getFactory(); // make sure mapper does not attempt closing streams it does not // manage... why is this even a default in jackson? sharedFactory.disable(Feature.AUTO_CLOSE_TARGET); // do not flush every time. why would we want to do that? // this is having a HUGE impact on extrest serializers (5x speedup) sharedMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); } private JsonNode parseJson(InputStream jsonStream) { Objects.requireNonNull(jsonStream); try { com.fasterxml.jackson.core.JsonParser parser = sharedFactory.createParser(jsonStream); return new ObjectMapper().readTree(parser); } catch (IOException e) {
throw new GraphQLRestException(Status.BAD_REQUEST, "Error parsing JSON", e);
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestExceptionMapper.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // }
import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestException; import org.objectstyle.graphql.rest.MessageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.objectstyle.graphql.rest.provider; @Provider @Singleton
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestExceptionMapper.java import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestException; import org.objectstyle.graphql.rest.MessageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.objectstyle.graphql.rest.provider; @Provider @Singleton
public class GraphQLRestExceptionMapper implements ExceptionMapper<GraphQLRestException> {
objectstyle/graphql
graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestExceptionMapper.java
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // }
import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestException; import org.objectstyle.graphql.rest.MessageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class GraphQLRestExceptionMapper implements ExceptionMapper<GraphQLRestException> { private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLRestExceptionMapper.class); @Override public Response toResponse(GraphQLRestException exception) { String message = exception.getMessage(); Status status = exception.getStatus(); if (LOGGER.isInfoEnabled()) { StringBuilder log = new StringBuilder(); log.append(status.getStatusCode()).append(" ").append(status.getReasonPhrase()); if (message != null) { log.append(" (").append(message).append(")"); } if (exception.getCause() != null && exception.getCause().getMessage() != null) { log.append(" [cause: ").append(exception.getCause().getMessage()).append("]"); } // include stack trace in debug mode... if (LOGGER.isDebugEnabled()) { LOGGER.debug(log.toString(), exception); } else { LOGGER.info(log.toString()); } }
// Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/GraphQLRestException.java // public class GraphQLRestException extends RuntimeException { // // private static final long serialVersionUID = -1228276457093874409L; // // private Status status; // // public GraphQLRestException() { // this(Status.INTERNAL_SERVER_ERROR); // } // // public GraphQLRestException(Status status) { // this(status, null, null); // } // // public GraphQLRestException(Status status, String message) { // this(status, message, null); // } // // public GraphQLRestException(Status status, String message, Throwable cause) { // super(message, cause); // this.status = status; // } // // public Status getStatus() { // return status; // } // } // // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/MessageResponse.java // public class MessageResponse { // // private String message; // // public MessageResponse(String message) { // this.message = message; // } // // public String getMessage() { // return message; // } // } // Path: graphql-rest/src/main/java/org/objectstyle/graphql/rest/provider/GraphQLRestExceptionMapper.java import javax.inject.Singleton; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.objectstyle.graphql.rest.GraphQLRestException; import org.objectstyle.graphql.rest.MessageResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.objectstyle.graphql.rest.provider; @Provider @Singleton public class GraphQLRestExceptionMapper implements ExceptionMapper<GraphQLRestException> { private static final Logger LOGGER = LoggerFactory.getLogger(GraphQLRestExceptionMapper.class); @Override public Response toResponse(GraphQLRestException exception) { String message = exception.getMessage(); Status status = exception.getStatus(); if (LOGGER.isInfoEnabled()) { StringBuilder log = new StringBuilder(); log.append(status.getStatusCode()).append(" ").append(status.getReasonPhrase()); if (message != null) { log.append(" (").append(message).append(")"); } if (exception.getCause() != null && exception.getCause().getMessage() != null) { log.append(" [cause: ").append(exception.getCause().getMessage()).append("]"); } // include stack trace in debug mode... if (LOGGER.isDebugEnabled()) { LOGGER.debug(log.toString(), exception); } else { LOGGER.info(log.toString()); } }
return Response.status(status).entity(new MessageResponse(message)).type(MediaType.APPLICATION_JSON_TYPE)
objectstyle/graphql
graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E1.java
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E2;
package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E1 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E1 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
// Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/E2.java // public class E2 extends _E2 { // // private static final long serialVersionUID = 1L; // // } // Path: graphql-example/src/main/java/org/objectstyle/graphql/example/cayenne/auto/_E1.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import org.objectstyle.graphql.example.cayenne.E2; package org.objectstyle.graphql.example.cayenne.auto; /** * Class _E1 was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _E1 extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String ID_PK_COLUMN = "id"; public static final Property<Integer> ID = new Property<Integer>("id"); public static final Property<String> NAME = new Property<String>("name");
public static final Property<List<E2>> E2S = new Property<List<E2>>("e2s");
childe/hangout
hangout-filters/hangout-filters-trim/src/test/java/com/ctrip/ops/sysdev/test/TestTrimFilter.java
// Path: hangout-filters/hangout-filters-trim/src/main/java/com/ctrip/ops/sysdev/filters/Trim.java // @Log4j2 // public class Trim extends BaseFilter { // // public Trim(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // // TemplateRender templateRender = null; // try { // templateRender = TemplateRender.getRender(field, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + field); // } // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), templateRender)); // } // } // // @Override // protected Map filter(final Map event) { // for (Tuple2 t2 : fields) { // Object value = ((TemplateRender) t2._2()).render(event); // if (value != null && String.class.isAssignableFrom(value.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) value).trim()); // } // } // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Trim; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestTrimFilter { @Test public void testTrimFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-trim/src/main/java/com/ctrip/ops/sysdev/filters/Trim.java // @Log4j2 // public class Trim extends BaseFilter { // // public Trim(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // // TemplateRender templateRender = null; // try { // templateRender = TemplateRender.getRender(field, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + field); // } // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), templateRender)); // } // } // // @Override // protected Map filter(final Map event) { // for (Tuple2 t2 : fields) { // Object value = ((TemplateRender) t2._2()).render(event); // if (value != null && String.class.isAssignableFrom(value.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) value).trim()); // } // } // return event; // } // } // Path: hangout-filters/hangout-filters-trim/src/test/java/com/ctrip/ops/sysdev/test/TestTrimFilter.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Trim; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestTrimFilter { @Test public void testTrimFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Trim trimFilter = new Trim(config);
childe/hangout
hangout-filters/hangout-filters-translate/src/test/java/com/ctrip/ops/sysdev/test/TestTranslate.java
// Path: hangout-filters/hangout-filters-translate/src/main/java/com/ctrip/ops/sysdev/filters/Translate.java // @Log4j2 // public class Translate extends BaseFilter { // // public Translate(Map config) { // super(config); // } // // private FieldSetter target; // private TemplateRender source; // private String dictionaryPath; // private int refreshInterval; // private long nextLoadTime; // private HashMap dictionary; // // private void loadDictionary() { // log.info("begin to loadDictionary: " + this.dictionaryPath); // // Yaml yaml = new Yaml(); // // if (dictionaryPath.startsWith("http://") || dictionaryPath.startsWith("https://")) { // URL httpUrl; // URLConnection connection; // try { // httpUrl = new URL(dictionaryPath); // connection = httpUrl.openConnection(); // connection.connect(); // dictionary = (HashMap) yaml.load(connection.getInputStream()); // } catch (IOException e) { // e.printStackTrace(); // log.error("failed to load " + dictionaryPath); // System.exit(1); // } // } else { // FileInputStream input; // try { // input = new FileInputStream(new File(dictionaryPath)); // dictionary = (HashMap) yaml.load(input); // } catch (FileNotFoundException e) { // log.error(dictionaryPath + " is not found"); // log.error(e.getMessage()); // System.exit(1); // } // } // // log.info("loadDictionary done: " + this.dictionaryPath); // } // // protected void prepare() { // String sourceField = (String) config.get("source"); // String targetField = (String) config.get("target"); // try { // this.source = TemplateRender.getRender(sourceField, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + sourceField); // System.exit(1); // } // this.target = FieldSetter.getFieldSetter(targetField); // // dictionaryPath = (String) config.get("dictionary_path"); // // if (dictionaryPath == null) { // log.fatal("dictionary_path must be inclued in config"); // System.exit(1); // } // // loadDictionary(); // // if (config.containsKey("refresh_interval")) { // this.refreshInterval = (Integer) config.get("refresh_interval") * 1000; // } else { // this.refreshInterval = 300 * 1000; // } // nextLoadTime = System.currentTimeMillis() + refreshInterval; // } // // @Override // protected Map filter(final Map event) { // if (System.currentTimeMillis() >= nextLoadTime) { // loadDictionary(); // nextLoadTime += refreshInterval; // } // if (this.dictionary == null) { // log.debug("dictionary is null, return without any change"); // return event; // } // Object t = dictionary.get(this.source.render(event)); // if (t != null) { // this.target.setField(event, t); // } // return event; // } // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Translate; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestTranslate { @Test public void testTranslate() throws IOException { File temp = File.createTempFile("test-dict", ".yml"); BufferedWriter output = new BufferedWriter(new FileWriter(temp)); output.write("abc: xyz\n"); output.flush(); String c = String .format("%s\n%s\n%s", "dictionary_path: " + temp.getAbsolutePath(), "source: name", "target: nick" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-translate/src/main/java/com/ctrip/ops/sysdev/filters/Translate.java // @Log4j2 // public class Translate extends BaseFilter { // // public Translate(Map config) { // super(config); // } // // private FieldSetter target; // private TemplateRender source; // private String dictionaryPath; // private int refreshInterval; // private long nextLoadTime; // private HashMap dictionary; // // private void loadDictionary() { // log.info("begin to loadDictionary: " + this.dictionaryPath); // // Yaml yaml = new Yaml(); // // if (dictionaryPath.startsWith("http://") || dictionaryPath.startsWith("https://")) { // URL httpUrl; // URLConnection connection; // try { // httpUrl = new URL(dictionaryPath); // connection = httpUrl.openConnection(); // connection.connect(); // dictionary = (HashMap) yaml.load(connection.getInputStream()); // } catch (IOException e) { // e.printStackTrace(); // log.error("failed to load " + dictionaryPath); // System.exit(1); // } // } else { // FileInputStream input; // try { // input = new FileInputStream(new File(dictionaryPath)); // dictionary = (HashMap) yaml.load(input); // } catch (FileNotFoundException e) { // log.error(dictionaryPath + " is not found"); // log.error(e.getMessage()); // System.exit(1); // } // } // // log.info("loadDictionary done: " + this.dictionaryPath); // } // // protected void prepare() { // String sourceField = (String) config.get("source"); // String targetField = (String) config.get("target"); // try { // this.source = TemplateRender.getRender(sourceField, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + sourceField); // System.exit(1); // } // this.target = FieldSetter.getFieldSetter(targetField); // // dictionaryPath = (String) config.get("dictionary_path"); // // if (dictionaryPath == null) { // log.fatal("dictionary_path must be inclued in config"); // System.exit(1); // } // // loadDictionary(); // // if (config.containsKey("refresh_interval")) { // this.refreshInterval = (Integer) config.get("refresh_interval") * 1000; // } else { // this.refreshInterval = 300 * 1000; // } // nextLoadTime = System.currentTimeMillis() + refreshInterval; // } // // @Override // protected Map filter(final Map event) { // if (System.currentTimeMillis() >= nextLoadTime) { // loadDictionary(); // nextLoadTime += refreshInterval; // } // if (this.dictionary == null) { // log.debug("dictionary is null, return without any change"); // return event; // } // Object t = dictionary.get(this.source.render(event)); // if (t != null) { // this.target.setField(event, t); // } // return event; // } // } // Path: hangout-filters/hangout-filters-translate/src/test/java/com/ctrip/ops/sysdev/test/TestTranslate.java import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Translate; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestTranslate { @Test public void testTranslate() throws IOException { File temp = File.createTempFile("test-dict", ".yml"); BufferedWriter output = new BufferedWriter(new FileWriter(temp)); output.write("abc: xyz\n"); output.flush(); String c = String .format("%s\n%s\n%s", "dictionary_path: " + temp.getAbsolutePath(), "source: name", "target: nick" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Translate filter = new Translate(config);
childe/hangout
hangout-filters/hangout-filters-ua/src/test/java/com/ctrip/ops/sysdev/test/TestUA.java
// Path: hangout-filters/hangout-filters-ua/src/main/java/com/ctrip/ops/sysdev/filters/UA.java // @Log4j2 // public class UA extends BaseFilter { // // // public UA(Map config) { // super(config); // } // // private String source; // private Parser uaParser; // // protected void prepare() { // if (!config.containsKey("source")) { // log.error("no field configured in Json"); // System.exit(1); // } // this.source = (String) config.get("source"); // // try { // this.uaParser = new Parser(); // } catch (IOException e) { // log.error(e); // e.printStackTrace(); // System.exit(1); // } // }; // // @SuppressWarnings("unchecked") // @Override // protected Map filter(final Map event) { // if (event.containsKey(this.source)) { // Client c = uaParser.parse((String) event.get(this.source)); // // event.put("userAgent_family", c.userAgent.family); // event.put("userAgent_major", c.userAgent.major); // event.put("userAgent_minor", c.userAgent.minor); // event.put("os_family", c.os.family); // event.put("os_major", c.os.major); // event.put("os_minor", c.os.minor); // event.put("device_family", c.device.family); // } // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.UA; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestUA { @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testUA() { // General Test String c = String.format("%s\n", "source: ua"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-ua/src/main/java/com/ctrip/ops/sysdev/filters/UA.java // @Log4j2 // public class UA extends BaseFilter { // // // public UA(Map config) { // super(config); // } // // private String source; // private Parser uaParser; // // protected void prepare() { // if (!config.containsKey("source")) { // log.error("no field configured in Json"); // System.exit(1); // } // this.source = (String) config.get("source"); // // try { // this.uaParser = new Parser(); // } catch (IOException e) { // log.error(e); // e.printStackTrace(); // System.exit(1); // } // }; // // @SuppressWarnings("unchecked") // @Override // protected Map filter(final Map event) { // if (event.containsKey(this.source)) { // Client c = uaParser.parse((String) event.get(this.source)); // // event.put("userAgent_family", c.userAgent.family); // event.put("userAgent_major", c.userAgent.major); // event.put("userAgent_minor", c.userAgent.minor); // event.put("os_family", c.os.family); // event.put("os_major", c.os.major); // event.put("os_minor", c.os.minor); // event.put("device_family", c.device.family); // } // return event; // } // } // Path: hangout-filters/hangout-filters-ua/src/test/java/com/ctrip/ops/sysdev/test/TestUA.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.UA; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestUA { @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testUA() { // General Test String c = String.format("%s\n", "source: ua"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
UA UAfilter = new UA(config);
childe/hangout
hangout-filters/hangout-filters-json/src/test/java/com/ctrip/ops/sysdev/test/TestJsonFilter.java
// Path: hangout-filters/hangout-filters-json/src/main/java/com/ctrip/ops/sysdev/filters/Json.java // @Log4j2 // public class Json extends BaseFilter { // // public Json(Map config) { // super(config); // } // // private String field; // private TemplateRender templateRender; // private FieldSetter fieldSetter; // // protected void prepare() { // if (!config.containsKey("field")) { // log.error("no field configured in Json"); // System.exit(1); // } // this.field = (String) config.get("field"); // // String target = (String) config.get("target"); // if (target == null || target.equals("")) { // this.fieldSetter = null; // } else { // this.fieldSetter = FieldSetter.getFieldSetter(target); // } // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "jsonfail"; // } // // try { // this.templateRender = TemplateRender.getRender(field, false); // } catch (Exception e) { // log.error("could not render template: " + field); // System.exit(1); // } // } // // @Override // protected Map filter(final Map event) { // Object obj = null; // boolean success = false; // // Object o = this.templateRender.render(event); // if (o != null) { // try { // obj = JSONValue // .parseWithException((String) o); // success = true; // } catch (Exception e) { // log.debug("failed to json parse field: " + this.field); // } // } // // if (obj != null) { // if (this.fieldSetter == null) { // try { // event.putAll((Map) obj); // } catch (Exception e) { // log.warn(this.field + " is not a map, you should set a target to save it"); // success = false; // } // } else { // this.fieldSetter.setField(event, obj); // } // } // // this.postProcess(event, success); // return event; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Json; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestJsonFilter { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testJsonFilter() { // General Test String c = String.format("%s\n%s", "field: message", "remove_fields: ['message','abcd']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-json/src/main/java/com/ctrip/ops/sysdev/filters/Json.java // @Log4j2 // public class Json extends BaseFilter { // // public Json(Map config) { // super(config); // } // // private String field; // private TemplateRender templateRender; // private FieldSetter fieldSetter; // // protected void prepare() { // if (!config.containsKey("field")) { // log.error("no field configured in Json"); // System.exit(1); // } // this.field = (String) config.get("field"); // // String target = (String) config.get("target"); // if (target == null || target.equals("")) { // this.fieldSetter = null; // } else { // this.fieldSetter = FieldSetter.getFieldSetter(target); // } // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "jsonfail"; // } // // try { // this.templateRender = TemplateRender.getRender(field, false); // } catch (Exception e) { // log.error("could not render template: " + field); // System.exit(1); // } // } // // @Override // protected Map filter(final Map event) { // Object obj = null; // boolean success = false; // // Object o = this.templateRender.render(event); // if (o != null) { // try { // obj = JSONValue // .parseWithException((String) o); // success = true; // } catch (Exception e) { // log.debug("failed to json parse field: " + this.field); // } // } // // if (obj != null) { // if (this.fieldSetter == null) { // try { // event.putAll((Map) obj); // } catch (Exception e) { // log.warn(this.field + " is not a map, you should set a target to save it"); // success = false; // } // } else { // this.fieldSetter.setField(event, obj); // } // } // // this.postProcess(event, success); // return event; // } // } // Path: hangout-filters/hangout-filters-json/src/test/java/com/ctrip/ops/sysdev/test/TestJsonFilter.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Json; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestJsonFilter { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testJsonFilter() { // General Test String c = String.format("%s\n%s", "field: message", "remove_fields: ['message','abcd']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Json Jsonfilter = new Json(config);
childe/hangout
hangout-filters/hangout-filters-remove/src/test/java/com/ctrip/ops/sysdev/test/TestRemoveFilter.java
// Path: hangout-filters/hangout-filters-remove/src/main/java/com/ctrip/ops/sysdev/filters/Remove.java // @SuppressWarnings("ALL") // public class Remove extends BaseFilter { // public Remove(Map config) { // super(config); // } // // private ArrayList<FieldDeleter> fields; // // protected void prepare() { // // this.fields = new ArrayList<>(); // for (String field : (ArrayList<String>) config.get("fields")) { // this.fields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // @Override // protected Map filter(final Map event) { // for (FieldDeleter t : this.fields) { // t.delete(event); // } // // return event; // } // }
import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.filters.Remove; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestRemoveFilter { @Test public void testRemoveFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - gender", " - '[name][first]'", " - '[value][list][value1]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-remove/src/main/java/com/ctrip/ops/sysdev/filters/Remove.java // @SuppressWarnings("ALL") // public class Remove extends BaseFilter { // public Remove(Map config) { // super(config); // } // // private ArrayList<FieldDeleter> fields; // // protected void prepare() { // // this.fields = new ArrayList<>(); // for (String field : (ArrayList<String>) config.get("fields")) { // this.fields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // @Override // protected Map filter(final Map event) { // for (FieldDeleter t : this.fields) { // t.delete(event); // } // // return event; // } // } // Path: hangout-filters/hangout-filters-remove/src/test/java/com/ctrip/ops/sysdev/test/TestRemoveFilter.java import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.filters.Remove; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestRemoveFilter { @Test public void testRemoveFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - gender", " - '[name][first]'", " - '[value][list][value1]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Remove removeFilter = new Remove(config);
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/utils/Utils.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java // @Log4j2 // public class BaseFilter extends Base { // // protected Map config; // protected String tagOnFailure; // protected List<FieldDeleter> removeFields; // protected Map<FieldSetter, TemplateRender> addFields; // private List<TemplateRender> IF; // public boolean processExtraEventsFunc; // public BaseFilter nextFilter; // public List<BaseOutput> outputs; // // public BaseFilter(Map config) { // super(config); // this.config = config; // // this.nextFilter = null; // this.outputs = new ArrayList<BaseOutput>(); // // final List<String> ifConditions = (List<String>) this.config.get("if"); // if (ifConditions != null) { // IF = new ArrayList<TemplateRender>(ifConditions.size()); // for (String c : ifConditions) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage(),e); // System.exit(1); // } // } // } // // this.tagOnFailure = (String) config.get("tag_on_failure"); // // final List<String> remove_fields = (ArrayList<String>) config.get("remove_fields"); // if (remove_fields != null) { // this.removeFields = new ArrayList<>(remove_fields.size()); // for (String field : remove_fields) { // this.removeFields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // final Map<String, String> add_fields = (Map<String, String>) config.get("add_fields"); // if (add_fields != null) { // this.addFields = new HashMap<>(add_fields.size()); // final Iterator<Map.Entry<String, String>> it = add_fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // Object value = entry.getValue(); // // try { // this.addFields.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // this.prepare(); // } // // protected void prepare() { // } // // public boolean needProcess(Map event) { // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // return false; // } // } // } // return true; // } // // public Map process(Map event) { // if (event == null) { // return null; // } // // if (this.needProcess(event) == true) { // event = this.filter(event); // } // // if (event == null) { // return null; // } // // if (this.nextFilter != null) { // event = this.nextFilter.process(event); // } else { // for (BaseOutput o : this.outputs) { // o.process(event); // } // } // return event; // } // // public void processExtraEvents(Stack<Map<String, Object>> to_st) { // this.filterExtraEvents(to_st); // } // // protected Map filter(Map event) { // return event; // } // // protected void filterExtraEvents(Stack<Map<String, Object>> to_stt) { // return; // } // // public void postProcess(Map event, boolean ifSuccess) { // if (ifSuccess == false) { // if (this.tagOnFailure == null || this.tagOnFailure.length() <= 0) { // return; // } // if (!event.containsKey("tags")) { // event.put("tags", new ArrayList<String>(Arrays.asList(this.tagOnFailure))); // } else { // Object tags = event.get("tags"); // if (tags.getClass() == ArrayList.class // && ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) { // ((ArrayList) tags).add(this.tagOnFailure); // } // } // } else { // if (this.removeFields != null) { // for (FieldDeleter f : this.removeFields) { // f.delete(event); // } // } // // if (this.addFields != null) { // Iterator<Map.Entry<FieldSetter, TemplateRender>> it = this.addFields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // TemplateRender templateRender = entry.getValue(); // fieldSetter.setField(event, templateRender.render(event)); // } // } // } // } // }
import com.ctrip.ops.sysdev.baseplugin.BaseFilter; import lombok.extern.log4j.Log4j2; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map;
package com.ctrip.ops.sysdev.utils; @SuppressWarnings("ALL") @Log4j2 public class Utils {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java // @Log4j2 // public class BaseFilter extends Base { // // protected Map config; // protected String tagOnFailure; // protected List<FieldDeleter> removeFields; // protected Map<FieldSetter, TemplateRender> addFields; // private List<TemplateRender> IF; // public boolean processExtraEventsFunc; // public BaseFilter nextFilter; // public List<BaseOutput> outputs; // // public BaseFilter(Map config) { // super(config); // this.config = config; // // this.nextFilter = null; // this.outputs = new ArrayList<BaseOutput>(); // // final List<String> ifConditions = (List<String>) this.config.get("if"); // if (ifConditions != null) { // IF = new ArrayList<TemplateRender>(ifConditions.size()); // for (String c : ifConditions) { // try { // IF.add(new FreeMarkerRender(c, c)); // } catch (IOException e) { // log.fatal(e.getMessage(),e); // System.exit(1); // } // } // } // // this.tagOnFailure = (String) config.get("tag_on_failure"); // // final List<String> remove_fields = (ArrayList<String>) config.get("remove_fields"); // if (remove_fields != null) { // this.removeFields = new ArrayList<>(remove_fields.size()); // for (String field : remove_fields) { // this.removeFields.add(FieldDeleter.getFieldDeleter(field)); // } // } // // final Map<String, String> add_fields = (Map<String, String>) config.get("add_fields"); // if (add_fields != null) { // this.addFields = new HashMap<>(add_fields.size()); // final Iterator<Map.Entry<String, String>> it = add_fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, String> entry = it.next(); // // String field = entry.getKey(); // Object value = entry.getValue(); // // try { // this.addFields.put(FieldSetter.getFieldSetter(field), TemplateRender.getRender(value)); // } catch (IOException e) { // log.fatal(e.getMessage()); // System.exit(1); // } // } // } // // this.prepare(); // } // // protected void prepare() { // } // // public boolean needProcess(Map event) { // if (this.IF != null) { // for (TemplateRender render : this.IF) { // if (!render.render(event).equals("true")) { // return false; // } // } // } // return true; // } // // public Map process(Map event) { // if (event == null) { // return null; // } // // if (this.needProcess(event) == true) { // event = this.filter(event); // } // // if (event == null) { // return null; // } // // if (this.nextFilter != null) { // event = this.nextFilter.process(event); // } else { // for (BaseOutput o : this.outputs) { // o.process(event); // } // } // return event; // } // // public void processExtraEvents(Stack<Map<String, Object>> to_st) { // this.filterExtraEvents(to_st); // } // // protected Map filter(Map event) { // return event; // } // // protected void filterExtraEvents(Stack<Map<String, Object>> to_stt) { // return; // } // // public void postProcess(Map event, boolean ifSuccess) { // if (ifSuccess == false) { // if (this.tagOnFailure == null || this.tagOnFailure.length() <= 0) { // return; // } // if (!event.containsKey("tags")) { // event.put("tags", new ArrayList<String>(Arrays.asList(this.tagOnFailure))); // } else { // Object tags = event.get("tags"); // if (tags.getClass() == ArrayList.class // && ((ArrayList) tags).indexOf(this.tagOnFailure) == -1) { // ((ArrayList) tags).add(this.tagOnFailure); // } // } // } else { // if (this.removeFields != null) { // for (FieldDeleter f : this.removeFields) { // f.delete(event); // } // } // // if (this.addFields != null) { // Iterator<Map.Entry<FieldSetter, TemplateRender>> it = this.addFields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<FieldSetter, TemplateRender> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // TemplateRender templateRender = entry.getValue(); // fieldSetter.setField(event, templateRender.render(event)); // } // } // } // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/utils/Utils.java import com.ctrip.ops.sysdev.baseplugin.BaseFilter; import lombok.extern.log4j.Log4j2; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; package com.ctrip.ops.sysdev.utils; @SuppressWarnings("ALL") @Log4j2 public class Utils {
public static List<BaseFilter> createFilterProcessors(List<Map> filters) {
childe/hangout
hangout-filters/hangout-filters-uppercase/src/test/java/com/ctrip/ops/sysdev/test/TestUppercaseFilter.java
// Path: hangout-filters/hangout-filters-uppercase/src/main/java/com/ctrip/ops/sysdev/filters/Uppercase.java // @SuppressWarnings("ALL") // @Log4j2 // public class Uppercase extends BaseFilter { // // // public Uppercase(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // try { // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), TemplateRender.getRender(field, false))); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + field); // System.exit(1); // } // } // } // // @Override // protected Map filter(Map event) { // for (Tuple2 t2 : fields) { // Object input = ((TemplateRender) t2._2()).render(event); // if (input != null && String.class.isAssignableFrom(input.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) input).toUpperCase()); // } // } // // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Uppercase; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestUppercaseFilter { @Test public void testUppercaseFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-uppercase/src/main/java/com/ctrip/ops/sysdev/filters/Uppercase.java // @SuppressWarnings("ALL") // @Log4j2 // public class Uppercase extends BaseFilter { // // // public Uppercase(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // try { // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), TemplateRender.getRender(field, false))); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + field); // System.exit(1); // } // } // } // // @Override // protected Map filter(Map event) { // for (Tuple2 t2 : fields) { // Object input = ((TemplateRender) t2._2()).render(event); // if (input != null && String.class.isAssignableFrom(input.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) input).toUpperCase()); // } // } // // return event; // } // } // Path: hangout-filters/hangout-filters-uppercase/src/test/java/com/ctrip/ops/sysdev/test/TestUppercaseFilter.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Uppercase; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestUppercaseFilter { @Test public void testUppercaseFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Uppercase uppercaseFilter = new Uppercase(config);
childe/hangout
hangout-core/src/test/java/com/ctrip/ops/sysdev/fieldSetter/TestFieldSetter.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // }
import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import org.testng.Assert; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map;
package com.ctrip.ops.sysdev.fieldSetter; /** * Created by liujia on 17/2/10. */ public class TestFieldSetter { @Test public void testFieldSetter() {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // Path: hangout-core/src/test/java/com/ctrip/ops/sysdev/fieldSetter/TestFieldSetter.java import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import org.testng.Assert; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; package com.ctrip.ops.sysdev.fieldSetter; /** * Created by liujia on 17/2/10. */ public class TestFieldSetter { @Test public void testFieldSetter() {
FieldSetter fieldSetter = FieldSetter.getFieldSetter("[a][b]");
childe/hangout
hangout-filters/hangout-filters-lowercase/src/test/java/com/ctrip/ops/sysdev/test/TestLowercaseFilter.java
// Path: hangout-filters/hangout-filters-lowercase/src/main/java/com/ctrip/ops/sysdev/filters/Lowercase.java // @SuppressWarnings("ALL") // @Log4j2 // public class Lowercase extends BaseFilter { // // // public Lowercase(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // try { // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), TemplateRender.getRender(field, false))); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + field); // System.exit(1); // } // } // } // // @Override // protected Map filter(Map event) { // for (Tuple2 t2 : fields) { // Object input = ((TemplateRender) t2._2()).render(event); // if (input != null && String.class.isAssignableFrom(input.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) input).toLowerCase()); // } // } // // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Lowercase; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestLowercaseFilter { @Test public void testLowercaseFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-lowercase/src/main/java/com/ctrip/ops/sysdev/filters/Lowercase.java // @SuppressWarnings("ALL") // @Log4j2 // public class Lowercase extends BaseFilter { // // // public Lowercase(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // // protected void prepare() { // this.fields = new ArrayList(); // for (String field : (ArrayList<String>) config.get("fields")) { // try { // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), TemplateRender.getRender(field, false))); // } catch (IOException e) { // log.error("could NOT build TemplateRender from " + field); // System.exit(1); // } // } // } // // @Override // protected Map filter(Map event) { // for (Tuple2 t2 : fields) { // Object input = ((TemplateRender) t2._2()).render(event); // if (input != null && String.class.isAssignableFrom(input.getClass())) { // ((FieldSetter) t2._1()).setField(event, ((String) input).toLowerCase()); // } // } // // return event; // } // } // Path: hangout-filters/hangout-filters-lowercase/src/test/java/com/ctrip/ops/sysdev/test/TestLowercaseFilter.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Lowercase; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestLowercaseFilter { @Test public void testLowercaseFilter() { String c = String.format("%s\n%s\n%s\n%s", "fields:", " - name", " - '[metric][value]'", " - '[metric][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Lowercase lowercaseFilter = new Lowercase(config);
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseOutput extends Base { protected Map config;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseOutput extends Base { protected Map config;
protected List<TemplateRender> IF;
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseOutput extends Base { protected Map config; protected List<TemplateRender> IF; public BaseOutput(Map config) { super(config); this.config = config; if (this.config.containsKey("if")) { IF = new ArrayList<TemplateRender>(); for (String c : (List<String>) this.config.get("if")) { try {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseOutput.java import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseOutput extends Base { protected Map config; protected List<TemplateRender> IF; public BaseOutput(Map config) { super(config); this.config = config; if (this.config.containsKey("if")) { IF = new ArrayList<TemplateRender>(); for (String c : (List<String>) this.config.get("if")) { try {
IF.add(new FreeMarkerRender(c, c));
childe/hangout
hangout-metric-plugins/hangout-metric-watcher/src/main/java/com/ctrip/ops/sysdev/metrics/Watcher.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseMetric.java // public abstract class BaseMetric extends Base { // public BaseMetric(Map config) { // super(config); // } // // public void register() { // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // }
import com.codahale.metrics.health.HealthCheckRegistry; import com.codahale.metrics.servlets.AdminServlet; import com.codahale.metrics.servlets.HealthCheckServlet; import com.codahale.metrics.servlets.MetricsServlet; import com.ctrip.ops.sysdev.baseplugin.BaseMetric; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import lombok.extern.log4j.Log4j2; import javax.servlet.ServletException; import java.util.Map; import com.ctrip.ops.sysdev.metric.Metric;
package com.ctrip.ops.sysdev.metrics; /** * Created by liujia on 17/7/4. */ @Log4j2 public class Watcher extends BaseMetric { private final String host; private final int port; private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); public Watcher(Map config) { super(config); this.host = (String) config.get("host"); this.port = (Integer) config.get("port"); } public void register() { Runnable task = () -> { DeploymentInfo servletBuilder = Servlets.deployment() .setClassLoader(Watcher.class.getClassLoader()) .setContextPath("/") .setDeploymentName("admin.war")
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseMetric.java // public abstract class BaseMetric extends Base { // public BaseMetric(Map config) { // super(config); // } // // public void register() { // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // } // Path: hangout-metric-plugins/hangout-metric-watcher/src/main/java/com/ctrip/ops/sysdev/metrics/Watcher.java import com.codahale.metrics.health.HealthCheckRegistry; import com.codahale.metrics.servlets.AdminServlet; import com.codahale.metrics.servlets.HealthCheckServlet; import com.codahale.metrics.servlets.MetricsServlet; import com.ctrip.ops.sysdev.baseplugin.BaseMetric; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.handlers.PathHandler; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import lombok.extern.log4j.Log4j2; import javax.servlet.ServletException; import java.util.Map; import com.ctrip.ops.sysdev.metric.Metric; package com.ctrip.ops.sysdev.metrics; /** * Created by liujia on 17/7/4. */ @Log4j2 public class Watcher extends BaseMetric { private final String host; private final int port; private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); public Watcher(Map config) { super(config); this.host = (String) config.get("host"); this.port = (Integer) config.get("port"); } public void register() { Runnable task = () -> { DeploymentInfo servletBuilder = Servlets.deployment() .setClassLoader(Watcher.class.getClassLoader()) .setContextPath("/") .setDeploymentName("admin.war")
.addServletContextAttribute(MetricsServlet.METRICS_REGISTRY, Metric.getMetricRegistry())
childe/hangout
hangout-filters/hangout-filters-replace/src/test/java/com/ctrip/ops/sysdev/test/TestReplace.java
// Path: hangout-filters/hangout-filters-replace/src/main/java/com/ctrip/ops/sysdev/filters/Replace.java // @Log4j2 // public class Replace extends BaseFilter { // // public Replace(Map config) { // super(config); // } // // private TemplateRender templateRender; // private TemplateRender srcTemplateRender; // private FieldSetter fieldSetter; // // protected void prepare() { // String src = (String) config.get("src"); // this.fieldSetter = FieldSetter.getFieldSetter(src); // try { // this.srcTemplateRender = TemplateRender.getRender(src, false); // } catch (IOException e) { // log.fatal("could NOT build tempalte render from " + src); // System.exit(1); // } // // String value = (String) config.get("value"); // try { // this.templateRender = TemplateRender.getRender(value); // } catch (IOException e) { // log.fatal("could NOT build tempalte render from " + value); // System.exit(1); // } // } // // @Override // protected Map filter(final Map event) { // if (this.srcTemplateRender.render(event) != null) { // this.fieldSetter.setField(event, this.templateRender.render(event)); // } // return event; // } // }
import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Replace; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestReplace { @Test public void testReplace() { String c = String .format("%s\n%s\n", "src: name", "value: abcd"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-replace/src/main/java/com/ctrip/ops/sysdev/filters/Replace.java // @Log4j2 // public class Replace extends BaseFilter { // // public Replace(Map config) { // super(config); // } // // private TemplateRender templateRender; // private TemplateRender srcTemplateRender; // private FieldSetter fieldSetter; // // protected void prepare() { // String src = (String) config.get("src"); // this.fieldSetter = FieldSetter.getFieldSetter(src); // try { // this.srcTemplateRender = TemplateRender.getRender(src, false); // } catch (IOException e) { // log.fatal("could NOT build tempalte render from " + src); // System.exit(1); // } // // String value = (String) config.get("value"); // try { // this.templateRender = TemplateRender.getRender(value); // } catch (IOException e) { // log.fatal("could NOT build tempalte render from " + value); // System.exit(1); // } // } // // @Override // protected Map filter(final Map event) { // if (this.srcTemplateRender.render(event) != null) { // this.fieldSetter.setField(event, this.templateRender.render(event)); // } // return event; // } // } // Path: hangout-filters/hangout-filters-replace/src/test/java/com/ctrip/ops/sysdev/test/TestReplace.java import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Replace; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestReplace { @Test public void testReplace() { String c = String .format("%s\n%s\n", "src: name", "value: abcd"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Replace filter = new Replace(config);
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/Base.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/exception/YamlConfigException.java // @SuppressWarnings("ALL") // public class YamlConfigException extends Exception { // public YamlConfigException(String msg) { // super("Invalid Config Exception! " + msg); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // }
import com.codahale.metrics.Meter; import com.ctrip.ops.sysdev.exception.YamlConfigException; import com.ctrip.ops.sysdev.metric.Metric; import lombok.NonNull; import java.util.Map;
package com.ctrip.ops.sysdev.baseplugin; /** * Created by gnuhpc on 2017/2/14. */ public class Base { protected boolean enableMeter = false; protected Meter meter; public Base(@NonNull Map config) { if (config.containsKey("meter_name")) { this.enableMeter = true;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/exception/YamlConfigException.java // @SuppressWarnings("ALL") // public class YamlConfigException extends Exception { // public YamlConfigException(String msg) { // super("Invalid Config Exception! " + msg); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/Base.java import com.codahale.metrics.Meter; import com.ctrip.ops.sysdev.exception.YamlConfigException; import com.ctrip.ops.sysdev.metric.Metric; import lombok.NonNull; import java.util.Map; package com.ctrip.ops.sysdev.baseplugin; /** * Created by gnuhpc on 2017/2/14. */ public class Base { protected boolean enableMeter = false; protected Meter meter; public Base(@NonNull Map config) { if (config.containsKey("meter_name")) { this.enableMeter = true;
meter = Metric.setMetric((String) config.get("meter_name"));
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/Base.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/exception/YamlConfigException.java // @SuppressWarnings("ALL") // public class YamlConfigException extends Exception { // public YamlConfigException(String msg) { // super("Invalid Config Exception! " + msg); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // }
import com.codahale.metrics.Meter; import com.ctrip.ops.sysdev.exception.YamlConfigException; import com.ctrip.ops.sysdev.metric.Metric; import lombok.NonNull; import java.util.Map;
package com.ctrip.ops.sysdev.baseplugin; /** * Created by gnuhpc on 2017/2/14. */ public class Base { protected boolean enableMeter = false; protected Meter meter; public Base(@NonNull Map config) { if (config.containsKey("meter_name")) { this.enableMeter = true; meter = Metric.setMetric((String) config.get("meter_name")); } } /** * Get specified config from configurations, default config can also be set, isMust indicates whether this config is a must or not. * * @param config * @param key * @param defaultConfig * @param isMust * @param <T> * @return */
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/exception/YamlConfigException.java // @SuppressWarnings("ALL") // public class YamlConfigException extends Exception { // public YamlConfigException(String msg) { // super("Invalid Config Exception! " + msg); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/metric/Metric.java // public class Metric { // // private static MetricRegistry metricRegistry = new MetricRegistry(); // // public static Meter setMetric(String metricName) { // return metricRegistry.meter(metricName); // } // // public static MetricRegistry getMetricRegistry() // { // return metricRegistry; // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/Base.java import com.codahale.metrics.Meter; import com.ctrip.ops.sysdev.exception.YamlConfigException; import com.ctrip.ops.sysdev.metric.Metric; import lombok.NonNull; import java.util.Map; package com.ctrip.ops.sysdev.baseplugin; /** * Created by gnuhpc on 2017/2/14. */ public class Base { protected boolean enableMeter = false; protected Meter meter; public Base(@NonNull Map config) { if (config.containsKey("meter_name")) { this.enableMeter = true; meter = Metric.setMetric((String) config.get("meter_name")); } } /** * Get specified config from configurations, default config can also be set, isMust indicates whether this config is a must or not. * * @param config * @param key * @param defaultConfig * @param isMust * @param <T> * @return */
public <T> T getConfig(Map config, String key, T defaultConfig, boolean isMust) throws YamlConfigException {
childe/hangout
hangout-filters/hangout-filters-convert/src/test/java/com/ctrip/ops/sysdev/test/TestConvertFilter.java
// Path: hangout-filters/hangout-filters-convert/src/main/java/com/ctrip/ops/sysdev/filters/Convert.java // @Log4j2 // public class Convert extends BaseFilter { // private Map<FieldSetter, Tuple4> f; // // public Convert(Map config) { // super(config); // } // // protected void prepare() { // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "convertfail"; // } // // f = new HashMap(); // Map<String, Map> fields = (Map<String, Map>) config.get("fields"); // Iterator<Entry<String, Map>> it = fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, Map> entry = it.next(); // String field = entry.getKey(); // Map value = entry.getValue(); // ConverterI converter = null; // Boolean remove_if_fail = false; // Object setto_if_fail = null; // if (((String) value.get("to")).equalsIgnoreCase("long")) { // converter = new LongConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("integer")) { // converter = new IntegerConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("double")) { // converter = new DoubleConverter(value); // } else if (((String) value.get("to")).equalsIgnoreCase("float")) { // converter = new FloatConverter(value); // } else if (((String) value.get("to")).equalsIgnoreCase("string")) { // converter = new StringConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("boolean")) { // converter = new BooleanConverter(); // } // // if (value.containsKey("remove_if_fail")) { // remove_if_fail = (Boolean) value.get("remove_if_fail"); // } // // if (value.containsKey("setto_if_fail")) { // setto_if_fail = value.get("setto_if_fail"); // } // // try { // f.put(FieldSetter.getFieldSetter(field), new Tuple4(converter, TemplateRender.getRender(field, false), remove_if_fail, setto_if_fail)); // } catch (Exception e) { // log.error("could not create filed render for '" + field + "'"); // System.exit(1); // } // } // } // // @SuppressWarnings({"unchecked", "rawtypes"}) // @Override // protected Map filter(final Map event) { // Iterator<Entry<FieldSetter, Tuple4>> it = f.entrySet().iterator(); // boolean success = true; // while (it.hasNext()) { // boolean flag = true; // Map.Entry<FieldSetter, Tuple4> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // Tuple4 t4 = entry.getValue(); // Object d = null; // try { // TemplateRender tr = (TemplateRender) t4._2(); // d = ((ConverterI) t4._1()).convert(tr.render(event)); // } catch (Exception e) { // flag = false; // success = false; // } // // if (!flag || d == null) { // if ((Boolean) t4._3()) { // fieldSetter.setField(event, null); // } else { // if (t4._4() != null) { // fieldSetter.setField(event, t4._4()); // } // } // } else { // fieldSetter.setField(event, d); // } // } // // this.postProcess(event, success); // // return event; // } // }
import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Convert; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestConvertFilter { @Test @SuppressWarnings({"rawtypes", "unchecked", "serial"}) public void testConvertFilter() throws UnsupportedEncodingException { String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s", " fields:", " cs_bytes: ", " to: integer", " remove_if_fail: true", " time_taken: ", " to: float", " setto_if_fail: 0.0"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-convert/src/main/java/com/ctrip/ops/sysdev/filters/Convert.java // @Log4j2 // public class Convert extends BaseFilter { // private Map<FieldSetter, Tuple4> f; // // public Convert(Map config) { // super(config); // } // // protected void prepare() { // // if (config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) config.get("tag_on_failure"); // } else { // this.tagOnFailure = "convertfail"; // } // // f = new HashMap(); // Map<String, Map> fields = (Map<String, Map>) config.get("fields"); // Iterator<Entry<String, Map>> it = fields.entrySet().iterator(); // while (it.hasNext()) { // Map.Entry<String, Map> entry = it.next(); // String field = entry.getKey(); // Map value = entry.getValue(); // ConverterI converter = null; // Boolean remove_if_fail = false; // Object setto_if_fail = null; // if (((String) value.get("to")).equalsIgnoreCase("long")) { // converter = new LongConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("integer")) { // converter = new IntegerConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("double")) { // converter = new DoubleConverter(value); // } else if (((String) value.get("to")).equalsIgnoreCase("float")) { // converter = new FloatConverter(value); // } else if (((String) value.get("to")).equalsIgnoreCase("string")) { // converter = new StringConverter(); // } else if (((String) value.get("to")).equalsIgnoreCase("boolean")) { // converter = new BooleanConverter(); // } // // if (value.containsKey("remove_if_fail")) { // remove_if_fail = (Boolean) value.get("remove_if_fail"); // } // // if (value.containsKey("setto_if_fail")) { // setto_if_fail = value.get("setto_if_fail"); // } // // try { // f.put(FieldSetter.getFieldSetter(field), new Tuple4(converter, TemplateRender.getRender(field, false), remove_if_fail, setto_if_fail)); // } catch (Exception e) { // log.error("could not create filed render for '" + field + "'"); // System.exit(1); // } // } // } // // @SuppressWarnings({"unchecked", "rawtypes"}) // @Override // protected Map filter(final Map event) { // Iterator<Entry<FieldSetter, Tuple4>> it = f.entrySet().iterator(); // boolean success = true; // while (it.hasNext()) { // boolean flag = true; // Map.Entry<FieldSetter, Tuple4> entry = it.next(); // FieldSetter fieldSetter = entry.getKey(); // Tuple4 t4 = entry.getValue(); // Object d = null; // try { // TemplateRender tr = (TemplateRender) t4._2(); // d = ((ConverterI) t4._1()).convert(tr.render(event)); // } catch (Exception e) { // flag = false; // success = false; // } // // if (!flag || d == null) { // if ((Boolean) t4._3()) { // fieldSetter.setField(event, null); // } else { // if (t4._4() != null) { // fieldSetter.setField(event, t4._4()); // } // } // } else { // fieldSetter.setField(event, d); // } // } // // this.postProcess(event, success); // // return event; // } // } // Path: hangout-filters/hangout-filters-convert/src/test/java/com/ctrip/ops/sysdev/test/TestConvertFilter.java import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.Convert; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestConvertFilter { @Test @SuppressWarnings({"rawtypes", "unchecked", "serial"}) public void testConvertFilter() throws UnsupportedEncodingException { String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s", " fields:", " cs_bytes: ", " to: integer", " remove_if_fail: true", " time_taken: ", " to: float", " setto_if_fail: 0.0"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Convert convertFilter = new Convert(config);
childe/hangout
hangout-filters/hangout-filters-urldecode/src/test/java/com/ctrip/ops/sysdev/test/TestURLDecode.java
// Path: hangout-filters/hangout-filters-urldecode/src/main/java/com/ctrip/ops/sysdev/filters/URLDecode.java // @Log4j2 // public class URLDecode extends BaseFilter { // // // @SuppressWarnings("rawtypes") // public URLDecode(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // private String enc; // // @SuppressWarnings("unchecked") // protected void prepare() { // this.fields = new ArrayList<>(); // for (String field : (ArrayList<String>) config.get("fields")) { // TemplateRender templateRender = null; // try { // templateRender = TemplateRender.getRender(field, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + field); // System.exit(1); // } // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), templateRender)); // } // // if (config.containsKey("enc")) { // this.enc = (String) config.get("enc"); // } else { // this.enc = "UTF-8"; // } // // if (this.config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) this.config.get("tag_on_failure"); // } else { // this.tagOnFailure = "URLDecodefail"; // } // } // // @Override // protected Map filter(final Map event) { // boolean success = true; // for (Tuple2 f2 : this.fields) { // TemplateRender templateRender = (TemplateRender) f2._2(); // Object value = templateRender.render(event); // if (value != null && String.class.isAssignableFrom(value.getClass())) { // try { // ((FieldSetter) f2._1()).setField(event, URLDecoder.decode((String) value, this.enc)); // } catch (Exception e) { // log.debug("URLDecode failed", e); // success = false; // } // } // } // // this.postProcess(event, success); // // return event; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.URLDecode; import org.apache.commons.collections4.map.HashedMap; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml;
package com.ctrip.ops.sysdev.test; public class TestURLDecode { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testURLDecode() { String c = String.format("%s\n%s\n%s", "fields:", " - query1", " - '[extra][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-urldecode/src/main/java/com/ctrip/ops/sysdev/filters/URLDecode.java // @Log4j2 // public class URLDecode extends BaseFilter { // // // @SuppressWarnings("rawtypes") // public URLDecode(Map config) { // super(config); // } // // private ArrayList<Tuple2> fields; // private String enc; // // @SuppressWarnings("unchecked") // protected void prepare() { // this.fields = new ArrayList<>(); // for (String field : (ArrayList<String>) config.get("fields")) { // TemplateRender templateRender = null; // try { // templateRender = TemplateRender.getRender(field, false); // } catch (IOException e) { // log.fatal("could NOT build template render from " + field); // System.exit(1); // } // this.fields.add(new Tuple2(FieldSetter.getFieldSetter(field), templateRender)); // } // // if (config.containsKey("enc")) { // this.enc = (String) config.get("enc"); // } else { // this.enc = "UTF-8"; // } // // if (this.config.containsKey("tag_on_failure")) { // this.tagOnFailure = (String) this.config.get("tag_on_failure"); // } else { // this.tagOnFailure = "URLDecodefail"; // } // } // // @Override // protected Map filter(final Map event) { // boolean success = true; // for (Tuple2 f2 : this.fields) { // TemplateRender templateRender = (TemplateRender) f2._2(); // Object value = templateRender.render(event); // if (value != null && String.class.isAssignableFrom(value.getClass())) { // try { // ((FieldSetter) f2._1()).setField(event, URLDecoder.decode((String) value, this.enc)); // } catch (Exception e) { // log.debug("URLDecode failed", e); // success = false; // } // } // } // // this.postProcess(event, success); // // return event; // } // } // Path: hangout-filters/hangout-filters-urldecode/src/test/java/com/ctrip/ops/sysdev/test/TestURLDecode.java import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.ctrip.ops.sysdev.filters.URLDecode; import org.apache.commons.collections4.map.HashedMap; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; package com.ctrip.ops.sysdev.test; public class TestURLDecode { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testURLDecode() { String c = String.format("%s\n%s\n%s", "fields:", " - query1", " - '[extra][value2]'" ); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
URLDecode URLDecodefilter = new URLDecode(config);
childe/hangout
hangout-filters/hangout-filters-filters/src/test/java/com/ctrip/ops/sysdev/test/TestFilters.java
// Path: hangout-filters/hangout-filters-filters/src/main/java/com/ctrip/ops/sysdev/filters/Filters.java // @Log4j2 // public class Filters extends BaseFilter { // public Filters(Map config) { // super(config); // } // // protected List<BaseFilter> filterProcessors; // private Map<String, Object> event; // // protected void prepare() { // ArrayList<Map> filters = (ArrayList<Map>) config.get("filters"); // // this.filterProcessors = Utils.createFilterProcessors(filters); // for (BaseFilter filterProcessor : filterProcessors) { // if (filterProcessor.processExtraEventsFunc == true) { // this.processExtraEventsFunc = true; // } // } // } // // @Override // protected Map filter(Map event) { // if (this.processExtraEventsFunc == true) { // //will prcess the event in filterExtraEvents // this.event = event; // return event; // } // if (this.filterProcessors != null) { // for (BaseFilter bf : filterProcessors) { // if (event == null) { // break; // } // event = bf.process(event); // } // } // return event; // } // // @Override // protected void filterExtraEvents(Stack<Map<String, Object>> to_st) { // Stack<Map<String, Object>> from_st = new Stack<Map<String, Object>>(); // from_st.push(event); // // for (BaseFilter bf : filterProcessors) { // while (!from_st.empty()) { // Map rst = bf.process(from_st.pop()); // if (rst != null) { // to_st.push(rst); // } // } // if (bf.processExtraEventsFunc == true) { // bf.processExtraEvents(to_st); // } // } // return; // } // }
import com.ctrip.ops.sysdev.filters.Filters; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; import java.util.HashMap; import java.util.Map;
package com.ctrip.ops.sysdev.test; public class TestFilters { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testFilters() { // General Test String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", "if:", " - '<#if message??>true</#if>'", " - '<#if message?contains(\"liu\")>true<#elseif message?contains(\"warn\")>true</#if>'", "filters:", " - Grok:", " match:", " - '^(?<logtime>\\S+) %{USERNAME:user} (-|%{LOGLEVEL:level}) %{DATA:msg}$'", " remove_fields: ['message']", " - Add:", " fields:", " test: 'abcd'", " - Date:", " src: logtime", " formats:", " - 'ISO8601'", " remove_fields: ['logtime']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
// Path: hangout-filters/hangout-filters-filters/src/main/java/com/ctrip/ops/sysdev/filters/Filters.java // @Log4j2 // public class Filters extends BaseFilter { // public Filters(Map config) { // super(config); // } // // protected List<BaseFilter> filterProcessors; // private Map<String, Object> event; // // protected void prepare() { // ArrayList<Map> filters = (ArrayList<Map>) config.get("filters"); // // this.filterProcessors = Utils.createFilterProcessors(filters); // for (BaseFilter filterProcessor : filterProcessors) { // if (filterProcessor.processExtraEventsFunc == true) { // this.processExtraEventsFunc = true; // } // } // } // // @Override // protected Map filter(Map event) { // if (this.processExtraEventsFunc == true) { // //will prcess the event in filterExtraEvents // this.event = event; // return event; // } // if (this.filterProcessors != null) { // for (BaseFilter bf : filterProcessors) { // if (event == null) { // break; // } // event = bf.process(event); // } // } // return event; // } // // @Override // protected void filterExtraEvents(Stack<Map<String, Object>> to_st) { // Stack<Map<String, Object>> from_st = new Stack<Map<String, Object>>(); // from_st.push(event); // // for (BaseFilter bf : filterProcessors) { // while (!from_st.empty()) { // Map rst = bf.process(from_st.pop()); // if (rst != null) { // to_st.push(rst); // } // } // if (bf.processExtraEventsFunc == true) { // bf.processExtraEvents(to_st); // } // } // return; // } // } // Path: hangout-filters/hangout-filters-filters/src/test/java/com/ctrip/ops/sysdev/test/TestFilters.java import com.ctrip.ops.sysdev.filters.Filters; import org.testng.Assert; import org.testng.annotations.Test; import org.yaml.snakeyaml.Yaml; import java.util.HashMap; import java.util.Map; package com.ctrip.ops.sysdev.test; public class TestFilters { @Test @SuppressWarnings({"rawtypes", "unchecked"}) public void testFilters() { // General Test String c = String.format("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n", "if:", " - '<#if message??>true</#if>'", " - '<#if message?contains(\"liu\")>true<#elseif message?contains(\"warn\")>true</#if>'", "filters:", " - Grok:", " match:", " - '^(?<logtime>\\S+) %{USERNAME:user} (-|%{LOGLEVEL:level}) %{DATA:msg}$'", " remove_fields: ['message']", " - Add:", " fields:", " test: 'abcd'", " - Date:", " src: logtime", " formats:", " - 'ISO8601'", " remove_fields: ['logtime']"); Yaml yaml = new Yaml(); Map config = (Map) yaml.load(c); Assert.assertNotNull(config);
Filters Filtersfilter = new Filters(config);
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // }
import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config;
protected Decode decoder;
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // }
import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config; protected Decode decoder; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseInput(Map config, ArrayList<Map> filters, ArrayList<Map> outputs) throws Exception { super(config); this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); this.config = config; this.createDecoder(); this.prepare(); this.registerShutdownHookForSelf(); } protected abstract void prepare(); public abstract void emit(); protected Map<String, Object> preprocess(Map<String, Object> event) { return event; } protected Map<String, Object> postprocess(Map<String, Object> event) { return event; } // any input plugin should create decoder when init public void createDecoder() { String codec = (String) this.config.get("codec"); if (codec != null && codec.equalsIgnoreCase("plain")) {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config; protected Decode decoder; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseInput(Map config, ArrayList<Map> filters, ArrayList<Map> outputs) throws Exception { super(config); this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); this.config = config; this.createDecoder(); this.prepare(); this.registerShutdownHookForSelf(); } protected abstract void prepare(); public abstract void emit(); protected Map<String, Object> preprocess(Map<String, Object> event) { return event; } protected Map<String, Object> postprocess(Map<String, Object> event) { return event; } // any input plugin should create decoder when init public void createDecoder() { String codec = (String) this.config.get("codec"); if (codec != null && codec.equalsIgnoreCase("plain")) {
decoder = new PlainDecoder();
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // }
import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config; protected Decode decoder; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseInput(Map config, ArrayList<Map> filters, ArrayList<Map> outputs) throws Exception { super(config); this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); this.config = config; this.createDecoder(); this.prepare(); this.registerShutdownHookForSelf(); } protected abstract void prepare(); public abstract void emit(); protected Map<String, Object> preprocess(Map<String, Object> event) { return event; } protected Map<String, Object> postprocess(Map<String, Object> event) { return event; } // any input plugin should create decoder when init public void createDecoder() { String codec = (String) this.config.get("codec"); if (codec != null && codec.equalsIgnoreCase("plain")) { decoder = new PlainDecoder(); } else {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/Decode.java // public interface Decode { // Map<String, Object> decode(String message); // // default Map<String, Object> createDefaultEvent(String message) { // return new HashMap<String, Object>(2) { // { // put("message", message); // put("@timestamp", DateTime.now()); // } // }; // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/JsonDecoder.java // @Log4j2 // public class JsonDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // Map<String, Object> event = null; // try { // event = (HashMap) JSONValue.parseWithException(message); // } catch (Exception e) { // log.warn("failed to json parse message to event", e); // } finally { // if (event == null) { // event = createDefaultEvent(message); // } // return event; // } // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/decoders/PlainDecoder.java // public class PlainDecoder implements Decode { // // public Map<String, Object> decode(final String message) { // return createDefaultEvent(message); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseInput.java import com.ctrip.ops.sysdev.decoders.Decode; import com.ctrip.ops.sysdev.decoders.JsonDecoder; import com.ctrip.ops.sysdev.decoders.PlainDecoder; import lombok.extern.log4j.Log4j2; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public abstract class BaseInput extends Base { protected Map<String, Object> config; protected Decode decoder; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseInput(Map config, ArrayList<Map> filters, ArrayList<Map> outputs) throws Exception { super(config); this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); this.config = config; this.createDecoder(); this.prepare(); this.registerShutdownHookForSelf(); } protected abstract void prepare(); public abstract void emit(); protected Map<String, Object> preprocess(Map<String, Object> event) { return event; } protected Map<String, Object> postprocess(Map<String, Object> event) { return event; } // any input plugin should create decoder when init public void createDecoder() { String codec = (String) this.config.get("codec"); if (codec != null && codec.equalsIgnoreCase("plain")) { decoder = new PlainDecoder(); } else {
decoder = new JsonDecoder();
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure;
protected List<FieldDeleter> removeFields;
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields;
protected Map<FieldSetter, TemplateRender> addFields;
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields;
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields;
protected Map<FieldSetter, TemplateRender> addFields;
childe/hangout
hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // }
import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*;
package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields; protected Map<FieldSetter, TemplateRender> addFields; private List<TemplateRender> IF; public boolean processExtraEventsFunc; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseFilter(Map config) { super(config); this.config = config; this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); final List<String> ifConditions = (List<String>) this.config.get("if"); if (ifConditions != null) { IF = new ArrayList<TemplateRender>(ifConditions.size()); for (String c : ifConditions) { try {
// Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldDeleter/FieldDeleter.java // public interface FieldDeleter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Map delete(Map event); // // public static FieldDeleter getFieldDeleter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelDeleter(field); // } // return new OneLevelDeleter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/fieldSetter/FieldSetter.java // public interface FieldSetter { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public void setField(Map event, String field, Object value); // // public void setField(Map event, Object value); // // public static FieldSetter getFieldSetter(String field) { // if (p.matcher(field).matches()) { // return new MultiLevelSetter(field); // } // return new OneLevelSetter(field); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/FreeMarkerRender.java // @Log4j2 // public class FreeMarkerRender implements TemplateRender { // private Template t; // // public FreeMarkerRender(String template, String templateName) // throws IOException { // Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); // this.t = new Template(templateName, template, cfg); // } // // public Object render(Map event) { // StringWriter sw = new StringWriter(); // try { // t.process(event, sw); // } catch (Exception e) { // log.error(e.getMessage()); // log.debug(event); // return null; // } // try { // sw.close(); // } catch (IOException e) { // log.error(e.getMessage(),e); // } // return sw.toString(); // } // } // // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/render/TemplateRender.java // public interface TemplateRender { // Pattern p = Pattern.compile("\\[\\S+\\]+"); // // public Object render(Map event); // // static public TemplateRender getRender(Object template) throws IOException { // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher((String) template).matches()) { // return new FieldRender((String) template); // } // // return new FreeMarkerRender((String) template, (String) template); // // } // // // static public TemplateRender getRender(String template, boolean ignoreOneLevelRender) throws IOException { // if (ignoreOneLevelRender == true) { // return getRender(template); // } // // if (!String.class.isAssignableFrom(template.getClass())) { // return new DirectRender(template); // } // if (p.matcher(template).matches()) { // return new FieldRender(template); // } // if (template.contains("$")) { // return new FreeMarkerRender(template, template); // } // return new OneLevelRender(template); // } // // // static public TemplateRender getRender(String template, String timezone) throws IOException { // Pattern p = Pattern.compile("\\%\\{\\+.*?\\}"); // if (p.matcher(template).find()) { // return new DateFormatter(template, timezone); // } // return getRender(template); // } // } // Path: hangout-core/src/main/java/com/ctrip/ops/sysdev/baseplugin/BaseFilter.java import com.ctrip.ops.sysdev.fieldDeleter.FieldDeleter; import com.ctrip.ops.sysdev.fieldSetter.FieldSetter; import com.ctrip.ops.sysdev.render.FreeMarkerRender; import com.ctrip.ops.sysdev.render.TemplateRender; import lombok.extern.log4j.Log4j2; import java.io.IOException; import java.util.*; package com.ctrip.ops.sysdev.baseplugin; @Log4j2 public class BaseFilter extends Base { protected Map config; protected String tagOnFailure; protected List<FieldDeleter> removeFields; protected Map<FieldSetter, TemplateRender> addFields; private List<TemplateRender> IF; public boolean processExtraEventsFunc; public BaseFilter nextFilter; public List<BaseOutput> outputs; public BaseFilter(Map config) { super(config); this.config = config; this.nextFilter = null; this.outputs = new ArrayList<BaseOutput>(); final List<String> ifConditions = (List<String>) this.config.get("if"); if (ifConditions != null) { IF = new ArrayList<TemplateRender>(ifConditions.size()); for (String c : ifConditions) { try {
IF.add(new FreeMarkerRender(c, c));