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 |
|---|---|---|---|---|---|---|
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/emt/EMT.java | // Path: src/main/java/mods/belgabor/amtweaker/mods/emt/handlers/Fuel.java
// @ZenClass("mods.emt.Fuel")
// public class Fuel {
// // Adding a new barrel brewing recipe
// @ZenMethod
// public static void add(ILiquidStack fuel, int amount) {
// Fluid cfuel = toFluid(fuel).getFluid();
// if (cfuel == null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Fuel may be null!");
// return;
// }
// if (findFuel(cfuel) != null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Fuel " + cfuel.toString() + " already registered");
// return;
// }
// MineTweakerAPI.apply(new FuelAdd(cfuel, amount));
// }
//
// private static IFuelFluid findFuel(Fluid fuel) {
// for(IFuelFluid f : RecipeManagerEMT.fuelRegister.getRecipes()) {
// if (fuel.getName().equals(f.getInput().getName()))
// return f;
// }
// return null;
// }
//
// private static class FuelAdd implements IUndoableAction {
// private final Fluid fuel;
// private final int amount;
// private Boolean applied;
//
// public FuelAdd(Fluid fuel, int amount) {
// this.fuel = fuel;
// this.amount = amount;
// this.applied = false;
// }
//
// @Override
// public void apply() {
// if (!applied) {
// RecipeManagerEMT.fuelRegister.addFuel(fuel, amount);
// applied = true;
// }
// }
//
// @Override
// public boolean canUndo() {
// return true;
// }
//
// @Override
// public void undo() {
// if (applied) {
// IFuelFluid f = findFuel(fuel);
// if (f == null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Entry unexpectedly not found!");
// } else {
// RecipeManagerEMT.fuelRegister.getRecipes().remove(f);
// applied = false;
// }
// }
// }
//
// @Override
// public String describe() {
// return String.format("Registering fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public String describeUndo() {
// return String.format("Removing registered fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public Object getOverrideKey() {
// return null;
// }
// }
//
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// // Removing a clay pan recipe
// @ZenMethod
// public static void remove(ILiquidStack fuel) {
// Fluid cfuel = toFluid(fuel).getFluid();
// if (cfuel == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Input may not be null!");
// return;
// }
// if (findFuel(cfuel) == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Fuel " + cfuel.toString() + " isn't registered");
// return;
// }
// MineTweakerAPI.apply(new FuelRemove(cfuel));
// }
//
// //Removes a recipe, apply is never the same for anything, so will always need to override it
// private static class FuelRemove implements IUndoableAction {
// private Integer amount = null;
// private final Fluid fuel;
// private Boolean applied = false;
//
// public FuelRemove(Fluid fuel) {
// this.fuel = fuel;
// }
//
// @Override
// public void apply() {
// if (!applied) {
// IFuelFluid f = findFuel(fuel);
// if (f == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Couldn't apply removal (fuel unexpectedly not found)");
// return;
// }
// amount = f.getGenerateAmount();
// RecipeManagerEMT.fuelRegister.getRecipes().remove(f);
// applied = true;
// }
// }
//
// @Override
// public boolean canUndo() {
// return true;
// }
//
// @Override
// public void undo() {
// if (applied) {
// RecipeManagerEMT.fuelRegister.addFuel(fuel, amount);
// applied = false;
// }
// }
//
// @Override
// public String describeUndo() {
// return String.format("Restoring fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public String describe() {
// return String.format("Removing registered fluid fuel %s", fuel.getName());
// }
//
// @Override
// public Object getOverrideKey() {
// return null;
// }
//
// }
//
// }
| import minetweaker.MineTweakerAPI;
import mods.belgabor.amtweaker.mods.emt.handlers.Fuel; | package mods.belgabor.amtweaker.mods.emt;
/**
* Created by Belgabor on 25.05.2016.
*/
public class EMT {
public static final String MODID = "DCsEcoMT";
public EMT() { | // Path: src/main/java/mods/belgabor/amtweaker/mods/emt/handlers/Fuel.java
// @ZenClass("mods.emt.Fuel")
// public class Fuel {
// // Adding a new barrel brewing recipe
// @ZenMethod
// public static void add(ILiquidStack fuel, int amount) {
// Fluid cfuel = toFluid(fuel).getFluid();
// if (cfuel == null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Fuel may be null!");
// return;
// }
// if (findFuel(cfuel) != null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Fuel " + cfuel.toString() + " already registered");
// return;
// }
// MineTweakerAPI.apply(new FuelAdd(cfuel, amount));
// }
//
// private static IFuelFluid findFuel(Fluid fuel) {
// for(IFuelFluid f : RecipeManagerEMT.fuelRegister.getRecipes()) {
// if (fuel.getName().equals(f.getInput().getName()))
// return f;
// }
// return null;
// }
//
// private static class FuelAdd implements IUndoableAction {
// private final Fluid fuel;
// private final int amount;
// private Boolean applied;
//
// public FuelAdd(Fluid fuel, int amount) {
// this.fuel = fuel;
// this.amount = amount;
// this.applied = false;
// }
//
// @Override
// public void apply() {
// if (!applied) {
// RecipeManagerEMT.fuelRegister.addFuel(fuel, amount);
// applied = true;
// }
// }
//
// @Override
// public boolean canUndo() {
// return true;
// }
//
// @Override
// public void undo() {
// if (applied) {
// IFuelFluid f = findFuel(fuel);
// if (f == null) {
// MineTweakerAPI.getLogger().logError("Fluid Fuel: Entry unexpectedly not found!");
// } else {
// RecipeManagerEMT.fuelRegister.getRecipes().remove(f);
// applied = false;
// }
// }
// }
//
// @Override
// public String describe() {
// return String.format("Registering fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public String describeUndo() {
// return String.format("Removing registered fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public Object getOverrideKey() {
// return null;
// }
// }
//
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// // Removing a clay pan recipe
// @ZenMethod
// public static void remove(ILiquidStack fuel) {
// Fluid cfuel = toFluid(fuel).getFluid();
// if (cfuel == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Input may not be null!");
// return;
// }
// if (findFuel(cfuel) == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Fuel " + cfuel.toString() + " isn't registered");
// return;
// }
// MineTweakerAPI.apply(new FuelRemove(cfuel));
// }
//
// //Removes a recipe, apply is never the same for anything, so will always need to override it
// private static class FuelRemove implements IUndoableAction {
// private Integer amount = null;
// private final Fluid fuel;
// private Boolean applied = false;
//
// public FuelRemove(Fluid fuel) {
// this.fuel = fuel;
// }
//
// @Override
// public void apply() {
// if (!applied) {
// IFuelFluid f = findFuel(fuel);
// if (f == null) {
// MineTweakerAPI.getLogger().logError("Fluid fuel removal: Couldn't apply removal (fuel unexpectedly not found)");
// return;
// }
// amount = f.getGenerateAmount();
// RecipeManagerEMT.fuelRegister.getRecipes().remove(f);
// applied = true;
// }
// }
//
// @Override
// public boolean canUndo() {
// return true;
// }
//
// @Override
// public void undo() {
// if (applied) {
// RecipeManagerEMT.fuelRegister.addFuel(fuel, amount);
// applied = false;
// }
// }
//
// @Override
// public String describeUndo() {
// return String.format("Restoring fluid fuel %s, amount %d", fuel.getName(), amount);
// }
//
// @Override
// public String describe() {
// return String.format("Removing registered fluid fuel %s", fuel.getName());
// }
//
// @Override
// public Object getOverrideKey() {
// return null;
// }
//
// }
//
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/emt/EMT.java
import minetweaker.MineTweakerAPI;
import mods.belgabor.amtweaker.mods.emt.handlers.Fuel;
package mods.belgabor.amtweaker.mods.emt;
/**
* Created by Belgabor on 25.05.2016.
*/
public class EMT {
public static final String MODID = "DCsEcoMT";
public EMT() { | MineTweakerAPI.registerClass(Fuel.class); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/vanilla/loggers/VanillaCommandLoggerItem.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import minetweaker.api.player.IPlayer;
import minetweaker.api.server.ICommandFunction;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.*;
import java.util.Set;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.vanilla.loggers;
/**
* Created by Belgabor on 03.06.2016.
*/
public class VanillaCommandLoggerItem extends CommandLoggerBase implements ICommandFunction {
public static void register() {
MineTweakerAPI.server.addMineTweakerCommand("handextra", new String[] {
"/minetweaker handextra",
" dump extra information about the held item"
}, new VanillaCommandLoggerItem());
}
@Override
public void execute(String[] arguments, IPlayer player) {
IItemStack item = player.getCurrentItem();
if (item != null) { | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/vanilla/loggers/VanillaCommandLoggerItem.java
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import minetweaker.api.player.IPlayer;
import minetweaker.api.server.ICommandFunction;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.*;
import java.util.Set;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.vanilla.loggers;
/**
* Created by Belgabor on 03.06.2016.
*/
public class VanillaCommandLoggerItem extends CommandLoggerBase implements ICommandFunction {
public static void register() {
MineTweakerAPI.server.addMineTweakerCommand("handextra", new String[] {
"/minetweaker handextra",
" dump extra information about the held item"
}, new VanillaCommandLoggerItem());
}
@Override
public void execute(String[] arguments, IPlayer player) {
IItemStack item = player.getCurrentItem();
if (item != null) { | ItemStack itemStack = toStack(item); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/emt/handlers/Fuel.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
| import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import defeatedcrow.addonforamt.economy.api.RecipeManagerEMT;
import defeatedcrow.addonforamt.economy.api.energy.IFuelFluid;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.liquid.ILiquidStack;
import net.minecraftforge.fluids.Fluid; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.emt.handlers;
/**
* Created by Belgabor on 13.05.2015.
*/
@ZenClass("mods.emt.Fuel")
public class Fuel {
// Adding a new barrel brewing recipe
@ZenMethod
public static void add(ILiquidStack fuel, int amount) { | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/emt/handlers/Fuel.java
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import defeatedcrow.addonforamt.economy.api.RecipeManagerEMT;
import defeatedcrow.addonforamt.economy.api.energy.IFuelFluid;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.liquid.ILiquidStack;
import net.minecraftforge.fluids.Fluid;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.emt.handlers;
/**
* Created by Belgabor on 13.05.2015.
*/
@ZenClass("mods.emt.Fuel")
public class Fuel {
// Adding a new barrel brewing recipe
@ZenMethod
public static void add(ILiquidStack fuel, int amount) { | Fluid cfuel = toFluid(fuel).getFluid(); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/FluidRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import minetweaker.api.liquid.ILiquidStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import shift.sextiarysector.api.recipe.IFluidRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 04.06.2016.
*/
public class FluidRecipe {
protected static void doAdd(IFluidRecipe handler, String name, ILiquidStack outputLiquid, IItemStack output, IIngredient input) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Input item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on input item (%s), the recipe will only require one.", name, input.toString()));
} | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/FluidRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import minetweaker.api.liquid.ILiquidStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import shift.sextiarysector.api.recipe.IFluidRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 04.06.2016.
*/
public class FluidRecipe {
protected static void doAdd(IFluidRecipe handler, String name, ILiquidStack outputLiquid, IItemStack output, IIngredient input) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Input item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on input item (%s), the recipe will only require one.", name, input.toString()));
} | Object iInput = toObject(input, true); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/FluidRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import minetweaker.api.liquid.ILiquidStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import shift.sextiarysector.api.recipe.IFluidRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (input instanceof String) {
handler.getOreList().remove(input);
applied = false;
} else if (input instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) input);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/FluidRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import minetweaker.api.liquid.ILiquidStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import shift.sextiarysector.api.recipe.IFluidRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (input instanceof String) {
handler.getOreList().remove(input);
applied = false;
} else if (input instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) input);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | return String.format("%s: Adding recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output)); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/BambooBasket.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import mods.defeatedcrow.plugin.LoadBambooPlugin;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.ZenClass; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.amt.handlers;
/**
* Created by Belgabor on 17.02.2015.
*/
@ZenClass("mods.amt.BambooBasket")
public class BambooBasket {
@ZenMethod
public static void add(IItemStack item) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Bamboo basket: Item must not be null!");
return;
}
MineTweakerAPI.apply(new BambooBasketSetAction(item));
}
private static class BambooBasketSetAction implements IUndoableAction {
private final ItemStack item;
public BambooBasketSetAction(IItemStack item) { | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/BambooBasket.java
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import mods.defeatedcrow.plugin.LoadBambooPlugin;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.ZenClass;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.amt.handlers;
/**
* Created by Belgabor on 17.02.2015.
*/
@ZenClass("mods.amt.BambooBasket")
public class BambooBasket {
@ZenMethod
public static void add(IItemStack item) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Bamboo basket: Item must not be null!");
return;
}
MineTweakerAPI.apply(new BambooBasketSetAction(item));
}
private static class BambooBasketSetAction implements IUndoableAction {
private final ItemStack item;
public BambooBasketSetAction(IItemStack item) { | this.item = toStack(item); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/Durability.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.Durability")
public class Durability {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, int durability) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Durability: Item must not be null!");
return;
} | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/Durability.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.Durability")
public class Durability {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, int durability) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Durability: Item must not be null!");
return;
} | Item test = toStack(item).getItem(); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Barrel.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
| import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.liquid.ILiquidStack;
import mods.defeatedcrow.recipe.BrewingRecipe;
import net.minecraftforge.fluids.Fluid;
import stanhebben.zenscript.annotations.ZenClass; | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.amt.handlers;
/**
* Created by Belgabor on 13.05.2015.
*/
@ZenClass("mods.amt.Barrel")
public class Barrel {
// Adding a new barrel brewing recipe
@ZenMethod
public static void addRecipe(ILiquidStack output, ILiquidStack input) {
if ((output == null) || (input == null)) {
MineTweakerAPI.getLogger().logError("Barrel Recipe: Neither input nor output may be null!");
return;
} | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static FluidStack toFluid(ILiquidStack iStack) {
// if (iStack == null) {
// return null;
// } else return FluidRegistry.getFluidStack(iStack.getName(), iStack.getAmount());
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/amt/handlers/Barrel.java
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toFluid;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.liquid.ILiquidStack;
import mods.defeatedcrow.recipe.BrewingRecipe;
import net.minecraftforge.fluids.Fluid;
import stanhebben.zenscript.annotations.ZenClass;
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Belgabor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package mods.belgabor.amtweaker.mods.amt.handlers;
/**
* Created by Belgabor on 13.05.2015.
*/
@ZenClass("mods.amt.Barrel")
public class Barrel {
// Adding a new barrel brewing recipe
@ZenMethod
public static void addRecipe(ILiquidStack output, ILiquidStack input) {
if ((output == null) || (input == null)) {
MineTweakerAPI.getLogger().logError("Barrel Recipe: Neither input nor output may be null!");
return;
} | Fluid cinput = toFluid(input).getFluid(); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/amt/util/BlockAddition.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import mods.defeatedcrow.api.recipe.ICookingHeatSource;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.List;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.amt.util;
public abstract class BlockAddition implements IUndoableAction {
protected final String description;
protected final Block block;
protected final int meta;
protected final ItemStack item;
protected final List<? extends ICookingHeatSource> list;
public BlockAddition(String description, List<? extends ICookingHeatSource> list, IItemStack stack) {
this.description = description; | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/amt/util/BlockAddition.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import mods.defeatedcrow.api.recipe.ICookingHeatSource;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.List;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.amt.util;
public abstract class BlockAddition implements IUndoableAction {
protected final String description;
protected final Block block;
protected final int meta;
protected final ItemStack item;
protected final List<? extends ICookingHeatSource> list;
public BlockAddition(String description, List<? extends ICookingHeatSource> list, IItemStack stack) {
this.description = description; | this.item = toStack(stack); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/mce/util/MCEAccessHelper.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
| import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import shift.mceconomy2.ShopManager;
import shift.mceconomy2.api.MCEconomyAPI;
import shift.mceconomy2.api.purchase.IPurchaseItem;
import shift.mceconomy2.api.purchase.PurchaseItemStack;
import shift.mceconomy2.api.purchase.PurchaseOreDictionary;
import shift.mceconomy2.api.shop.IProduct;
import shift.mceconomy2.api.shop.IShop;
import shift.mceconomy2.api.shop.ShopAdapter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; |
public static int getPurchaseOreDictionary_oreId(PurchaseOreDictionary item) {
try {
return (int) PurchaseOreDictionary_oreId.get(item);
} catch (IllegalAccessException | ClassCastException e) {
return -999;
}
}
public static int getPurchaseOreDictionary_price(PurchaseOreDictionary item) {
try {
return (int) PurchaseOreDictionary_price.get(item);
} catch (IllegalAccessException | ClassCastException e) {
return -999;
}
}
private static IPurchaseItem findPurchaseItemOre(int oreId) {
for(IPurchaseItem theItem: purchaseItems) {
if (theItem instanceof PurchaseOreDictionary) {
if (oreId == getPurchaseOreDictionary_oreId((PurchaseOreDictionary) theItem))
return theItem;
}
}
return null;
}
private static IPurchaseItem findPurchaseItemItem(ItemStack item) {
for(IPurchaseItem theItem: purchaseItems) {
if (theItem instanceof PurchaseItemStack) { | // Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/mce/util/MCEAccessHelper.java
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import shift.mceconomy2.ShopManager;
import shift.mceconomy2.api.MCEconomyAPI;
import shift.mceconomy2.api.purchase.IPurchaseItem;
import shift.mceconomy2.api.purchase.PurchaseItemStack;
import shift.mceconomy2.api.purchase.PurchaseOreDictionary;
import shift.mceconomy2.api.shop.IProduct;
import shift.mceconomy2.api.shop.IShop;
import shift.mceconomy2.api.shop.ShopAdapter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
public static int getPurchaseOreDictionary_oreId(PurchaseOreDictionary item) {
try {
return (int) PurchaseOreDictionary_oreId.get(item);
} catch (IllegalAccessException | ClassCastException e) {
return -999;
}
}
public static int getPurchaseOreDictionary_price(PurchaseOreDictionary item) {
try {
return (int) PurchaseOreDictionary_price.get(item);
} catch (IllegalAccessException | ClassCastException e) {
return -999;
}
}
private static IPurchaseItem findPurchaseItemOre(int oreId) {
for(IPurchaseItem theItem: purchaseItems) {
if (theItem instanceof PurchaseOreDictionary) {
if (oreId == getPurchaseOreDictionary_oreId((PurchaseOreDictionary) theItem))
return theItem;
}
}
return null;
}
private static IPurchaseItem findPurchaseItemItem(ItemStack item) {
for(IPurchaseItem theItem: purchaseItems) {
if (theItem instanceof PurchaseItemStack) { | if (areEqual(item, getPurchaseItemStack_itemStack((PurchaseItemStack) theItem))) |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/Fuel.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.SSRecipes;
import shift.sextiarysector.recipe.RecipeSimpleFuel;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject; | package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 06.06.2016.
*/
@ZenClass("mods.ss2.Fuel")
public class Fuel {
@ZenMethod
public static void addMagic(IIngredient fuel, int amount) {
doAdd(SSRecipes.magicFuel, "Magic Fuel", fuel, amount);
}
@ZenMethod
public static void removeMagic(IIngredient fuel) {
doRemove(SSRecipes.magicFuel, "Magic Fuel", fuel);
}
@ZenMethod
public static void addIce(IIngredient fuel, int amount) {
doAdd(SSRecipes.iceFuel, "Ice Fuel", fuel, amount);
}
@ZenMethod
public static void removeIce(IIngredient fuel) {
doRemove(SSRecipes.iceFuel, "Ice Fuel", fuel);
}
protected static void doAdd(RecipeSimpleFuel handler, String name, IIngredient input, int amount) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Fuel item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on fuel item (%s), the recipe will only require one.", name, input.toString()));
} | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/Fuel.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.SSRecipes;
import shift.sextiarysector.recipe.RecipeSimpleFuel;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 06.06.2016.
*/
@ZenClass("mods.ss2.Fuel")
public class Fuel {
@ZenMethod
public static void addMagic(IIngredient fuel, int amount) {
doAdd(SSRecipes.magicFuel, "Magic Fuel", fuel, amount);
}
@ZenMethod
public static void removeMagic(IIngredient fuel) {
doRemove(SSRecipes.magicFuel, "Magic Fuel", fuel);
}
@ZenMethod
public static void addIce(IIngredient fuel, int amount) {
doAdd(SSRecipes.iceFuel, "Ice Fuel", fuel, amount);
}
@ZenMethod
public static void removeIce(IIngredient fuel) {
doRemove(SSRecipes.iceFuel, "Ice Fuel", fuel);
}
protected static void doAdd(RecipeSimpleFuel handler, String name, IIngredient input, int amount) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Fuel item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on fuel item (%s), the recipe will only require one.", name, input.toString()));
} | Object iInput = toObject(input, true); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/Fuel.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.SSRecipes;
import shift.sextiarysector.recipe.RecipeSimpleFuel;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject; | applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (fuel instanceof String) {
handler.getOreList().remove(fuel);
applied = false;
} else if (fuel instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) fuel);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/Fuel.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.SSRecipes;
import shift.sextiarysector.recipe.RecipeSimpleFuel;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (fuel instanceof String) {
handler.getOreList().remove(fuel);
applied = false;
} else if (fuel instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) fuel);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | return String.format("%s: Adding %s (%d)", name, CommandLoggerBase.getObjectDeclaration(fuel), amount); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/HarvestLevel.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static boolean isABlock(IItemStack block) {
// if (!(isABlock(toStack(block)))) {
// MineTweakerAPI.getLogger().logError("Item must be a block");
// return false;
// } else return true;
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.isABlock;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.HarvestLevel")
public class HarvestLevel {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, String tool, int level) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Harvest level: Block/Item must not be null!");
return;
} | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static boolean isABlock(IItemStack block) {
// if (!(isABlock(toStack(block)))) {
// MineTweakerAPI.getLogger().logError("Item must be a block");
// return false;
// } else return true;
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/HarvestLevel.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.isABlock;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.HarvestLevel")
public class HarvestLevel {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, String tool, int level) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Harvest level: Block/Item must not be null!");
return;
} | if (isABlock(toStack(item))) { |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/HarvestLevel.java | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static boolean isABlock(IItemStack block) {
// if (!(isABlock(toStack(block)))) {
// MineTweakerAPI.getLogger().logError("Item must be a block");
// return false;
// } else return true;
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.isABlock;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack; | package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.HarvestLevel")
public class HarvestLevel {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, String tool, int level) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Harvest level: Block/Item must not be null!");
return;
} | // Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static boolean isABlock(IItemStack block) {
// if (!(isABlock(toStack(block)))) {
// MineTweakerAPI.getLogger().logError("Item must be a block");
// return false;
// } else return true;
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/vanilla/handlers/HarvestLevel.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IItemStack;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import static mods.belgabor.amtweaker.helpers.InputHelper.isABlock;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
package mods.belgabor.amtweaker.mods.vanilla.handlers;
/**
* Created by Belgabor on 03.06.2016.
*/
@ZenClass("mods.vanilla.HarvestLevel")
public class HarvestLevel {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Change harvest level
@ZenMethod
public static void set(IItemStack item, String tool, int level) {
if (item == null) {
MineTweakerAPI.getLogger().logError("Harvest level: Block/Item must not be null!");
return;
} | if (isABlock(toStack(item))) { |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; | package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 04.06.2016.
*/
public class NormalRecipe {
protected static void doAdd(INormalRecipe handler, String name, IItemStack output, IIngredient input) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Input item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on input item (%s), the recipe will only require one.", name, input.toString()));
} | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
package mods.belgabor.amtweaker.mods.ss2.handlers;
/**
* Created by Belgabor on 04.06.2016.
*/
public class NormalRecipe {
protected static void doAdd(INormalRecipe handler, String name, IItemStack output, IIngredient input) {
if (input == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Input item must not be null!", name));
return;
}
if (input.getAmount() > 1) {
MineTweakerAPI.getLogger().logWarning(String.format("%s: Sextiary Sector does not support more than on input item (%s), the recipe will only require one.", name, input.toString()));
} | Object iInput = toObject(input, true); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; | return;
}
}
if (output == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Output item must not be null!", name));
return;
}
MineTweakerAPI.apply(new NormalRecipeAdd(handler, name, output, iInput));
}
private static ItemStack getActualItemStack(INormalRecipe handler, ItemStack item) {
for (ItemStack sItem : handler.getMetaList().keySet()) {
if (ItemStack.areItemStacksEqual(item, sItem))
return sItem;
}
return null;
}
private static class NormalRecipeAdd implements IUndoableAction {
private final INormalRecipe handler;
private final String name;
private final Object input;
private final ItemStack output;
private boolean applied = false;
public NormalRecipeAdd(INormalRecipe handler, String name, IItemStack output, Object input) {
this.handler = handler;
this.name = name;
this.input = input; | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
return;
}
}
if (output == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Output item must not be null!", name));
return;
}
MineTweakerAPI.apply(new NormalRecipeAdd(handler, name, output, iInput));
}
private static ItemStack getActualItemStack(INormalRecipe handler, ItemStack item) {
for (ItemStack sItem : handler.getMetaList().keySet()) {
if (ItemStack.areItemStacksEqual(item, sItem))
return sItem;
}
return null;
}
private static class NormalRecipeAdd implements IUndoableAction {
private final INormalRecipe handler;
private final String name;
private final Object input;
private final ItemStack output;
private boolean applied = false;
public NormalRecipeAdd(INormalRecipe handler, String name, IItemStack output, Object input) {
this.handler = handler;
this.name = name;
this.input = input; | this.output = toStack(output); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; | applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (input instanceof String) {
handler.getOreList().remove(input);
applied = false;
} else if (input instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) input);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
applied = true;
}
}
}
@Override
public boolean canUndo() {
return true;
}
@Override
public void undo() {
if (applied) {
if (input instanceof String) {
handler.getOreList().remove(input);
applied = false;
} else if (input instanceof ItemStack){
ItemStack temp = getActualItemStack(handler, (ItemStack) input);
if (temp == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Unexpectedly could not find recipe when undoing change!", name));
return;
}
handler.getMetaList().remove(temp);
applied = false;
}
}
}
@Override
public String describe() { | return String.format("%s: Adding recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output)); |
Belgabor/AMTweaker | src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
| import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual; | applied = false;
}
}
}
@Override
public String describe() {
return String.format("%s: Adding recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output));
}
@Override
public String describeUndo() {
return String.format("%s: Removing recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output));
}
@Override
public Object getOverrideKey() {
return null;
}
}
protected static void doRemove(INormalRecipe handler, String name, IItemStack output, IIngredient input) {
if (output == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Output item must not be null!", name));
return;
}
Object iInput = null;
if (input == null) {
boolean found = false;
for(ItemStack test : handler.getOreList().values()) { | // Path: src/main/java/mods/belgabor/amtweaker/util/CommandLoggerBase.java
// public class CommandLoggerBase {
// private static String deduceOre(ArrayList stack) {
// int count = 1;
// ArrayList<Integer> oreRefBase = new ArrayList<>();
// for (Object xItem : stack) {
// if (!(xItem instanceof ItemStack))
// return "?????";
// ItemStack item = (ItemStack) xItem;
// count = item.stackSize;
// int[] oreIds = OreDictionary.getOreIDs(item);
// ArrayList<Integer> oreRef = new ArrayList<>();
// for (int i : oreIds)
// oreRef.add(i);
// if (oreIds.length == 0) {
// return "?????";
// } else if (oreIds.length == 1) {
// return getObjectDeclaration(OreDictionary.getOreName(oreIds[0])) + ((count>1)?String.format(" * %d", count):"");
// } else {
// if (oreRefBase.size() == 0) {
// oreRefBase = oreRef;
// } else {
// ArrayList<Integer> toRemove = new ArrayList<>();
// for (Integer i : oreRefBase) {
// if (!oreRef.contains(i))
// toRemove.add(i);
// }
// oreRefBase.removeAll(toRemove);
// if (oreRefBase.size() == 1)
// return getObjectDeclaration(OreDictionary.getOreName(oreRefBase.get(0))) + ((count>1)?String.format(" * %d", count):"");
// }
// }
// }
//
// // Damn
// ArrayList<String> theOres = oreRefBase.stream().map(OreDictionary::getOreName).collect(Collectors.toCollection(ArrayList::new));
// return getObjectDeclaration("UNKNOWN[" + Joiner.on(",").join(theOres) + "]") + ((count>1)?String.format(" * %d", count):"");
// }
//
// protected void logBoth(IPlayer player, String s) {
// MineTweakerAPI.logCommand(s);
// if (player != null)
// player.sendChat(s);
// }
//
// protected static String getItemDeclaration(ItemStack stack) {
// if (stack == null) {
// return "null";
// }
// return MineTweakerMC.getIItemStack(stack).toString();
// }
// protected static String getItemDeclaration(Fluid stack) {
// return "<liquid:" + stack.getName() + ">";
// }
// protected static String getItemDeclaration(FluidStack stack) {
// return "<liquid:" + stack.getFluid().getName() + "> * " + stack.amount;
// }
// public static String getObjectDeclaration(Object stack) {
// if (stack instanceof String) {
// return "<ore:" + stack + ">";
// } else if (stack instanceof ItemStack) {
// return getItemDeclaration((ItemStack) stack);
// } else if (stack instanceof Item) {
// return getItemDeclaration(new ItemStack((Item) stack, 1));
// } else if (stack instanceof Block) {
// return getItemDeclaration(new ItemStack((Block) stack, 1));
// } else if (stack instanceof Fluid) {
// return getItemDeclaration((Fluid) stack);
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack instanceof ArrayList) {
// return deduceOre((ArrayList) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
// public static String getFullObjectDeclaration(Object stack) {
// if (stack instanceof ItemStack) {
// ItemStack r = (ItemStack) stack;
// return getItemDeclaration(r) + ((r.stackSize>1)?String.format(" * %d", r.stackSize):"");
// } else if (stack instanceof FluidStack) {
// return getItemDeclaration((FluidStack) stack);
// } else if (stack == null) {
// return "null";
// } else {
// return "?????";
// }
// }
//
// protected static String getBoolean(boolean b) {
// return b?"true":"false";
// }
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static Object toObject(IIngredient iStack) {
// return toObject(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/InputHelper.java
// public static ItemStack toStack(IItemStack iStack) {
// return toStack(iStack, false);
// }
//
// Path: src/main/java/mods/belgabor/amtweaker/helpers/StackHelper.java
// public static boolean areEqual(ItemStack stack, ItemStack stack2) {
// return !(stack == null || stack2 == null) && stack.isItemEqual(stack2);
// }
// Path: src/main/java/mods/belgabor/amtweaker/mods/ss2/handlers/NormalRecipe.java
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.api.item.IIngredient;
import minetweaker.api.item.IItemStack;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.item.ItemStack;
import shift.sextiarysector.api.recipe.INormalRecipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static mods.belgabor.amtweaker.helpers.InputHelper.toObject;
import static mods.belgabor.amtweaker.helpers.InputHelper.toStack;
import static mods.belgabor.amtweaker.helpers.StackHelper.areEqual;
applied = false;
}
}
}
@Override
public String describe() {
return String.format("%s: Adding recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output));
}
@Override
public String describeUndo() {
return String.format("%s: Removing recipe for %s to %s", name, CommandLoggerBase.getObjectDeclaration(input), CommandLoggerBase.getObjectDeclaration(output));
}
@Override
public Object getOverrideKey() {
return null;
}
}
protected static void doRemove(INormalRecipe handler, String name, IItemStack output, IIngredient input) {
if (output == null) {
MineTweakerAPI.getLogger().logError(String.format("%s: Output item must not be null!", name));
return;
}
Object iInput = null;
if (input == null) {
boolean found = false;
for(ItemStack test : handler.getOreList().values()) { | if (areEqual(test, toStack(output))) { |
gregdurrett/berkeley-entity | src/main/java/edu/berkeley/nlp/entity/Driver.java | // Path: src/main/java/edu/berkeley/nlp/entity/coref/ConjFeatures.java
// public enum ConjFeatures {
// NONE, TYPE, TYPE_OR_RAW_PRON, TYPE_OR_CANONICAL_PRON, SEMCLASS_OR_CANONICAL_PRON, SEMCLASS_OR_CANONICAL_PRON_COORD,
// NER_OR_CANONICAL_PRON, NERFINE_OR_CANONICAL_PRON, SEMCLASS_NER_OR_CANONICAL_PRON,
// CUSTOM_OR_CANONICAL_PRON, CUSTOM_NER_OR_CANONICAL_PRON, CUSTOM_NERMED_OR_CANONICAL_PRON, CUSTOM_NERFINE_OR_CANONICAL_PRON;
// }
| import edu.berkeley.nlp.entity.coref.ConjFeatures;
import edu.berkeley.nlp.entity.coref.ConjScheme;
import edu.berkeley.nlp.entity.coref.CorefPrunerJavaHack;
import edu.berkeley.nlp.entity.coref.CorefSystem;
import edu.berkeley.nlp.entity.lang.Language;
import edu.berkeley.nlp.futile.fig.basic.Option;
import edu.berkeley.nlp.futile.fig.exec.Execution;
import edu.berkeley.nlp.futile.util.Logger; |
@Option(gloss = "")
public static String neMentType = "all";
@Option(gloss = "")
public static boolean setProperMentionsFromNER = true;
// TRAINING AND INFERENCE
// These settings are reasonable and quite robust; you really shouldn't have
// to tune the regularizer. I didn't find adjusting it useful even when going
// from thousands to millions of features.
@Option(gloss = "eta for Adagrad")
public static double eta = 1.0;
@Option(gloss = "Regularization constant (might be lambda or c depending on which algorithm is used)")
public static double reg = 0.001;
@Option(gloss = "Batch size; right now batchSize > 1 works badly for some reason")
public static int batchSize = 1;
// COREFERENCE OPTIONS
@Option(gloss = "Loss fcn to use")
public static String lossFcn = "customLoss-0.1-3-1";
@Option(gloss = "Loss fcn to use")
public static String lossFcnSecondPass = "customLoss-0.1-3-1";
@Option(gloss = "Number of iterations")
public static int numItrs = 20;
@Option(gloss = "Pruning strategy for coarse pass. No pruning by default")
public static String pruningStrategy = "distance:10000:5000";
@Option(gloss = "Features to use")
public static String pairwiseFeats = "FINAL";
@Option(gloss = "Conjunction features: what bits do we add to each feature?") | // Path: src/main/java/edu/berkeley/nlp/entity/coref/ConjFeatures.java
// public enum ConjFeatures {
// NONE, TYPE, TYPE_OR_RAW_PRON, TYPE_OR_CANONICAL_PRON, SEMCLASS_OR_CANONICAL_PRON, SEMCLASS_OR_CANONICAL_PRON_COORD,
// NER_OR_CANONICAL_PRON, NERFINE_OR_CANONICAL_PRON, SEMCLASS_NER_OR_CANONICAL_PRON,
// CUSTOM_OR_CANONICAL_PRON, CUSTOM_NER_OR_CANONICAL_PRON, CUSTOM_NERMED_OR_CANONICAL_PRON, CUSTOM_NERFINE_OR_CANONICAL_PRON;
// }
// Path: src/main/java/edu/berkeley/nlp/entity/Driver.java
import edu.berkeley.nlp.entity.coref.ConjFeatures;
import edu.berkeley.nlp.entity.coref.ConjScheme;
import edu.berkeley.nlp.entity.coref.CorefPrunerJavaHack;
import edu.berkeley.nlp.entity.coref.CorefSystem;
import edu.berkeley.nlp.entity.lang.Language;
import edu.berkeley.nlp.futile.fig.basic.Option;
import edu.berkeley.nlp.futile.fig.exec.Execution;
import edu.berkeley.nlp.futile.util.Logger;
@Option(gloss = "")
public static String neMentType = "all";
@Option(gloss = "")
public static boolean setProperMentionsFromNER = true;
// TRAINING AND INFERENCE
// These settings are reasonable and quite robust; you really shouldn't have
// to tune the regularizer. I didn't find adjusting it useful even when going
// from thousands to millions of features.
@Option(gloss = "eta for Adagrad")
public static double eta = 1.0;
@Option(gloss = "Regularization constant (might be lambda or c depending on which algorithm is used)")
public static double reg = 0.001;
@Option(gloss = "Batch size; right now batchSize > 1 works badly for some reason")
public static int batchSize = 1;
// COREFERENCE OPTIONS
@Option(gloss = "Loss fcn to use")
public static String lossFcn = "customLoss-0.1-3-1";
@Option(gloss = "Loss fcn to use")
public static String lossFcnSecondPass = "customLoss-0.1-3-1";
@Option(gloss = "Number of iterations")
public static int numItrs = 20;
@Option(gloss = "Pruning strategy for coarse pass. No pruning by default")
public static String pruningStrategy = "distance:10000:5000";
@Option(gloss = "Features to use")
public static String pairwiseFeats = "FINAL";
@Option(gloss = "Conjunction features: what bits do we add to each feature?") | public static ConjFeatures conjFeats = ConjFeatures.TYPE_OR_CANONICAL_PRON; |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/ui/activity/base/BaseActivity.java | // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.haogefeifei.odoo.application.App;
import com.haogefeifei.odoo.common.utils.LogOldUtil;
import com.umeng.analytics.MobclickAgent; | package com.haogefeifei.odoo.ui.activity.base;
/**
* 基础
* Created by feifei on 15/7/2.
*/
public class BaseActivity extends AppCompatActivity {
private static final String TAG = "BaseActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() { | // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/base/BaseActivity.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.haogefeifei.odoo.application.App;
import com.haogefeifei.odoo.common.utils.LogOldUtil;
import com.umeng.analytics.MobclickAgent;
package com.haogefeifei.odoo.ui.activity.base;
/**
* 基础
* Created by feifei on 15/7/2.
*/
public class BaseActivity extends AppCompatActivity {
private static final String TAG = "BaseActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() { | LogOldUtil.d(TAG, this.getClass().getSimpleName() + " onStart() invoked!!"); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/ui/activity/base/BaseActivity.java | // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.haogefeifei.odoo.application.App;
import com.haogefeifei.odoo.common.utils.LogOldUtil;
import com.umeng.analytics.MobclickAgent; | }
}
protected static int getNavigationBarHeight(Context context) {
int navigationBarHeight = 0;
Resources rs = context.getResources();
int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
if (id > 0) {
navigationBarHeight = rs.getDimensionPixelSize(id);
}
return navigationBarHeight;
}
@SuppressLint("NewApi")
protected static boolean checkDeviceHasNavigationBar(Context activity) {
//通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
boolean hasMenuKey = ViewConfiguration.get(activity)
.hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasMenuKey && !hasBackKey) {
// 做任何你需要做的,这个设备有一个导航栏
return true;
}
return false;
}
protected void showShort(String msg){
| // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/base/BaseActivity.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import com.haogefeifei.odoo.application.App;
import com.haogefeifei.odoo.common.utils.LogOldUtil;
import com.umeng.analytics.MobclickAgent;
}
}
protected static int getNavigationBarHeight(Context context) {
int navigationBarHeight = 0;
Resources rs = context.getResources();
int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
if (id > 0) {
navigationBarHeight = rs.getDimensionPixelSize(id);
}
return navigationBarHeight;
}
@SuppressLint("NewApi")
protected static boolean checkDeviceHasNavigationBar(Context activity) {
//通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
boolean hasMenuKey = ViewConfiguration.get(activity)
.hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasMenuKey && !hasBackKey) {
// 做任何你需要做的,这个设备有一个导航栏
return true;
}
return false;
}
protected void showShort(String msg){
| Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show(); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/service/inf/UserServiceInf.java | // Path: app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java
// public class OdooRpcException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// private String exceptionMessage = ""; //错误信息
//
// public static final String XML_ERROR = "服务器暂时无法您的处理请求";
// public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
// public static final String NULL_DATE_ERROR = "无法获取数据";
// public static final String NOT_HTTP = "没有网络";
// public static final String TIME_OUT = "请求超时";
//
// public String getExceptionMessage() {
// return exceptionMessage;
// }
//
// public void setExceptionMessage(String exceptionMessage) {
// this.exceptionMessage = exceptionMessage;
// }
//
// public String getMessage(){
// return exceptionMessage;
// }
//
// public OdooRpcException(String message) {
//
// super(message);
//
// //对错误信息进行处理
// LogUtil.d("ExceptionMessageUtil", message);
//
// String msg = "";
//
// if(message.indexOf("--") > -1){
// msg = StringCutOut.cutOut(message, message.indexOf("-- ") + 3, message.length());
// }
// else if(message.indexOf("HTTP server returned unexpected status: Not Found") > -1
// || message.indexOf("org.apache.http.conn.HttpHostConnectException") > -1){
// msg = FOUND_SERVER_ERROR;
// }
// else if(message.indexOf("Cannot serialize null") > -1){
// msg = NULL_DATE_ERROR;
// }
// else if(message.indexOf("Failed to read server's response: failed to connect") > -1
// || message.indexOf("Null values aren't supported") > -1
// || message.indexOf("ConnectTimeoutException") > -1
// || message.indexOf("SocketTimeoutException") > -1){
//
// msg = TIME_OUT;
//
// }
// else{
// msg = message;
// }
//
// this.exceptionMessage = msg;
//
// }
//
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/entity/User.java
// public class User extends OdooModel {
//
// public static final String MODEL_NAME = "res.users";
//
// private String username ; // 用户名
// private String login ; //用户登录账号
// private String password ; //用户密码
// private String image ;
// private Timestamp loginTime ;
// private Object[] em_ids;
//
// public Object[] getEm_ids() {
//
// if(em_ids == null){
// em_ids = new Object[0];
// }
//
// return em_ids;
// }
//
// public void setEm_ids(Object[] em_ids) {
// this.em_ids = em_ids;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getLogin() {
// return login;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Timestamp getLoginTime() {
// return loginTime;
// }
//
// public void setLoginTime(Timestamp loginTime) {
// this.loginTime = loginTime;
// }
// }
| import com.haogefeifei.odoo.api.inf.OdooRpcException;
import com.haogefeifei.odoo.entity.User; | package com.haogefeifei.odoo.service.inf;
/**
* Created by feifei on 15/12/28.
*/
public interface UserServiceInf {
/**
* 用户登录
*
* @return 登陆成功的id ,失败则返回负数代码
*/
public int Login() throws OdooRpcException;
/**
* 用户登录
*
* @param username
* @param password
* @return
* @throws OdooRpcException
*/
public int Login(String username, String password) throws OdooRpcException;
/**
* 通过用户id来获取用户信息
*
* @param uid 用户id
* @return User对象
*/ | // Path: app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java
// public class OdooRpcException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// private String exceptionMessage = ""; //错误信息
//
// public static final String XML_ERROR = "服务器暂时无法您的处理请求";
// public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
// public static final String NULL_DATE_ERROR = "无法获取数据";
// public static final String NOT_HTTP = "没有网络";
// public static final String TIME_OUT = "请求超时";
//
// public String getExceptionMessage() {
// return exceptionMessage;
// }
//
// public void setExceptionMessage(String exceptionMessage) {
// this.exceptionMessage = exceptionMessage;
// }
//
// public String getMessage(){
// return exceptionMessage;
// }
//
// public OdooRpcException(String message) {
//
// super(message);
//
// //对错误信息进行处理
// LogUtil.d("ExceptionMessageUtil", message);
//
// String msg = "";
//
// if(message.indexOf("--") > -1){
// msg = StringCutOut.cutOut(message, message.indexOf("-- ") + 3, message.length());
// }
// else if(message.indexOf("HTTP server returned unexpected status: Not Found") > -1
// || message.indexOf("org.apache.http.conn.HttpHostConnectException") > -1){
// msg = FOUND_SERVER_ERROR;
// }
// else if(message.indexOf("Cannot serialize null") > -1){
// msg = NULL_DATE_ERROR;
// }
// else if(message.indexOf("Failed to read server's response: failed to connect") > -1
// || message.indexOf("Null values aren't supported") > -1
// || message.indexOf("ConnectTimeoutException") > -1
// || message.indexOf("SocketTimeoutException") > -1){
//
// msg = TIME_OUT;
//
// }
// else{
// msg = message;
// }
//
// this.exceptionMessage = msg;
//
// }
//
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/entity/User.java
// public class User extends OdooModel {
//
// public static final String MODEL_NAME = "res.users";
//
// private String username ; // 用户名
// private String login ; //用户登录账号
// private String password ; //用户密码
// private String image ;
// private Timestamp loginTime ;
// private Object[] em_ids;
//
// public Object[] getEm_ids() {
//
// if(em_ids == null){
// em_ids = new Object[0];
// }
//
// return em_ids;
// }
//
// public void setEm_ids(Object[] em_ids) {
// this.em_ids = em_ids;
// }
//
// public String getImage() {
// return image;
// }
//
// public void setImage(String image) {
// this.image = image;
// }
//
// public String getLogin() {
// return login;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public void setLogin(String login) {
// this.login = login;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Timestamp getLoginTime() {
// return loginTime;
// }
//
// public void setLoginTime(Timestamp loginTime) {
// this.loginTime = loginTime;
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/service/inf/UserServiceInf.java
import com.haogefeifei.odoo.api.inf.OdooRpcException;
import com.haogefeifei.odoo.entity.User;
package com.haogefeifei.odoo.service.inf;
/**
* Created by feifei on 15/12/28.
*/
public interface UserServiceInf {
/**
* 用户登录
*
* @return 登陆成功的id ,失败则返回负数代码
*/
public int Login() throws OdooRpcException;
/**
* 用户登录
*
* @param username
* @param password
* @return
* @throws OdooRpcException
*/
public int Login(String username, String password) throws OdooRpcException;
/**
* 通过用户id来获取用户信息
*
* @param uid 用户id
* @return User对象
*/ | public User getUserInfo(int uid) throws OdooRpcException; |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/api/OdooConnect.java | // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
| import com.haogefeifei.odoo.application.App; | package com.haogefeifei.odoo.api;
/**
* XmlRPC访问Odoo连接参数对象
*
* @author feifei
*/
public class OdooConnect {
private static OdooConnect instance = new OdooConnect();
public static OdooConnect getInstance() {
| // Path: app/src/main/java/com/haogefeifei/odoo/application/App.java
// public class App extends Application {
//
// public static final String TAG = "OdooApp";
//
// private static App application;
// private static OdooConnect instanceConnect = OdooConnect.getInstanceApplication();
//
// public OdooConnect getInstanceConnect() {
// return instanceConnect;
// }
//
// public static App getInstance() {
// return application;
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// application = this;
//
// initMap();
// initConnectConfig();
// }
//
// private void initMap() {
//
// //在使用SDK各组件之前初始化context信息,传入ApplicationContext
// //注意该方法要再setContentView方法之前实现
// SDKInitializer.initialize(getApplicationContext());
// }
//
// private void initConnectConfig(){
//
// OdooConnect connect = OdooConnect.getInstance();
// connect.setHost("192.168.31.247");
// connect.setPort(8069);
// connect.setDb("odoo");
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/api/OdooConnect.java
import com.haogefeifei.odoo.application.App;
package com.haogefeifei.odoo.api;
/**
* XmlRPC访问Odoo连接参数对象
*
* @author feifei
*/
public class OdooConnect {
private static OdooConnect instance = new OdooConnect();
public static OdooConnect getInstance() {
| return App.getInstance().getInstanceConnect(); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogUtil.java
// public class LogUtil {
//
// public static boolean isDebug = true;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).v(msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).v(msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).d(msg);
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).d(msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).i(msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).i(msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).w(msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).w(msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).e(msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).e(msg, t);
// }
//
// public static void json(String tag, String json) {
// if (isDebug)
// Logger.t(tag).json(json);
// }
//
// public static void xml(String tag, String xml) {
// if (isDebug)
// Logger.t(tag).xml(xml);
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/StringCutOut.java
// public class StringCutOut {
//
// public static String cutOut(String matter, int IndexofA, int IndexofB) {
// return matter.substring(IndexofA, IndexofB);
// }
//
// public static String cutOut(String matter, String str) {
// int Indexof = matter.indexOf(str);
// return matter.substring(0, Indexof);
// }
//
// public static String cutOut(String matter, String strA, String strB) {
// String strtempa = strA;
// String strtempb = strB;
// int IndexofA = matter.indexOf(strtempa) + strtempa.length();
// int IndexofB = matter.indexOf(strtempb);
// String s = null;
// try {
// s = matter.substring(IndexofA, IndexofB);
// } catch (Exception e) {
// e.printStackTrace();
// s = "0";
// } finally {
// return s;
// }
//
// }
//
// }
| import com.haogefeifei.odoo.common.utils.LogUtil;
import com.haogefeifei.odoo.common.utils.StringCutOut; | package com.haogefeifei.odoo.api.inf;
/**
* RPC异常类
* Created by feifei on 15/12/27.
*/
public class OdooRpcException extends Exception {
private static final long serialVersionUID = 1L;
private String exceptionMessage = ""; //错误信息
public static final String XML_ERROR = "服务器暂时无法您的处理请求";
public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
public static final String NULL_DATE_ERROR = "无法获取数据";
public static final String NOT_HTTP = "没有网络";
public static final String TIME_OUT = "请求超时";
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getMessage(){
return exceptionMessage;
}
public OdooRpcException(String message) {
super(message);
//对错误信息进行处理 | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogUtil.java
// public class LogUtil {
//
// public static boolean isDebug = true;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).v(msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).v(msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).d(msg);
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).d(msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).i(msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).i(msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).w(msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).w(msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).e(msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).e(msg, t);
// }
//
// public static void json(String tag, String json) {
// if (isDebug)
// Logger.t(tag).json(json);
// }
//
// public static void xml(String tag, String xml) {
// if (isDebug)
// Logger.t(tag).xml(xml);
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/StringCutOut.java
// public class StringCutOut {
//
// public static String cutOut(String matter, int IndexofA, int IndexofB) {
// return matter.substring(IndexofA, IndexofB);
// }
//
// public static String cutOut(String matter, String str) {
// int Indexof = matter.indexOf(str);
// return matter.substring(0, Indexof);
// }
//
// public static String cutOut(String matter, String strA, String strB) {
// String strtempa = strA;
// String strtempb = strB;
// int IndexofA = matter.indexOf(strtempa) + strtempa.length();
// int IndexofB = matter.indexOf(strtempb);
// String s = null;
// try {
// s = matter.substring(IndexofA, IndexofB);
// } catch (Exception e) {
// e.printStackTrace();
// s = "0";
// } finally {
// return s;
// }
//
// }
//
// }
// Path: app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java
import com.haogefeifei.odoo.common.utils.LogUtil;
import com.haogefeifei.odoo.common.utils.StringCutOut;
package com.haogefeifei.odoo.api.inf;
/**
* RPC异常类
* Created by feifei on 15/12/27.
*/
public class OdooRpcException extends Exception {
private static final long serialVersionUID = 1L;
private String exceptionMessage = ""; //错误信息
public static final String XML_ERROR = "服务器暂时无法您的处理请求";
public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
public static final String NULL_DATE_ERROR = "无法获取数据";
public static final String NOT_HTTP = "没有网络";
public static final String TIME_OUT = "请求超时";
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getMessage(){
return exceptionMessage;
}
public OdooRpcException(String message) {
super(message);
//对错误信息进行处理 | LogUtil.d("ExceptionMessageUtil", message); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogUtil.java
// public class LogUtil {
//
// public static boolean isDebug = true;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).v(msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).v(msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).d(msg);
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).d(msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).i(msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).i(msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).w(msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).w(msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).e(msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).e(msg, t);
// }
//
// public static void json(String tag, String json) {
// if (isDebug)
// Logger.t(tag).json(json);
// }
//
// public static void xml(String tag, String xml) {
// if (isDebug)
// Logger.t(tag).xml(xml);
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/StringCutOut.java
// public class StringCutOut {
//
// public static String cutOut(String matter, int IndexofA, int IndexofB) {
// return matter.substring(IndexofA, IndexofB);
// }
//
// public static String cutOut(String matter, String str) {
// int Indexof = matter.indexOf(str);
// return matter.substring(0, Indexof);
// }
//
// public static String cutOut(String matter, String strA, String strB) {
// String strtempa = strA;
// String strtempb = strB;
// int IndexofA = matter.indexOf(strtempa) + strtempa.length();
// int IndexofB = matter.indexOf(strtempb);
// String s = null;
// try {
// s = matter.substring(IndexofA, IndexofB);
// } catch (Exception e) {
// e.printStackTrace();
// s = "0";
// } finally {
// return s;
// }
//
// }
//
// }
| import com.haogefeifei.odoo.common.utils.LogUtil;
import com.haogefeifei.odoo.common.utils.StringCutOut; | package com.haogefeifei.odoo.api.inf;
/**
* RPC异常类
* Created by feifei on 15/12/27.
*/
public class OdooRpcException extends Exception {
private static final long serialVersionUID = 1L;
private String exceptionMessage = ""; //错误信息
public static final String XML_ERROR = "服务器暂时无法您的处理请求";
public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
public static final String NULL_DATE_ERROR = "无法获取数据";
public static final String NOT_HTTP = "没有网络";
public static final String TIME_OUT = "请求超时";
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getMessage(){
return exceptionMessage;
}
public OdooRpcException(String message) {
super(message);
//对错误信息进行处理
LogUtil.d("ExceptionMessageUtil", message);
String msg = "";
if(message.indexOf("--") > -1){ | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogUtil.java
// public class LogUtil {
//
// public static boolean isDebug = true;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).v(msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).v(msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).d(msg);
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).d(msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).i(msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).i(msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).w(msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).w(msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// Logger.t(tag).e(msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// Logger.t(tag).e(msg, t);
// }
//
// public static void json(String tag, String json) {
// if (isDebug)
// Logger.t(tag).json(json);
// }
//
// public static void xml(String tag, String xml) {
// if (isDebug)
// Logger.t(tag).xml(xml);
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/StringCutOut.java
// public class StringCutOut {
//
// public static String cutOut(String matter, int IndexofA, int IndexofB) {
// return matter.substring(IndexofA, IndexofB);
// }
//
// public static String cutOut(String matter, String str) {
// int Indexof = matter.indexOf(str);
// return matter.substring(0, Indexof);
// }
//
// public static String cutOut(String matter, String strA, String strB) {
// String strtempa = strA;
// String strtempb = strB;
// int IndexofA = matter.indexOf(strtempa) + strtempa.length();
// int IndexofB = matter.indexOf(strtempb);
// String s = null;
// try {
// s = matter.substring(IndexofA, IndexofB);
// } catch (Exception e) {
// e.printStackTrace();
// s = "0";
// } finally {
// return s;
// }
//
// }
//
// }
// Path: app/src/main/java/com/haogefeifei/odoo/api/inf/OdooRpcException.java
import com.haogefeifei.odoo.common.utils.LogUtil;
import com.haogefeifei.odoo.common.utils.StringCutOut;
package com.haogefeifei.odoo.api.inf;
/**
* RPC异常类
* Created by feifei on 15/12/27.
*/
public class OdooRpcException extends Exception {
private static final long serialVersionUID = 1L;
private String exceptionMessage = ""; //错误信息
public static final String XML_ERROR = "服务器暂时无法您的处理请求";
public static final String FOUND_SERVER_ERROR = "无法与服务器通信";
public static final String NULL_DATE_ERROR = "无法获取数据";
public static final String NOT_HTTP = "没有网络";
public static final String TIME_OUT = "请求超时";
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getMessage(){
return exceptionMessage;
}
public OdooRpcException(String message) {
super(message);
//对错误信息进行处理
LogUtil.d("ExceptionMessageUtil", message);
String msg = "";
if(message.indexOf("--") > -1){ | msg = StringCutOut.cutOut(message, message.indexOf("-- ") + 3, message.length()); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/db/DBHelper.java | // Path: app/src/main/java/com/haogefeifei/odoo/db/DBContract.java
// public class DBContract {
//
// /**
// * 版本管理表字段
// */
// public interface VersionColumns {
//
// String VERSION_VALUE = "version_value";
// String VERSION_KEY = "version_key";
// }
//
// /**
// * 客户表字段
// */
// public interface PartnerColumns {
//
// String PARTNER_ID = "partner_id"; //id
// String PARTNER_TYPE = "partner_type"; //类型
// String PARTNER_NAME = "partner_name"; //客户名称
// String PARTNER_PARENT_ID = "partner_parent_id"; //父id
// String PARTNER_COUNTRY = "partner_country"; //国家
// String PARTNER_STATE = "partner_state"; //省份
// String PARTNER_CITY = "partner_city"; //城市
// String PARTNER_ZIP = "partner_zip"; //邮编
// String PARTNER_STREET = "partner_street"; //街道
// String PARTNER_STREET2 = "partner_street2"; //街道2
// String PARTNER_EMAIL = "partner_email"; //邮箱
// String PARTNER_PHONE = "partner_phone"; //邮箱
// String PARTNER_FAX = "partner_fax"; //传真
// String PARTNER_MOBILE = "partner_mobile"; //手机
// String PARTNER_IMAGE = "partner_image"; //头像
// }
//
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import com.haogefeifei.odoo.db.DBContract.*;
import com.haogefeifei.odoo.common.utils.LogOldUtil; |
db.execSQL("INSERT INTO " + Tables.VERSION
+ " VALUES(null, ?, ?)", new Object[]{"update_time", "1979-01-01 01:00:00"});
db.execSQL("CREATE TABLE " + Tables.PARTNER + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PartnerColumns.PARTNER_ID + " INTEGER NOT NULL,"
+ PartnerColumns.PARTNER_TYPE + " TEXT,"
+ PartnerColumns.PARTNER_NAME + " TEXT NOT NULL,"
+ PartnerColumns.PARTNER_PARENT_ID + " INTEGER,"
+ PartnerColumns.PARTNER_COUNTRY + " TEXT,"
+ PartnerColumns.PARTNER_STATE + " TEXT,"
+ PartnerColumns.PARTNER_CITY + " TEXT,"
+ PartnerColumns.PARTNER_ZIP + " TEXT,"
+ PartnerColumns.PARTNER_STREET + " TEXT,"
+ PartnerColumns.PARTNER_STREET2 + " TEXT,"
+ PartnerColumns.PARTNER_EMAIL + " TEXT,"
+ PartnerColumns.PARTNER_PHONE + " TEXT,"
+ PartnerColumns.PARTNER_FAX + " TEXT,"
+ PartnerColumns.PARTNER_MOBILE + " TEXT,"
+ PartnerColumns.PARTNER_IMAGE + " TEXT)");
}
/**
* 当数据库版本发生改变的时候被调用
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
| // Path: app/src/main/java/com/haogefeifei/odoo/db/DBContract.java
// public class DBContract {
//
// /**
// * 版本管理表字段
// */
// public interface VersionColumns {
//
// String VERSION_VALUE = "version_value";
// String VERSION_KEY = "version_key";
// }
//
// /**
// * 客户表字段
// */
// public interface PartnerColumns {
//
// String PARTNER_ID = "partner_id"; //id
// String PARTNER_TYPE = "partner_type"; //类型
// String PARTNER_NAME = "partner_name"; //客户名称
// String PARTNER_PARENT_ID = "partner_parent_id"; //父id
// String PARTNER_COUNTRY = "partner_country"; //国家
// String PARTNER_STATE = "partner_state"; //省份
// String PARTNER_CITY = "partner_city"; //城市
// String PARTNER_ZIP = "partner_zip"; //邮编
// String PARTNER_STREET = "partner_street"; //街道
// String PARTNER_STREET2 = "partner_street2"; //街道2
// String PARTNER_EMAIL = "partner_email"; //邮箱
// String PARTNER_PHONE = "partner_phone"; //邮箱
// String PARTNER_FAX = "partner_fax"; //传真
// String PARTNER_MOBILE = "partner_mobile"; //手机
// String PARTNER_IMAGE = "partner_image"; //头像
// }
//
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/common/utils/LogOldUtil.java
// public class LogOldUtil {
//
// public static boolean isDebug = LogUtil.isDebug;
//
// public static void v(String tag, String msg) {
// if (isDebug)
// android.util.Log.v(tag, msg);
// }
//
// public static void v(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.v(tag, msg, t);
// }
//
// public static void d(String tag, String msg) {
// if (isDebug){
//
// try {
//
// android.util.Log.d(tag, msg);
// }
// catch (NullPointerException e){
//
// }
//
// }
//
//
// }
//
// public static void d(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.d(tag, msg, t);
// }
//
// public static void i(String tag, String msg) {
// if (isDebug)
// android.util.Log.i(tag, msg);
// }
//
// public static void i(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.i(tag, msg, t);
// }
//
// public static void w(String tag, String msg) {
// if (isDebug)
// android.util.Log.w(tag, msg);
// }
//
// public static void w(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.w(tag, msg, t);
// }
//
// public static void e(String tag, String msg) {
// if (isDebug)
// android.util.Log.e(tag, msg);
// }
//
// public static void e(String tag, String msg, Throwable t) {
// if (isDebug)
// android.util.Log.e(tag, msg, t);
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/db/DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import com.haogefeifei.odoo.db.DBContract.*;
import com.haogefeifei.odoo.common.utils.LogOldUtil;
db.execSQL("INSERT INTO " + Tables.VERSION
+ " VALUES(null, ?, ?)", new Object[]{"update_time", "1979-01-01 01:00:00"});
db.execSQL("CREATE TABLE " + Tables.PARTNER + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ PartnerColumns.PARTNER_ID + " INTEGER NOT NULL,"
+ PartnerColumns.PARTNER_TYPE + " TEXT,"
+ PartnerColumns.PARTNER_NAME + " TEXT NOT NULL,"
+ PartnerColumns.PARTNER_PARENT_ID + " INTEGER,"
+ PartnerColumns.PARTNER_COUNTRY + " TEXT,"
+ PartnerColumns.PARTNER_STATE + " TEXT,"
+ PartnerColumns.PARTNER_CITY + " TEXT,"
+ PartnerColumns.PARTNER_ZIP + " TEXT,"
+ PartnerColumns.PARTNER_STREET + " TEXT,"
+ PartnerColumns.PARTNER_STREET2 + " TEXT,"
+ PartnerColumns.PARTNER_EMAIL + " TEXT,"
+ PartnerColumns.PARTNER_PHONE + " TEXT,"
+ PartnerColumns.PARTNER_FAX + " TEXT,"
+ PartnerColumns.PARTNER_MOBILE + " TEXT,"
+ PartnerColumns.PARTNER_IMAGE + " TEXT)");
}
/**
* 当数据库版本发生改变的时候被调用
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
| LogOldUtil.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/ui/activity/IntroActivity.java | // Path: app/src/main/java/com/haogefeifei/odoo/ui/fragment/SampleSlide.java
// public class SampleSlide extends Fragment {
//
// private static final String ARG_LAYOUT_RES_ID = "layoutResId";
//
// public static SampleSlide newInstance(int layoutResId) {
// SampleSlide sampleSlide = new SampleSlide();
//
// Bundle args = new Bundle();
// args.putInt(ARG_LAYOUT_RES_ID, layoutResId);
// sampleSlide.setArguments(args);
//
// return sampleSlide;
// }
//
// private int layoutResId;
//
// public SampleSlide() {}
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// if(getArguments() != null && getArguments().containsKey(ARG_LAYOUT_RES_ID))
// layoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return inflater.inflate(layoutResId, container, false);
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.WindowManager;
import com.github.paolorotolo.appintro.AppIntro;
import com.haogefeifei.odoo.R;
import com.haogefeifei.odoo.ui.fragment.SampleSlide; | package com.haogefeifei.odoo.ui.activity;
/**
* 介绍Activity
*/
public class IntroActivity extends AppIntro {
public static final String TAG = "IntroActivity";
@Override
public void init(@Nullable Bundle savedInstanceState) {
| // Path: app/src/main/java/com/haogefeifei/odoo/ui/fragment/SampleSlide.java
// public class SampleSlide extends Fragment {
//
// private static final String ARG_LAYOUT_RES_ID = "layoutResId";
//
// public static SampleSlide newInstance(int layoutResId) {
// SampleSlide sampleSlide = new SampleSlide();
//
// Bundle args = new Bundle();
// args.putInt(ARG_LAYOUT_RES_ID, layoutResId);
// sampleSlide.setArguments(args);
//
// return sampleSlide;
// }
//
// private int layoutResId;
//
// public SampleSlide() {}
//
// @Override
// public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// if(getArguments() != null && getArguments().containsKey(ARG_LAYOUT_RES_ID))
// layoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return inflater.inflate(layoutResId, container, false);
// }
//
// }
// Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/IntroActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.WindowManager;
import com.github.paolorotolo.appintro.AppIntro;
import com.haogefeifei.odoo.R;
import com.haogefeifei.odoo.ui.fragment.SampleSlide;
package com.haogefeifei.odoo.ui.activity;
/**
* 介绍Activity
*/
public class IntroActivity extends AppIntro {
public static final String TAG = "IntroActivity";
@Override
public void init(@Nullable Bundle savedInstanceState) {
| addSlide(SampleSlide.newInstance(R.layout.view_intro)); |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/api/inf/RpcApiInf.java | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/Page.java
// public class Page {
//
// // 1.每页显示数量(everyPage)
// private int everyPage;
// //2.当前页(currentPage)
// private int currentPage;
//
// public Page(int everyPage, int currentPage) {
// this.everyPage = everyPage;
// this.currentPage = currentPage;
// }
//
// //构造函数,默认
// //构造方法,对所有属性进行设置
// public Page() {
// this.currentPage = 1;
// this.everyPage = 30;
// }
//
// public int getEveryPage() {
// return everyPage;
// }
//
// public void setEveryPage(int everyPage) {
// this.everyPage = everyPage;
// }
//
// public int getCurrentPage() {
// return currentPage;
// }
//
// public void setCurrentPage(int currentPage) {
// this.currentPage = currentPage;
// }
//
//
// }
| import com.haogefeifei.odoo.common.utils.Page;
import java.util.HashMap; | package com.haogefeifei.odoo.api.inf;
/**
* Created by feifei on 15/12/27.
*/
public interface RpcApiInf {
/**
* 登录
*
* @return 结果代码
*/
public int Connect() throws OdooRpcException;
/**
* 登录
*
* @param username
* @param password
* @return
* @throws OdooRpcException
*/
public int Connect(String username, String password) throws OdooRpcException;
/**
* 登录验证
*
* @param password
* @return
*/
public int confirmationPassWord(String password) throws OdooRpcException;
/**
* 查询记录总数
*
* @param model
* @param filters
* @return
*/
public Object getCount(String model, Object[] filters) throws OdooRpcException;
/**
* 创建对象
*
* @param model
* @param values
* @return
*/
public int createObject(String model, HashMap<String, Object> values) throws OdooRpcException;
/**
* 修改
*
* @param model
* @param values
* @return
*/
public Object writeObject(String model, Object[] ids, HashMap<String, Object> values) throws OdooRpcException;
/**
* 读取数据
*
* @param model
* @param ids
* @param fields
* @return
*/
public Object[] readData(String model, Object[] ids, Object[] fields) throws OdooRpcException;
/**
* 查询
*
* @param model 要查询的对象
* @param filters 查询过滤条件
*/
public Object[] searchObject(String model, Object[] filters) throws OdooRpcException;
/**
* 查询
*
* @param model 要查询的对象
* @param filters 查询过滤条件
* @param page 分页对象
*/ | // Path: app/src/main/java/com/haogefeifei/odoo/common/utils/Page.java
// public class Page {
//
// // 1.每页显示数量(everyPage)
// private int everyPage;
// //2.当前页(currentPage)
// private int currentPage;
//
// public Page(int everyPage, int currentPage) {
// this.everyPage = everyPage;
// this.currentPage = currentPage;
// }
//
// //构造函数,默认
// //构造方法,对所有属性进行设置
// public Page() {
// this.currentPage = 1;
// this.everyPage = 30;
// }
//
// public int getEveryPage() {
// return everyPage;
// }
//
// public void setEveryPage(int everyPage) {
// this.everyPage = everyPage;
// }
//
// public int getCurrentPage() {
// return currentPage;
// }
//
// public void setCurrentPage(int currentPage) {
// this.currentPage = currentPage;
// }
//
//
// }
// Path: app/src/main/java/com/haogefeifei/odoo/api/inf/RpcApiInf.java
import com.haogefeifei.odoo.common.utils.Page;
import java.util.HashMap;
package com.haogefeifei.odoo.api.inf;
/**
* Created by feifei on 15/12/27.
*/
public interface RpcApiInf {
/**
* 登录
*
* @return 结果代码
*/
public int Connect() throws OdooRpcException;
/**
* 登录
*
* @param username
* @param password
* @return
* @throws OdooRpcException
*/
public int Connect(String username, String password) throws OdooRpcException;
/**
* 登录验证
*
* @param password
* @return
*/
public int confirmationPassWord(String password) throws OdooRpcException;
/**
* 查询记录总数
*
* @param model
* @param filters
* @return
*/
public Object getCount(String model, Object[] filters) throws OdooRpcException;
/**
* 创建对象
*
* @param model
* @param values
* @return
*/
public int createObject(String model, HashMap<String, Object> values) throws OdooRpcException;
/**
* 修改
*
* @param model
* @param values
* @return
*/
public Object writeObject(String model, Object[] ids, HashMap<String, Object> values) throws OdooRpcException;
/**
* 读取数据
*
* @param model
* @param ids
* @param fields
* @return
*/
public Object[] readData(String model, Object[] ids, Object[] fields) throws OdooRpcException;
/**
* 查询
*
* @param model 要查询的对象
* @param filters 查询过滤条件
*/
public Object[] searchObject(String model, Object[] filters) throws OdooRpcException;
/**
* 查询
*
* @param model 要查询的对象
* @param filters 查询过滤条件
* @param page 分页对象
*/ | public Object[] searchObject(String model, Object[] filters, Page page) throws OdooRpcException; |
haogefeifei/odoo-mobile-building | app/src/main/java/com/haogefeifei/odoo/ui/activity/SettingActivity.java | // Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/base/ToolbarActivity.java
// public abstract class ToolbarActivity extends AppCompatActivity {
//
// abstract protected int getLayoutResource();
//
// protected AppBarLayout mAppBar;
// protected Toolbar mToolbar;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutResource());
//
// mAppBar = (AppBarLayout) findViewById(R.id.app_bar_layout);
// mToolbar = (Toolbar) findViewById(R.id.toolbar);
//
// if (mToolbar == null || mAppBar == null) {
// throw new IllegalStateException("no toolbar");
// }
//
// setSupportActionBar(mToolbar);
//
// if (canBack()) {
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true);
// }
//
// if (Build.VERSION.SDK_INT >= 21) {
// mAppBar.setElevation(10.6f);
// }
// }
//
// public boolean canBack() {
// return false;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// } else {
// return super.onOptionsItemSelected(item);
// }
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/ui/settings/SettingFragment.java
// public class SettingFragment extends PreferenceFragment
// implements Preference.OnPreferenceClickListener {
//
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.prefs);
// }
//
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
//
// return false;
// }
// }
| import android.os.Bundle;
import com.haogefeifei.odoo.R;
import com.haogefeifei.odoo.ui.activity.base.ToolbarActivity;
import com.haogefeifei.odoo.ui.settings.SettingFragment; | package com.haogefeifei.odoo.ui.activity;
public class SettingActivity extends ToolbarActivity {
public static final String TAG = "SettingActivity";
@Override
protected int getLayoutResource() {
return R.layout.activity_setting;
}
@Override
public boolean canBack() {
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.title_activity_setting));
getFragmentManager()
.beginTransaction() | // Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/base/ToolbarActivity.java
// public abstract class ToolbarActivity extends AppCompatActivity {
//
// abstract protected int getLayoutResource();
//
// protected AppBarLayout mAppBar;
// protected Toolbar mToolbar;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutResource());
//
// mAppBar = (AppBarLayout) findViewById(R.id.app_bar_layout);
// mToolbar = (Toolbar) findViewById(R.id.toolbar);
//
// if (mToolbar == null || mAppBar == null) {
// throw new IllegalStateException("no toolbar");
// }
//
// setSupportActionBar(mToolbar);
//
// if (canBack()) {
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true);
// }
//
// if (Build.VERSION.SDK_INT >= 21) {
// mAppBar.setElevation(10.6f);
// }
// }
//
// public boolean canBack() {
// return false;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == android.R.id.home) {
// onBackPressed();
// return true;
// } else {
// return super.onOptionsItemSelected(item);
// }
// }
// }
//
// Path: app/src/main/java/com/haogefeifei/odoo/ui/settings/SettingFragment.java
// public class SettingFragment extends PreferenceFragment
// implements Preference.OnPreferenceClickListener {
//
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.prefs);
// }
//
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
//
// return false;
// }
// }
// Path: app/src/main/java/com/haogefeifei/odoo/ui/activity/SettingActivity.java
import android.os.Bundle;
import com.haogefeifei.odoo.R;
import com.haogefeifei.odoo.ui.activity.base.ToolbarActivity;
import com.haogefeifei.odoo.ui.settings.SettingFragment;
package com.haogefeifei.odoo.ui.activity;
public class SettingActivity extends ToolbarActivity {
public static final String TAG = "SettingActivity";
@Override
protected int getLayoutResource() {
return R.layout.activity_setting;
}
@Override
public boolean canBack() {
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.title_activity_setting));
getFragmentManager()
.beginTransaction() | .replace(R.id.fragment_frame, new SettingFragment()) |
google/zetasketch | javatests/com/google/zetasketch/internal/hllplus/SparseRepresentationTest.java | // Path: java/com/google/zetasketch/internal/DifferenceDecoder.java
// public class DifferenceDecoder extends AbstractIntIterator {
//
// private final ByteSlice slice;
//
// private int last = 0;
//
// public DifferenceDecoder(ByteSlice slice) {
// Preconditions.checkNotNull(slice);
// this.slice = slice;
// }
//
// @Override
// public boolean hasNext() {
// return slice.hasRemaining();
// }
//
// @Override
// public int nextInt() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
//
// last += slice.getNextVarInt();
// return last;
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitIterableSubject.java
// public class IntegerBitIterableSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitIterableSubject, Iterable<Integer>> FACTORY =
// IntegerBitIterableSubject::new;
//
// public static IntegerBitIterableSubject assertThat(Iterable<Integer> value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// public static IntegerBitIterableSubject assertThat(Iterator<Integer> value) {
// return Truth.assertAbout(FACTORY).that(Lists.newArrayList(value));
// }
//
// private final Iterable<Integer> actual;
//
// private IntegerBitIterableSubject(FailureMetadata failureMetadata, Iterable<Integer> subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// if (other instanceof Iterable<?>) {
// internalIsEqualTo((Iterable<?>) other);
// } else if (other instanceof Iterator<?>) {
// internalIsEqualTo(Lists.newArrayList((Iterator<?>) other));
// } else {
// failWithActual("expected to be equal to", other);
// }
// }
//
// private void internalIsEqualTo(Iterable<?> other) {
// if (!Iterables.elementsEqual(this.actual, other)) {
// this.failWithActual("expected to be equal to", toString(other));
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toString(actual);
// }
//
// private static String toString(Iterable<?> list) {
// StringBuilder builder = new StringBuilder("[");
// boolean first = true;
// for (Object value : list) {
// if (!first) {
// builder.append(", ");
// }
// first = false;
//
// if (value instanceof Integer) {
// builder.append("0b").append(Integer.toBinaryString(((Integer) value).intValue()));
// } else {
// builder.append(value);
// }
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitSubject.java
// public class IntegerBitSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitSubject, Integer> FACTORY = IntegerBitSubject::new;
//
// public static IntegerBitSubject assertThat(Integer value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// private final Integer actual;
//
// private IntegerBitSubject(FailureMetadata failureMetadata, Integer subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// Object displayObject =
// (other instanceof Integer) ? toBinaryString(((Integer) other).intValue()) : other;
// if (!this.actual.equals(other)) {
// this.failWithActual("expected to be equal to", displayObject);
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toBinaryString(getIntSubject());
// }
//
// private static String toBinaryString(int value) {
// return "0b" + Integer.toBinaryString(value);
// }
//
// private int getIntSubject() {
// return actual.intValue();
// }
// }
| import static com.google.common.truth.Truth.assertThat;
import com.google.zetasketch.internal.DifferenceDecoder;
import com.google.zetasketch.testing.IntegerBitIterableSubject;
import com.google.zetasketch.testing.IntegerBitSubject;
import it.unimi.dsi.fastutil.ints.IntIterators;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hllplus;
/**
* Unit tests for the HLL++ {@link SparseRepresentation}.
*
* <p>IMPORTANT: Note that these tests were introduced later and currently don't cover the full
* functionality of SparseRepresentation. All code paths are covered by the more abstract {@link
* com.google.zetasketch.HyperLogLogPlusPlusTest}, however.
*/
// TODO: Remove warning above once unit test coverage is complete.
@RunWith(JUnit4.class)
public final class SparseRepresentationTest {
/**
* Verifies that a sparse value with a higher precision is correctly downgraded to match the
* representation.
*/
@Test
public void addSparseValue_HigherPrecision() {
Representation repr = create(10, 13);
Encoding.Sparse sparseEncoding = new Encoding.Sparse(11, 15);
int sparseValue = 0b000000000011111;
repr = repr.addSparseValue(sparseEncoding, sparseValue).compact();
assertThat(repr.state.precision).isEqualTo(10);
assertThat(repr.state.sparsePrecision).isEqualTo(13); | // Path: java/com/google/zetasketch/internal/DifferenceDecoder.java
// public class DifferenceDecoder extends AbstractIntIterator {
//
// private final ByteSlice slice;
//
// private int last = 0;
//
// public DifferenceDecoder(ByteSlice slice) {
// Preconditions.checkNotNull(slice);
// this.slice = slice;
// }
//
// @Override
// public boolean hasNext() {
// return slice.hasRemaining();
// }
//
// @Override
// public int nextInt() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
//
// last += slice.getNextVarInt();
// return last;
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitIterableSubject.java
// public class IntegerBitIterableSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitIterableSubject, Iterable<Integer>> FACTORY =
// IntegerBitIterableSubject::new;
//
// public static IntegerBitIterableSubject assertThat(Iterable<Integer> value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// public static IntegerBitIterableSubject assertThat(Iterator<Integer> value) {
// return Truth.assertAbout(FACTORY).that(Lists.newArrayList(value));
// }
//
// private final Iterable<Integer> actual;
//
// private IntegerBitIterableSubject(FailureMetadata failureMetadata, Iterable<Integer> subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// if (other instanceof Iterable<?>) {
// internalIsEqualTo((Iterable<?>) other);
// } else if (other instanceof Iterator<?>) {
// internalIsEqualTo(Lists.newArrayList((Iterator<?>) other));
// } else {
// failWithActual("expected to be equal to", other);
// }
// }
//
// private void internalIsEqualTo(Iterable<?> other) {
// if (!Iterables.elementsEqual(this.actual, other)) {
// this.failWithActual("expected to be equal to", toString(other));
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toString(actual);
// }
//
// private static String toString(Iterable<?> list) {
// StringBuilder builder = new StringBuilder("[");
// boolean first = true;
// for (Object value : list) {
// if (!first) {
// builder.append(", ");
// }
// first = false;
//
// if (value instanceof Integer) {
// builder.append("0b").append(Integer.toBinaryString(((Integer) value).intValue()));
// } else {
// builder.append(value);
// }
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitSubject.java
// public class IntegerBitSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitSubject, Integer> FACTORY = IntegerBitSubject::new;
//
// public static IntegerBitSubject assertThat(Integer value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// private final Integer actual;
//
// private IntegerBitSubject(FailureMetadata failureMetadata, Integer subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// Object displayObject =
// (other instanceof Integer) ? toBinaryString(((Integer) other).intValue()) : other;
// if (!this.actual.equals(other)) {
// this.failWithActual("expected to be equal to", displayObject);
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toBinaryString(getIntSubject());
// }
//
// private static String toBinaryString(int value) {
// return "0b" + Integer.toBinaryString(value);
// }
//
// private int getIntSubject() {
// return actual.intValue();
// }
// }
// Path: javatests/com/google/zetasketch/internal/hllplus/SparseRepresentationTest.java
import static com.google.common.truth.Truth.assertThat;
import com.google.zetasketch.internal.DifferenceDecoder;
import com.google.zetasketch.testing.IntegerBitIterableSubject;
import com.google.zetasketch.testing.IntegerBitSubject;
import it.unimi.dsi.fastutil.ints.IntIterators;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hllplus;
/**
* Unit tests for the HLL++ {@link SparseRepresentation}.
*
* <p>IMPORTANT: Note that these tests were introduced later and currently don't cover the full
* functionality of SparseRepresentation. All code paths are covered by the more abstract {@link
* com.google.zetasketch.HyperLogLogPlusPlusTest}, however.
*/
// TODO: Remove warning above once unit test coverage is complete.
@RunWith(JUnit4.class)
public final class SparseRepresentationTest {
/**
* Verifies that a sparse value with a higher precision is correctly downgraded to match the
* representation.
*/
@Test
public void addSparseValue_HigherPrecision() {
Representation repr = create(10, 13);
Encoding.Sparse sparseEncoding = new Encoding.Sparse(11, 15);
int sparseValue = 0b000000000011111;
repr = repr.addSparseValue(sparseEncoding, sparseValue).compact();
assertThat(repr.state.precision).isEqualTo(10);
assertThat(repr.state.sparsePrecision).isEqualTo(13); | IntegerBitIterableSubject.assertThat(new DifferenceDecoder(repr.state.sparseData)) |
google/zetasketch | javatests/com/google/zetasketch/internal/hllplus/SparseRepresentationTest.java | // Path: java/com/google/zetasketch/internal/DifferenceDecoder.java
// public class DifferenceDecoder extends AbstractIntIterator {
//
// private final ByteSlice slice;
//
// private int last = 0;
//
// public DifferenceDecoder(ByteSlice slice) {
// Preconditions.checkNotNull(slice);
// this.slice = slice;
// }
//
// @Override
// public boolean hasNext() {
// return slice.hasRemaining();
// }
//
// @Override
// public int nextInt() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
//
// last += slice.getNextVarInt();
// return last;
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitIterableSubject.java
// public class IntegerBitIterableSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitIterableSubject, Iterable<Integer>> FACTORY =
// IntegerBitIterableSubject::new;
//
// public static IntegerBitIterableSubject assertThat(Iterable<Integer> value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// public static IntegerBitIterableSubject assertThat(Iterator<Integer> value) {
// return Truth.assertAbout(FACTORY).that(Lists.newArrayList(value));
// }
//
// private final Iterable<Integer> actual;
//
// private IntegerBitIterableSubject(FailureMetadata failureMetadata, Iterable<Integer> subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// if (other instanceof Iterable<?>) {
// internalIsEqualTo((Iterable<?>) other);
// } else if (other instanceof Iterator<?>) {
// internalIsEqualTo(Lists.newArrayList((Iterator<?>) other));
// } else {
// failWithActual("expected to be equal to", other);
// }
// }
//
// private void internalIsEqualTo(Iterable<?> other) {
// if (!Iterables.elementsEqual(this.actual, other)) {
// this.failWithActual("expected to be equal to", toString(other));
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toString(actual);
// }
//
// private static String toString(Iterable<?> list) {
// StringBuilder builder = new StringBuilder("[");
// boolean first = true;
// for (Object value : list) {
// if (!first) {
// builder.append(", ");
// }
// first = false;
//
// if (value instanceof Integer) {
// builder.append("0b").append(Integer.toBinaryString(((Integer) value).intValue()));
// } else {
// builder.append(value);
// }
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitSubject.java
// public class IntegerBitSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitSubject, Integer> FACTORY = IntegerBitSubject::new;
//
// public static IntegerBitSubject assertThat(Integer value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// private final Integer actual;
//
// private IntegerBitSubject(FailureMetadata failureMetadata, Integer subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// Object displayObject =
// (other instanceof Integer) ? toBinaryString(((Integer) other).intValue()) : other;
// if (!this.actual.equals(other)) {
// this.failWithActual("expected to be equal to", displayObject);
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toBinaryString(getIntSubject());
// }
//
// private static String toBinaryString(int value) {
// return "0b" + Integer.toBinaryString(value);
// }
//
// private int getIntSubject() {
// return actual.intValue();
// }
// }
| import static com.google.common.truth.Truth.assertThat;
import com.google.zetasketch.internal.DifferenceDecoder;
import com.google.zetasketch.testing.IntegerBitIterableSubject;
import com.google.zetasketch.testing.IntegerBitSubject;
import it.unimi.dsi.fastutil.ints.IntIterators;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hllplus;
/**
* Unit tests for the HLL++ {@link SparseRepresentation}.
*
* <p>IMPORTANT: Note that these tests were introduced later and currently don't cover the full
* functionality of SparseRepresentation. All code paths are covered by the more abstract {@link
* com.google.zetasketch.HyperLogLogPlusPlusTest}, however.
*/
// TODO: Remove warning above once unit test coverage is complete.
@RunWith(JUnit4.class)
public final class SparseRepresentationTest {
/**
* Verifies that a sparse value with a higher precision is correctly downgraded to match the
* representation.
*/
@Test
public void addSparseValue_HigherPrecision() {
Representation repr = create(10, 13);
Encoding.Sparse sparseEncoding = new Encoding.Sparse(11, 15);
int sparseValue = 0b000000000011111;
repr = repr.addSparseValue(sparseEncoding, sparseValue).compact();
assertThat(repr.state.precision).isEqualTo(10);
assertThat(repr.state.sparsePrecision).isEqualTo(13); | // Path: java/com/google/zetasketch/internal/DifferenceDecoder.java
// public class DifferenceDecoder extends AbstractIntIterator {
//
// private final ByteSlice slice;
//
// private int last = 0;
//
// public DifferenceDecoder(ByteSlice slice) {
// Preconditions.checkNotNull(slice);
// this.slice = slice;
// }
//
// @Override
// public boolean hasNext() {
// return slice.hasRemaining();
// }
//
// @Override
// public int nextInt() {
// if (!hasNext()) {
// throw new NoSuchElementException();
// }
//
// last += slice.getNextVarInt();
// return last;
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitIterableSubject.java
// public class IntegerBitIterableSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitIterableSubject, Iterable<Integer>> FACTORY =
// IntegerBitIterableSubject::new;
//
// public static IntegerBitIterableSubject assertThat(Iterable<Integer> value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// public static IntegerBitIterableSubject assertThat(Iterator<Integer> value) {
// return Truth.assertAbout(FACTORY).that(Lists.newArrayList(value));
// }
//
// private final Iterable<Integer> actual;
//
// private IntegerBitIterableSubject(FailureMetadata failureMetadata, Iterable<Integer> subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// if (other instanceof Iterable<?>) {
// internalIsEqualTo((Iterable<?>) other);
// } else if (other instanceof Iterator<?>) {
// internalIsEqualTo(Lists.newArrayList((Iterator<?>) other));
// } else {
// failWithActual("expected to be equal to", other);
// }
// }
//
// private void internalIsEqualTo(Iterable<?> other) {
// if (!Iterables.elementsEqual(this.actual, other)) {
// this.failWithActual("expected to be equal to", toString(other));
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toString(actual);
// }
//
// private static String toString(Iterable<?> list) {
// StringBuilder builder = new StringBuilder("[");
// boolean first = true;
// for (Object value : list) {
// if (!first) {
// builder.append(", ");
// }
// first = false;
//
// if (value instanceof Integer) {
// builder.append("0b").append(Integer.toBinaryString(((Integer) value).intValue()));
// } else {
// builder.append(value);
// }
// }
// builder.append("]");
// return builder.toString();
// }
// }
//
// Path: java/com/google/zetasketch/testing/IntegerBitSubject.java
// public class IntegerBitSubject extends Subject {
//
// private static final Subject.Factory<IntegerBitSubject, Integer> FACTORY = IntegerBitSubject::new;
//
// public static IntegerBitSubject assertThat(Integer value) {
// return Truth.assertAbout(FACTORY).that(value);
// }
//
// private final Integer actual;
//
// private IntegerBitSubject(FailureMetadata failureMetadata, Integer subject) {
// super(failureMetadata, subject);
// this.actual = subject;
// }
//
// @Override
// public void isEqualTo(@Nullable Object other) {
// Object displayObject =
// (other instanceof Integer) ? toBinaryString(((Integer) other).intValue()) : other;
// if (!this.actual.equals(other)) {
// this.failWithActual("expected to be equal to", displayObject);
// }
// }
//
// @Override
// protected String actualCustomStringRepresentation() {
// return toBinaryString(getIntSubject());
// }
//
// private static String toBinaryString(int value) {
// return "0b" + Integer.toBinaryString(value);
// }
//
// private int getIntSubject() {
// return actual.intValue();
// }
// }
// Path: javatests/com/google/zetasketch/internal/hllplus/SparseRepresentationTest.java
import static com.google.common.truth.Truth.assertThat;
import com.google.zetasketch.internal.DifferenceDecoder;
import com.google.zetasketch.testing.IntegerBitIterableSubject;
import com.google.zetasketch.testing.IntegerBitSubject;
import it.unimi.dsi.fastutil.ints.IntIterators;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hllplus;
/**
* Unit tests for the HLL++ {@link SparseRepresentation}.
*
* <p>IMPORTANT: Note that these tests were introduced later and currently don't cover the full
* functionality of SparseRepresentation. All code paths are covered by the more abstract {@link
* com.google.zetasketch.HyperLogLogPlusPlusTest}, however.
*/
// TODO: Remove warning above once unit test coverage is complete.
@RunWith(JUnit4.class)
public final class SparseRepresentationTest {
/**
* Verifies that a sparse value with a higher precision is correctly downgraded to match the
* representation.
*/
@Test
public void addSparseValue_HigherPrecision() {
Representation repr = create(10, 13);
Encoding.Sparse sparseEncoding = new Encoding.Sparse(11, 15);
int sparseValue = 0b000000000011111;
repr = repr.addSparseValue(sparseEncoding, sparseValue).compact();
assertThat(repr.state.precision).isEqualTo(10);
assertThat(repr.state.sparsePrecision).isEqualTo(13); | IntegerBitIterableSubject.assertThat(new DifferenceDecoder(repr.state.sparseData)) |
google/zetasketch | java/com/google/zetasketch/internal/hash/Fingerprint2011.java | // Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64(byte[] input, int offset) {
// // We don't want this in production code as this is the most critical part of the loop.
// assert input.length >= offset + 8;
// // Delegates to the fast (unsafe) version or the fallback.
// return byteArray.getLongLittleEndian(input, offset);
// }
//
// Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64Safely(byte[] input, int offset, int length) {
// long result = 0;
// // Due to the way we shift, we can stop iterating once we've run out of data, the rest
// // of the result already being filled with zeros.
//
// // This loop is critical to performance, so please check HashBenchmark if altering it.
// int limit = Math.min(length, 8);
// for (int i = 0; i < limit; i++) {
// // Shift value left while iterating logically through the array.
// result |= (input[offset + i] & 0xFFL) << (i * 8);
// }
// return result;
// }
| import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64Safely;
import static java.lang.Long.rotateRight;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.HashCode; | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hash;
/**
* Note to maintainers: This implementation relies on signed arithmetic being bit-wise equivalent
* to unsigned arithmetic in all cases except:
*
* <ul>
* <li>comparisons (signed values can be negative)
* <li>division (avoided here)
* <li>shifting (right shift must be unsigned)
* </ul>
*
*/
final class Fingerprint2011 extends AbstractNonStreamingHashFunction {
// Some primes between 2^63 and 2^64 for various uses.
private static final long K0 = 0xa5b85c5e198ed849L;
private static final long K1 = 0x8d58ac26afe12e47L;
private static final long K2 = 0xc47b6e9e3a970ed3L;
private static final long K3 = 0xc6a4a7935bd1e995L;
@Override
public HashCode hashBytes(byte[] input, int off, int len) {
checkPositionIndexes(off, off + len, input.length);
return HashCode.fromLong(fingerprint(input, off, len));
}
@Override
public int bits() {
return 64;
}
@Override
public String toString() {
return "Hashing.fingerprint2011()";
}
// End of public functions.
@VisibleForTesting
static long fingerprint(byte[] bytes, int offset, int length) {
long result;
if (length <= 32) {
result = murmurHash64WithSeed(bytes, offset, length, K0 ^ K1 ^ K2);
} else if (length <= 64) {
result = hashLength33To64(bytes, offset, length);
} else {
result = fullFingerprint(bytes, offset, length);
}
| // Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64(byte[] input, int offset) {
// // We don't want this in production code as this is the most critical part of the loop.
// assert input.length >= offset + 8;
// // Delegates to the fast (unsafe) version or the fallback.
// return byteArray.getLongLittleEndian(input, offset);
// }
//
// Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64Safely(byte[] input, int offset, int length) {
// long result = 0;
// // Due to the way we shift, we can stop iterating once we've run out of data, the rest
// // of the result already being filled with zeros.
//
// // This loop is critical to performance, so please check HashBenchmark if altering it.
// int limit = Math.min(length, 8);
// for (int i = 0; i < limit; i++) {
// // Shift value left while iterating logically through the array.
// result |= (input[offset + i] & 0xFFL) << (i * 8);
// }
// return result;
// }
// Path: java/com/google/zetasketch/internal/hash/Fingerprint2011.java
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64Safely;
import static java.lang.Long.rotateRight;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.HashCode;
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.zetasketch.internal.hash;
/**
* Note to maintainers: This implementation relies on signed arithmetic being bit-wise equivalent
* to unsigned arithmetic in all cases except:
*
* <ul>
* <li>comparisons (signed values can be negative)
* <li>division (avoided here)
* <li>shifting (right shift must be unsigned)
* </ul>
*
*/
final class Fingerprint2011 extends AbstractNonStreamingHashFunction {
// Some primes between 2^63 and 2^64 for various uses.
private static final long K0 = 0xa5b85c5e198ed849L;
private static final long K1 = 0x8d58ac26afe12e47L;
private static final long K2 = 0xc47b6e9e3a970ed3L;
private static final long K3 = 0xc6a4a7935bd1e995L;
@Override
public HashCode hashBytes(byte[] input, int off, int len) {
checkPositionIndexes(off, off + len, input.length);
return HashCode.fromLong(fingerprint(input, off, len));
}
@Override
public int bits() {
return 64;
}
@Override
public String toString() {
return "Hashing.fingerprint2011()";
}
// End of public functions.
@VisibleForTesting
static long fingerprint(byte[] bytes, int offset, int length) {
long result;
if (length <= 32) {
result = murmurHash64WithSeed(bytes, offset, length, K0 ^ K1 ^ K2);
} else if (length <= 64) {
result = hashLength33To64(bytes, offset, length);
} else {
result = fullFingerprint(bytes, offset, length);
}
| long u = length >= 8 ? load64(bytes, offset) : K0; |
google/zetasketch | java/com/google/zetasketch/internal/hash/Fingerprint2011.java | // Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64(byte[] input, int offset) {
// // We don't want this in production code as this is the most critical part of the loop.
// assert input.length >= offset + 8;
// // Delegates to the fast (unsafe) version or the fallback.
// return byteArray.getLongLittleEndian(input, offset);
// }
//
// Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64Safely(byte[] input, int offset, int length) {
// long result = 0;
// // Due to the way we shift, we can stop iterating once we've run out of data, the rest
// // of the result already being filled with zeros.
//
// // This loop is critical to performance, so please check HashBenchmark if altering it.
// int limit = Math.min(length, 8);
// for (int i = 0; i < limit; i++) {
// // Shift value left while iterating logically through the array.
// result |= (input[offset + i] & 0xFFL) << (i * 8);
// }
// return result;
// }
| import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64Safely;
import static java.lang.Long.rotateRight;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.HashCode; | a = load64(bytes, offset + 16) + load64(bytes, offset + length - 32);
z = load64(bytes, offset + length - 8);
b = rotateRight(a + z, 52);
c = rotateRight(a, 37);
a += load64(bytes, offset + length - 24);
c += rotateRight(a, 7);
a += load64(bytes, offset + length - 16);
long wf = a + z;
long ws = b + rotateRight(a, 31) + c;
long r = shiftMix((vf + ws) * K2 + (wf + vs) * K0);
return shiftMix(r * K0 + vs) * K2;
}
@VisibleForTesting
static long murmurHash64WithSeed(byte[] bytes, int offset, int length, long seed) {
final long mul = K3;
final int topBit = 0x7;
int lengthAligned = length & ~topBit;
int lengthRemainder = length & topBit;
long hash = seed ^ (length * mul);
for (int i = 0; i < lengthAligned; i += 8) {
long loaded = load64(bytes, offset + i);
long data = shiftMix(loaded * mul) * mul;
hash ^= data;
hash *= mul;
}
if (lengthRemainder != 0) { | // Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64(byte[] input, int offset) {
// // We don't want this in production code as this is the most critical part of the loop.
// assert input.length >= offset + 8;
// // Delegates to the fast (unsafe) version or the fallback.
// return byteArray.getLongLittleEndian(input, offset);
// }
//
// Path: java/com/google/zetasketch/internal/hash/LittleEndianByteArray.java
// static long load64Safely(byte[] input, int offset, int length) {
// long result = 0;
// // Due to the way we shift, we can stop iterating once we've run out of data, the rest
// // of the result already being filled with zeros.
//
// // This loop is critical to performance, so please check HashBenchmark if altering it.
// int limit = Math.min(length, 8);
// for (int i = 0; i < limit; i++) {
// // Shift value left while iterating logically through the array.
// result |= (input[offset + i] & 0xFFL) << (i * 8);
// }
// return result;
// }
// Path: java/com/google/zetasketch/internal/hash/Fingerprint2011.java
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64;
import static com.google.zetasketch.internal.hash.LittleEndianByteArray.load64Safely;
import static java.lang.Long.rotateRight;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.HashCode;
a = load64(bytes, offset + 16) + load64(bytes, offset + length - 32);
z = load64(bytes, offset + length - 8);
b = rotateRight(a + z, 52);
c = rotateRight(a, 37);
a += load64(bytes, offset + length - 24);
c += rotateRight(a, 7);
a += load64(bytes, offset + length - 16);
long wf = a + z;
long ws = b + rotateRight(a, 31) + c;
long r = shiftMix((vf + ws) * K2 + (wf + vs) * K0);
return shiftMix(r * K0 + vs) * K2;
}
@VisibleForTesting
static long murmurHash64WithSeed(byte[] bytes, int offset, int length, long seed) {
final long mul = K3;
final int topBit = 0x7;
int lengthAligned = length & ~topBit;
int lengthRemainder = length & topBit;
long hash = seed ^ (length * mul);
for (int i = 0; i < lengthAligned; i += 8) {
long loaded = load64(bytes, offset + i);
long data = shiftMix(loaded * mul) * mul;
hash ^= data;
hash *= mul;
}
if (lengthRemainder != 0) { | long data = load64Safely(bytes, offset + lengthAligned, lengthRemainder); |
google/zetasketch | java/com/google/zetasketch/internal/hllplus/Encoding.java | // Path: java/com/google/zetasketch/IncompatiblePrecisionException.java
// public class IncompatiblePrecisionException extends IllegalArgumentException {
// public IncompatiblePrecisionException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 0;
// }
| import com.google.zetasketch.IncompatiblePrecisionException;
import it.unimi.dsi.fastutil.ints.AbstractIntIterator;
import it.unimi.dsi.fastutil.ints.IntIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import javax.annotation.Nullable; | : "normal precision must be between 1 and 24 (inclusive)";
// While for the sparse precision it is 31 - 1 (for flag).
assert 1 <= sparsePrecision && sparsePrecision <= 30
: "sparse precision must be between 1 and 30 (inclusive)";
assert sparsePrecision >= normalPrecision
: "sparse precision must be larger than or equal to the normal precision";
this.normalPrecision = normalPrecision;
this.sparsePrecision = sparsePrecision;
// The position of the flag needs to be larger than any bits that could be used in the rhoW or
// non-rhoW encoded values so that (a) the two values can be distinguished and (b) they will
// not interleave when sorted numerically.
rhoEncodedFlag = 1 << Math.max(sparsePrecision, normalPrecision + RHOW_BITS);
this.normal = new Normal(normalPrecision);
}
/**
* Checks whether a sparse encoding is compatible with another. This encoding's precision and
* sparsePrecision must be both smaller or equal, or both bigger or equal to the {@code other}
* Encoding's precisions for them to be compatible.
*/
public void assertCompatible(Sparse other) {
if ((this.normalPrecision <= other.normalPrecision
&& this.sparsePrecision <= other.sparsePrecision)
|| (this.normalPrecision >= other.normalPrecision
&& this.sparsePrecision >= other.sparsePrecision)) {
return;
} | // Path: java/com/google/zetasketch/IncompatiblePrecisionException.java
// public class IncompatiblePrecisionException extends IllegalArgumentException {
// public IncompatiblePrecisionException(String message) {
// super(message);
// }
//
// private static final long serialVersionUID = 0;
// }
// Path: java/com/google/zetasketch/internal/hllplus/Encoding.java
import com.google.zetasketch.IncompatiblePrecisionException;
import it.unimi.dsi.fastutil.ints.AbstractIntIterator;
import it.unimi.dsi.fastutil.ints.IntIterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import javax.annotation.Nullable;
: "normal precision must be between 1 and 24 (inclusive)";
// While for the sparse precision it is 31 - 1 (for flag).
assert 1 <= sparsePrecision && sparsePrecision <= 30
: "sparse precision must be between 1 and 30 (inclusive)";
assert sparsePrecision >= normalPrecision
: "sparse precision must be larger than or equal to the normal precision";
this.normalPrecision = normalPrecision;
this.sparsePrecision = sparsePrecision;
// The position of the flag needs to be larger than any bits that could be used in the rhoW or
// non-rhoW encoded values so that (a) the two values can be distinguished and (b) they will
// not interleave when sorted numerically.
rhoEncodedFlag = 1 << Math.max(sparsePrecision, normalPrecision + RHOW_BITS);
this.normal = new Normal(normalPrecision);
}
/**
* Checks whether a sparse encoding is compatible with another. This encoding's precision and
* sparsePrecision must be both smaller or equal, or both bigger or equal to the {@code other}
* Encoding's precisions for them to be compatible.
*/
public void assertCompatible(Sparse other) {
if ((this.normalPrecision <= other.normalPrecision
&& this.sparsePrecision <= other.sparsePrecision)
|| (this.normalPrecision >= other.normalPrecision
&& this.sparsePrecision >= other.sparsePrecision)) {
return;
} | throw new IncompatiblePrecisionException( |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/ZeroToBlankTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/ZeroToBlankTransformer.java
// public class ZeroToBlankTransformer implements Transformer {
//
// @Override
// public String transform(String s) {
// String transformed = s;
// if ("0".equals(s)) {
// transformed = "";
// }
// return transformed;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.ZeroToBlankTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class ZeroToBlankTransformerTest {
@Test
public void testSimple() { | // Path: src/main/java/org/kew/rmf/transformers/ZeroToBlankTransformer.java
// public class ZeroToBlankTransformer implements Transformer {
//
// @Override
// public String transform(String s) {
// String transformed = s;
// if ("0".equals(s)) {
// transformed = "";
// }
// return transformed;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/ZeroToBlankTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.ZeroToBlankTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class ZeroToBlankTransformerTest {
@Test
public void testSimple() { | ZeroToBlankTransformer transformer = new ZeroToBlankTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/RegexTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/RegexTransformer.java
// public class RegexTransformer implements Transformer {
//
// private String pattern;
// private Pattern compiledPattern;
// private String replacement = "";
// private boolean removeMultipleWhitespaces = true;
// private boolean trimIt = true;
//
// @Override
// public String transform(String s) {
// s = compiledPattern.matcher(s).replaceAll(getReplacement());
//
// if (this.removeMultipleWhitespaces) {
// s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
// }
//
// if (this.trimIt) {
// s = s.trim();
// }
//
// return s;
// }
//
// public Pattern getCompiledPattern() {
// return compiledPattern;
// }
//
// public String getPattern() {
// return pattern;
// }
// public void setPattern(String pattern) {
// this.pattern = pattern;
// this.compiledPattern = Pattern.compile(pattern);
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
//
// public boolean isRemoveMultipleWhitespaces() {
// return removeMultipleWhitespaces;
// }
// public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) {
// this.removeMultipleWhitespaces = removeMultipleWhitespaces;
// }
//
// public boolean isTrimIt() {
// return trimIt;
// }
// public void setTrimIt(boolean trimIt) {
// this.trimIt = trimIt;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.RegexTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class RegexTransformerTest {
@Test
public void testSimple() { | // Path: src/main/java/org/kew/rmf/transformers/RegexTransformer.java
// public class RegexTransformer implements Transformer {
//
// private String pattern;
// private Pattern compiledPattern;
// private String replacement = "";
// private boolean removeMultipleWhitespaces = true;
// private boolean trimIt = true;
//
// @Override
// public String transform(String s) {
// s = compiledPattern.matcher(s).replaceAll(getReplacement());
//
// if (this.removeMultipleWhitespaces) {
// s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
// }
//
// if (this.trimIt) {
// s = s.trim();
// }
//
// return s;
// }
//
// public Pattern getCompiledPattern() {
// return compiledPattern;
// }
//
// public String getPattern() {
// return pattern;
// }
// public void setPattern(String pattern) {
// this.pattern = pattern;
// this.compiledPattern = Pattern.compile(pattern);
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
//
// public boolean isRemoveMultipleWhitespaces() {
// return removeMultipleWhitespaces;
// }
// public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) {
// this.removeMultipleWhitespaces = removeMultipleWhitespaces;
// }
//
// public boolean isTrimIt() {
// return trimIt;
// }
// public void setTrimIt(boolean trimIt) {
// this.trimIt = trimIt;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/RegexTransformerTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.RegexTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class RegexTransformerTest {
@Test
public void testSimple() { | RegexTransformer transformer = new RegexTransformer(); |
RBGKew/String-Transformers | src/main/java/org/kew/rmf/transformers/collations/ipni/CollationUtils.java | // Path: src/main/java/org/kew/rmf/transformers/collations/CollationStructureTransformer.java
// public class CollationStructureTransformer implements Transformer{
//
// @Override
// public String transform(String s) {
// return assessCollationStructure(s);
// }
//
// private static char[] DASHES = {'\u2012', '\u2013', '\u2014'};
//
// // This converts the extended characters to a normalised equivalent which is more easy to work with:
// // accented e
// // emdashes / emrules (sometimes used in place of hyphens).
// private static String convertExtChars(String str){
// for (char c : DASHES)
// while (str.indexOf(c)!=-1)
// str = str.replace(c, '-');
// while (str.indexOf('\u00E9')!=-1)
// str = str.replace('\u00E9', 'e');
// return str;
// }
//
// public static String[] splitCollation(String collation){
// return convertExtChars(collation).split("[^A-Za-z\u00E90-9\\-]+");
// }
//
// public static String assessCollationStructure(String collation){
// String c_structure = null;
// if (collation != null){
// c_structure = convertExtChars(collation.toLowerCase());
// c_structure=c_structure.replaceAll("1[7-9][0-9][0-9]","YYYY");
// c_structure=c_structure.replaceAll("20[0-1][0-9]","YYYY");
// c_structure=c_structure.replaceAll("[0-9]+","D");
// c_structure=c_structure.replaceAll("[ivxlc]+","R");
// c_structure=c_structure.replaceAll("[a-z\u00E9]+","A");
// c_structure=c_structure.replaceAll("RA","A");
// c_structure=c_structure.replaceAll("AR","A");
// c_structure=c_structure.replaceAll("A+","A");
// // Treat things like 21A as a "number":
// c_structure=c_structure.replaceAll("DA","D");
// // And treat things like 1891A as a "number":
// c_structure=c_structure.replaceAll("YYYYA","D");
// // ...and things like 21C as a "number":
// c_structure=c_structure.replaceAll("DR","D");
// // Treat numeric ranges as a single number:
// c_structure=c_structure.replaceAll("D\\-D","D");
// c_structure=c_structure.toLowerCase();
// }
// return c_structure;
// }
// }
| import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.kew.rmf.transformers.collations.CollationStructureTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.collations.ipni;
public class CollationUtils {
public static int SERIES_INDEX = 0;
public static int VOL_INDEX = 1;
public static int ISSUE_INDEX = 2;
public static int PAGE_INDEX = 3;
public static int TAB_OR_FIG_INDEX = 4;
public static int YEAR_INDEX = 5;
public static int RULE_INDEX = 6;
private static String[] NOTES_PATTERNS={", a.", ", a. a.", ", a a.", ", a a a.", ", a 'a'"};
// This pair of methods provides a way to match collation patterns which have notes, such as ', in obs.'
// at the end, without always explicitly stating these in each test below.
// It has not been used in all the code in the parseCollation method but would make this much more succinct if done so.
//private static boolean patternMatchesWithNotes(String suppliedPattern, String testPattern){
// return patternMatchesWithNotes(suppliedPattern, testPattern, false);
//}
private static boolean patternMatchesWithNotes(String suppliedPattern, String testPattern, boolean normaliseSpace){
boolean matches = false;
for (String suffix :NOTES_PATTERNS){
if (normaliseSpace){
matches = suppliedPattern.replaceAll(" ", "").equals((testPattern+suffix).replaceAll(" ", ""));
}
else{
matches = suppliedPattern.equals(testPattern+suffix);
}
if (matches) break;
}
// if the submitted pattern matches the test pattern with the addition of notes flags, then return true:
return matches;
}
private static String[] splitCollation(String collation){ | // Path: src/main/java/org/kew/rmf/transformers/collations/CollationStructureTransformer.java
// public class CollationStructureTransformer implements Transformer{
//
// @Override
// public String transform(String s) {
// return assessCollationStructure(s);
// }
//
// private static char[] DASHES = {'\u2012', '\u2013', '\u2014'};
//
// // This converts the extended characters to a normalised equivalent which is more easy to work with:
// // accented e
// // emdashes / emrules (sometimes used in place of hyphens).
// private static String convertExtChars(String str){
// for (char c : DASHES)
// while (str.indexOf(c)!=-1)
// str = str.replace(c, '-');
// while (str.indexOf('\u00E9')!=-1)
// str = str.replace('\u00E9', 'e');
// return str;
// }
//
// public static String[] splitCollation(String collation){
// return convertExtChars(collation).split("[^A-Za-z\u00E90-9\\-]+");
// }
//
// public static String assessCollationStructure(String collation){
// String c_structure = null;
// if (collation != null){
// c_structure = convertExtChars(collation.toLowerCase());
// c_structure=c_structure.replaceAll("1[7-9][0-9][0-9]","YYYY");
// c_structure=c_structure.replaceAll("20[0-1][0-9]","YYYY");
// c_structure=c_structure.replaceAll("[0-9]+","D");
// c_structure=c_structure.replaceAll("[ivxlc]+","R");
// c_structure=c_structure.replaceAll("[a-z\u00E9]+","A");
// c_structure=c_structure.replaceAll("RA","A");
// c_structure=c_structure.replaceAll("AR","A");
// c_structure=c_structure.replaceAll("A+","A");
// // Treat things like 21A as a "number":
// c_structure=c_structure.replaceAll("DA","D");
// // And treat things like 1891A as a "number":
// c_structure=c_structure.replaceAll("YYYYA","D");
// // ...and things like 21C as a "number":
// c_structure=c_structure.replaceAll("DR","D");
// // Treat numeric ranges as a single number:
// c_structure=c_structure.replaceAll("D\\-D","D");
// c_structure=c_structure.toLowerCase();
// }
// return c_structure;
// }
// }
// Path: src/main/java/org/kew/rmf/transformers/collations/ipni/CollationUtils.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Arrays;
import org.kew.rmf.transformers.collations.CollationStructureTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.collations.ipni;
public class CollationUtils {
public static int SERIES_INDEX = 0;
public static int VOL_INDEX = 1;
public static int ISSUE_INDEX = 2;
public static int PAGE_INDEX = 3;
public static int TAB_OR_FIG_INDEX = 4;
public static int YEAR_INDEX = 5;
public static int RULE_INDEX = 6;
private static String[] NOTES_PATTERNS={", a.", ", a. a.", ", a a.", ", a a a.", ", a 'a'"};
// This pair of methods provides a way to match collation patterns which have notes, such as ', in obs.'
// at the end, without always explicitly stating these in each test below.
// It has not been used in all the code in the parseCollation method but would make this much more succinct if done so.
//private static boolean patternMatchesWithNotes(String suppliedPattern, String testPattern){
// return patternMatchesWithNotes(suppliedPattern, testPattern, false);
//}
private static boolean patternMatchesWithNotes(String suppliedPattern, String testPattern, boolean normaliseSpace){
boolean matches = false;
for (String suffix :NOTES_PATTERNS){
if (normaliseSpace){
matches = suppliedPattern.replaceAll(" ", "").equals((testPattern+suffix).replaceAll(" ", ""));
}
else{
matches = suppliedPattern.equals(testPattern+suffix);
}
if (matches) break;
}
// if the submitted pattern matches the test pattern with the addition of notes flags, then return true:
return matches;
}
private static String[] splitCollation(String collation){ | return CollationStructureTransformer.splitCollation(collation); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/YearRangeExtractorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/YearRangeExtractorTransformer.java
// public class YearRangeExtractorTransformer implements Transformer {
//
// private final Pattern yearsRegex = Pattern.compile("\\b(1[6789]\\d\\d|20[012]\\d)([–—-]\\b|\\b\\+|\\b)");
//
// @Override
// public String transform(String s) {
// StringBuffer sb = new StringBuffer();
// if (s != null) {
// Matcher m = yearsRegex.matcher(s);
// while (m.find()) {
// String match = m.group();
// match = match.replace('–', '-'); // en-dash
// match = match.replace('—', '-'); // em-dash
// sb.append(match);
// if (!match.endsWith("-")) {
// sb.append(" ");
// }
// }
// }
// return sb.toString().trim();
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.YearRangeExtractorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class YearRangeExtractorTransformerTest {
@Test
public void testSimple() { | // Path: src/main/java/org/kew/rmf/transformers/YearRangeExtractorTransformer.java
// public class YearRangeExtractorTransformer implements Transformer {
//
// private final Pattern yearsRegex = Pattern.compile("\\b(1[6789]\\d\\d|20[012]\\d)([–—-]\\b|\\b\\+|\\b)");
//
// @Override
// public String transform(String s) {
// StringBuffer sb = new StringBuffer();
// if (s != null) {
// Matcher m = yearsRegex.matcher(s);
// while (m.find()) {
// String match = m.group();
// match = match.replace('–', '-'); // en-dash
// match = match.replace('—', '-'); // em-dash
// sb.append(match);
// if (!match.endsWith("-")) {
// sb.append(" ");
// }
// }
// }
// return sb.toString().trim();
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/YearRangeExtractorTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.YearRangeExtractorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class YearRangeExtractorTransformerTest {
@Test
public void testSimple() { | YearRangeExtractorTransformer transformer = new YearRangeExtractorTransformer(); |
RBGKew/String-Transformers | src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
| import java.util.regex.Pattern;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.Transformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer translates author strings in the form "(Author1) Author2" to "Author2"
*/
public class StripBasionymAuthorTransformer implements Transformer {
private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)"); | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
// Path: src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java
import java.util.regex.Pattern;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.Transformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer translates author strings in the form "(Author1) Author2" to "Author2"
*/
public class StripBasionymAuthorTransformer implements Transformer {
private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)"); | private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/SurnameExtractorTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/SurnameExtractor.java
// public class SurnameExtractor implements Transformer {
//
// private Pattern linnaeusRemoveDot = Pattern.compile("L\\.(?=\\s)");
// private Pattern surnameExtractorPattern = Pattern.compile("(?<!\\p{L})(-*\\p{L}\\.\\s*)(?=[^$\\)])");
// private Pattern linnaeusAddDot = Pattern.compile("L ");
//
// @Override
// public String transform(String s) {
// // Linnaeus special: first we remove the Dot after "L" in order to make it appear as a surname,
// // but only where it's very likely to be Linnaeus; afterwards we'll add it again.
// s = linnaeusRemoveDot.matcher(s).replaceAll("L ");
//
// s = surnameExtractorPattern.matcher(s).replaceAll("");
//
// s = linnaeusAddDot.matcher(s).replaceAll("L.");
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.SurnameExtractor; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class SurnameExtractorTest {
@Test
public void extractSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/SurnameExtractor.java
// public class SurnameExtractor implements Transformer {
//
// private Pattern linnaeusRemoveDot = Pattern.compile("L\\.(?=\\s)");
// private Pattern surnameExtractorPattern = Pattern.compile("(?<!\\p{L})(-*\\p{L}\\.\\s*)(?=[^$\\)])");
// private Pattern linnaeusAddDot = Pattern.compile("L ");
//
// @Override
// public String transform(String s) {
// // Linnaeus special: first we remove the Dot after "L" in order to make it appear as a surname,
// // but only where it's very likely to be Linnaeus; afterwards we'll add it again.
// s = linnaeusRemoveDot.matcher(s).replaceAll("L ");
//
// s = surnameExtractorPattern.matcher(s).replaceAll("");
//
// s = linnaeusAddDot.matcher(s).replaceAll("L.");
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/SurnameExtractorTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.SurnameExtractor;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class SurnameExtractorTest {
@Test
public void extractSimple() throws Exception { | Transformer transformer = new SurnameExtractor(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/SurnameExtractorTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/SurnameExtractor.java
// public class SurnameExtractor implements Transformer {
//
// private Pattern linnaeusRemoveDot = Pattern.compile("L\\.(?=\\s)");
// private Pattern surnameExtractorPattern = Pattern.compile("(?<!\\p{L})(-*\\p{L}\\.\\s*)(?=[^$\\)])");
// private Pattern linnaeusAddDot = Pattern.compile("L ");
//
// @Override
// public String transform(String s) {
// // Linnaeus special: first we remove the Dot after "L" in order to make it appear as a surname,
// // but only where it's very likely to be Linnaeus; afterwards we'll add it again.
// s = linnaeusRemoveDot.matcher(s).replaceAll("L ");
//
// s = surnameExtractorPattern.matcher(s).replaceAll("");
//
// s = linnaeusAddDot.matcher(s).replaceAll("L.");
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.SurnameExtractor; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class SurnameExtractorTest {
@Test
public void extractSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/SurnameExtractor.java
// public class SurnameExtractor implements Transformer {
//
// private Pattern linnaeusRemoveDot = Pattern.compile("L\\.(?=\\s)");
// private Pattern surnameExtractorPattern = Pattern.compile("(?<!\\p{L})(-*\\p{L}\\.\\s*)(?=[^$\\)])");
// private Pattern linnaeusAddDot = Pattern.compile("L ");
//
// @Override
// public String transform(String s) {
// // Linnaeus special: first we remove the Dot after "L" in order to make it appear as a surname,
// // but only where it's very likely to be Linnaeus; afterwards we'll add it again.
// s = linnaeusRemoveDot.matcher(s).replaceAll("L ");
//
// s = surnameExtractorPattern.matcher(s).replaceAll("");
//
// s = linnaeusAddDot.matcher(s).replaceAll("L.");
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/SurnameExtractorTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.SurnameExtractor;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class SurnameExtractorTest {
@Test
public void extractSimple() throws Exception { | Transformer transformer = new SurnameExtractor(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/CleanedPubAuthorsTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/CleanedPubAuthors.java
// public class CleanedPubAuthors implements Transformer {
//
// @Override
// public String transform (String s) {
// s = new StripBasionymAuthorTransformer().transform(s);
// s = new StripExAuthorTransformer().transform(s);
// return new StripInAuthorTransformer().transform(s);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.CleanedPubAuthors; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class CleanedPubAuthorsTest {
@Test
public void cleanIt() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/CleanedPubAuthors.java
// public class CleanedPubAuthors implements Transformer {
//
// @Override
// public String transform (String s) {
// s = new StripBasionymAuthorTransformer().transform(s);
// s = new StripExAuthorTransformer().transform(s);
// return new StripInAuthorTransformer().transform(s);
// }
//
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/CleanedPubAuthorsTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.CleanedPubAuthors;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class CleanedPubAuthorsTest {
@Test
public void cleanIt() throws Exception { | Transformer transformer = new CleanedPubAuthors(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/CleanedPubAuthorsTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/CleanedPubAuthors.java
// public class CleanedPubAuthors implements Transformer {
//
// @Override
// public String transform (String s) {
// s = new StripBasionymAuthorTransformer().transform(s);
// s = new StripExAuthorTransformer().transform(s);
// return new StripInAuthorTransformer().transform(s);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.CleanedPubAuthors; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class CleanedPubAuthorsTest {
@Test
public void cleanIt() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/CleanedPubAuthors.java
// public class CleanedPubAuthors implements Transformer {
//
// @Override
// public String transform (String s) {
// s = new StripBasionymAuthorTransformer().transform(s);
// s = new StripExAuthorTransformer().transform(s);
// return new StripInAuthorTransformer().transform(s);
// }
//
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/CleanedPubAuthorsTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.CleanedPubAuthors;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class CleanedPubAuthorsTest {
@Test
public void cleanIt() throws Exception { | Transformer transformer = new CleanedPubAuthors(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/ShrunkPubAuthorsTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkPubAuthors.java
// public class ShrunkPubAuthors implements Transformer {
//
// private ShrunkAuthors shrunkAuthors = new ShrunkAuthors();
// private CleanedPubAuthors cleanedPubAuthors = new CleanedPubAuthors();
//
// @Override
// public String transform(String s) {
// s = cleanedPubAuthors.transform(s);
// s = shrunkAuthors.transform(s);
// return s;
// }
//
// public Integer getShrinkTo() {
// return shrunkAuthors.getShrinkTo();
// }
// public void setShrinkTo(int shrinkTo) {
// shrunkAuthors.setShrinkTo(shrinkTo);
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.ShrunkPubAuthors; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkPubAuthorsTest {
@Test
public void shrinkEm() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkPubAuthors.java
// public class ShrunkPubAuthors implements Transformer {
//
// private ShrunkAuthors shrunkAuthors = new ShrunkAuthors();
// private CleanedPubAuthors cleanedPubAuthors = new CleanedPubAuthors();
//
// @Override
// public String transform(String s) {
// s = cleanedPubAuthors.transform(s);
// s = shrunkAuthors.transform(s);
// return s;
// }
//
// public Integer getShrinkTo() {
// return shrunkAuthors.getShrinkTo();
// }
// public void setShrinkTo(int shrinkTo) {
// shrunkAuthors.setShrinkTo(shrinkTo);
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/ShrunkPubAuthorsTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.ShrunkPubAuthors;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkPubAuthorsTest {
@Test
public void shrinkEm() throws Exception { | Transformer transformer = new ShrunkPubAuthors(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/ShrunkPubAuthorsTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkPubAuthors.java
// public class ShrunkPubAuthors implements Transformer {
//
// private ShrunkAuthors shrunkAuthors = new ShrunkAuthors();
// private CleanedPubAuthors cleanedPubAuthors = new CleanedPubAuthors();
//
// @Override
// public String transform(String s) {
// s = cleanedPubAuthors.transform(s);
// s = shrunkAuthors.transform(s);
// return s;
// }
//
// public Integer getShrinkTo() {
// return shrunkAuthors.getShrinkTo();
// }
// public void setShrinkTo(int shrinkTo) {
// shrunkAuthors.setShrinkTo(shrinkTo);
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.ShrunkPubAuthors; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkPubAuthorsTest {
@Test
public void shrinkEm() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkPubAuthors.java
// public class ShrunkPubAuthors implements Transformer {
//
// private ShrunkAuthors shrunkAuthors = new ShrunkAuthors();
// private CleanedPubAuthors cleanedPubAuthors = new CleanedPubAuthors();
//
// @Override
// public String transform(String s) {
// s = cleanedPubAuthors.transform(s);
// s = shrunkAuthors.transform(s);
// return s;
// }
//
// public Integer getShrinkTo() {
// return shrunkAuthors.getShrinkTo();
// }
// public void setShrinkTo(int shrinkTo) {
// shrunkAuthors.setShrinkTo(shrinkTo);
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/ShrunkPubAuthorsTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.ShrunkPubAuthors;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkPubAuthorsTest {
@Test
public void shrinkEm() throws Exception { | Transformer transformer = new ShrunkPubAuthors(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/RegexExtractorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/RegexExtractorTransformer.java
// public class RegexExtractorTransformer implements Transformer {
//
// private Pattern regex;
// private boolean removeMultipleWhitespaces = true;
// private boolean trimIt = true;
//
// @Override
// public String transform(String s) {
// StringBuilder sb = new StringBuilder();
// if (s != null){
// if (this.removeMultipleWhitespaces) {
// s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
// }
// if (this.trimIt) {
// s = s.trim();
// }
//
// Matcher m = regex.matcher(s);
// while (m.find()){
// if (sb.length() > 0) sb.append(" ");
// sb.append(m.group());
// }
// }
// return sb.toString();
// }
//
// public String getRegex() {
// return regex.pattern();
// }
// public void setRegex(String regex) {
// this.regex = Pattern.compile("(" + regex + ")");
// }
//
// public boolean isRemoveMultipleWhitespaces() {
// return removeMultipleWhitespaces;
// }
// public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) {
// this.removeMultipleWhitespaces = removeMultipleWhitespaces;
// }
//
// public boolean isTrimIt() {
// return trimIt;
// }
// public void setTrimIt(boolean trimIt) {
// this.trimIt = trimIt;
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.RegexExtractorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class RegexExtractorTransformerTest {
@Test
public void test() { | // Path: src/main/java/org/kew/rmf/transformers/RegexExtractorTransformer.java
// public class RegexExtractorTransformer implements Transformer {
//
// private Pattern regex;
// private boolean removeMultipleWhitespaces = true;
// private boolean trimIt = true;
//
// @Override
// public String transform(String s) {
// StringBuilder sb = new StringBuilder();
// if (s != null){
// if (this.removeMultipleWhitespaces) {
// s = SqueezeWhitespaceTransformer.MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ");
// }
// if (this.trimIt) {
// s = s.trim();
// }
//
// Matcher m = regex.matcher(s);
// while (m.find()){
// if (sb.length() > 0) sb.append(" ");
// sb.append(m.group());
// }
// }
// return sb.toString();
// }
//
// public String getRegex() {
// return regex.pattern();
// }
// public void setRegex(String regex) {
// this.regex = Pattern.compile("(" + regex + ")");
// }
//
// public boolean isRemoveMultipleWhitespaces() {
// return removeMultipleWhitespaces;
// }
// public void setRemoveMultipleWhitespaces(boolean removeMultipleWhitespaces) {
// this.removeMultipleWhitespaces = removeMultipleWhitespaces;
// }
//
// public boolean isTrimIt() {
// return trimIt;
// }
// public void setTrimIt(boolean trimIt) {
// this.trimIt = trimIt;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/RegexExtractorTransformerTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.RegexExtractorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class RegexExtractorTransformerTest {
@Test
public void test() { | RegexExtractorTransformer transformer = new RegexExtractorTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/DictionaryTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/DictionaryTransformer.java
// public class DictionaryTransformer implements Transformer {
//
// Dictionary dictionary;
//
// @Override
// public String transform(String s) throws TransformationException {
// String value = this.dictionary.get(s);
// return (value != null) ? value : s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryTransformerTest {
public class TestDictionary extends HashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test | // Path: src/main/java/org/kew/rmf/transformers/DictionaryTransformer.java
// public class DictionaryTransformer implements Transformer {
//
// Dictionary dictionary;
//
// @Override
// public String transform(String s) throws TransformationException {
// String value = this.dictionary.get(s);
// return (value != null) ? value : s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
// Path: src/test/java/org/kew/rmf/transformers/DictionaryTransformerTest.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryTransformerTest {
public class TestDictionary extends HashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test | public void test() throws IOException, TransformationException { |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/DictionaryTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/DictionaryTransformer.java
// public class DictionaryTransformer implements Transformer {
//
// Dictionary dictionary;
//
// @Override
// public String transform(String s) throws TransformationException {
// String value = this.dictionary.get(s);
// return (value != null) ? value : s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryTransformerTest {
public class TestDictionary extends HashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test
public void test() throws IOException, TransformationException {
Dictionary dict = new TestDictionary();
| // Path: src/main/java/org/kew/rmf/transformers/DictionaryTransformer.java
// public class DictionaryTransformer implements Transformer {
//
// Dictionary dictionary;
//
// @Override
// public String transform(String s) throws TransformationException {
// String value = this.dictionary.get(s);
// return (value != null) ? value : s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
// Path: src/test/java/org/kew/rmf/transformers/DictionaryTransformerTest.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryTransformerTest {
public class TestDictionary extends HashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test
public void test() throws IOException, TransformationException {
Dictionary dict = new TestDictionary();
| DictionaryTransformer transformer = new DictionaryTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/botany/FakeHybridSignCleanerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/botany/FakeHybridSignCleaner.java
// public class FakeHybridSignCleaner extends RegexTransformer {
//
// public FakeHybridSignCleaner() {
// setPattern("^[Xx]\\s|\\s[xX]\\s");
// setReplacement(" ");
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.botany.FakeHybridSignCleaner; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.botany;
public class FakeHybridSignCleanerTest {
@Test
public void test() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/botany/FakeHybridSignCleaner.java
// public class FakeHybridSignCleaner extends RegexTransformer {
//
// public FakeHybridSignCleaner() {
// setPattern("^[Xx]\\s|\\s[xX]\\s");
// setReplacement(" ");
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/botany/FakeHybridSignCleanerTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.botany.FakeHybridSignCleaner;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.botany;
public class FakeHybridSignCleanerTest {
@Test
public void test() throws Exception { | Transformer transformer = new FakeHybridSignCleaner(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/botany/FakeHybridSignCleanerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/botany/FakeHybridSignCleaner.java
// public class FakeHybridSignCleaner extends RegexTransformer {
//
// public FakeHybridSignCleaner() {
// setPattern("^[Xx]\\s|\\s[xX]\\s");
// setReplacement(" ");
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.botany.FakeHybridSignCleaner; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.botany;
public class FakeHybridSignCleanerTest {
@Test
public void test() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/botany/FakeHybridSignCleaner.java
// public class FakeHybridSignCleaner extends RegexTransformer {
//
// public FakeHybridSignCleaner() {
// setPattern("^[Xx]\\s|\\s[xX]\\s");
// setReplacement(" ");
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/botany/FakeHybridSignCleanerTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.botany.FakeHybridSignCleaner;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.botany;
public class FakeHybridSignCleanerTest {
@Test
public void test() throws Exception { | Transformer transformer = new FakeHybridSignCleaner(); |
RBGKew/String-Transformers | src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
| // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
| private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer(); |
RBGKew/String-Transformers | src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer(); | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer(); | private StripNonAlphanumericCharactersTransformer safeStripNonAlphanumerics = new StripNonAlphanumericCharactersTransformer(); |
RBGKew/String-Transformers | src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java | // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
private StripNonAlphanumericCharactersTransformer safeStripNonAlphanumerics = new StripNonAlphanumericCharactersTransformer();
| // Path: src/main/java/org/kew/rmf/transformers/SqueezeWhitespaceTransformer.java
// public class SqueezeWhitespaceTransformer implements Transformer {
//
// protected static final Pattern MULTIPLE_WHITESPACE = Pattern.compile("\\s+");
//
// @Override
// public String transform(String s) {
// return MULTIPLE_WHITESPACE.matcher(s).replaceAll(" ").trim();
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StringShrinkerTransformer.java
// public class StringShrinkerTransformer implements Transformer {
//
// private int length = Integer.MAX_VALUE;
//
// @Override
// public String transform(String s) {
// if (s.length() > this.length) s = s.substring(0, this.length);
// return s;
// }
//
// public Integer getLength() {
// return length;
// }
// public void setLength(int length) {
// this.length = length;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/StripNonAlphanumericCharactersTransformer.java
// public class StripNonAlphanumericCharactersTransformer implements Transformer {
//
// private NormaliseDiacriticalMarksTransformer normaliseDiacriticalMarksTransformer = new NormaliseDiacriticalMarksTransformer();
// private SqueezeWhitespaceTransformer squeezeWhitespaceTransformer = new SqueezeWhitespaceTransformer();
//
// private final Pattern nonAlphanumeric = Pattern.compile("[^\\p{L}\\p{N}]");
// private String replacement = " ";
//
// @Override
// public String transform(String s) {
// s = normaliseDiacriticalMarksTransformer.transform(s);
// s = nonAlphanumeric.matcher(s).replaceAll(replacement);
// s = squeezeWhitespaceTransformer.transform(s);
// return s.trim();
// }
//
// public String getReplacement() {
// return replacement;
// }
// public void setReplacement(String replacement) {
// this.replacement = replacement;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
// Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.kew.rmf.transformers.SqueezeWhitespaceTransformer;
import org.kew.rmf.transformers.StringShrinkerTransformer;
import org.kew.rmf.transformers.StripNonAlphanumericCharactersTransformer;
import org.kew.rmf.transformers.Transformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
/**
* This transformer tries to identify <strong>all</strong> authors (accepts publishing-,
* basionym-, ex-, in-) of plant names in a string and returns a string where
* each of their surnames are shrunk/cropped to a length
* of {@link #setShrinkTo(int)}.
*/
/*
* For examples of standard usage and corner cases see {@link ShrunkAuthorsTest}
*/
public class ShrunkAuthors implements Transformer {
private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
private SurnameExtractor surnameExtractor = new SurnameExtractor();
private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
private StripNonAlphanumericCharactersTransformer safeStripNonAlphanumerics = new StripNonAlphanumericCharactersTransformer();
| private StringShrinkerTransformer stringShrinker = new StringShrinkerTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/DictionaryRegexTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/DictionaryRegexTransformer.java
// public class DictionaryRegexTransformer implements Transformer {
//
// private Dictionary dictionary;
// private boolean multiTransform = false;
//
// private List<Pattern> patterns = new ArrayList<>();
// private List<String> replacements = new ArrayList<>();
//
// @Override
// public String transform(String s) throws TransformationException {
// for (int i = 0; i < patterns.size(); i++) {
// Pattern p = patterns.get(i);
// String r = replacements.get(i);
//
// Matcher m = p.matcher(s);
// if (m.find()) {
// s = m.replaceAll(r);
// if (this.multiTransform == false) return s;
// }
// }
// return s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
//
// for (Map.Entry<String, String> entry : this.dictionary.entrySet()) {
// Pattern p = Pattern.compile(entry.getKey());
// patterns.add(p);
// replacements.add(entry.getValue());
// }
// }
//
// public boolean isMultiTransform() {
// return multiTransform;
// }
// public void setMultiTransform(boolean multiTransform) {
// this.multiTransform = multiTransform;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryRegexTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryRegexTransformerTest {
public class TestDictionary extends LinkedHashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test | // Path: src/main/java/org/kew/rmf/transformers/DictionaryRegexTransformer.java
// public class DictionaryRegexTransformer implements Transformer {
//
// private Dictionary dictionary;
// private boolean multiTransform = false;
//
// private List<Pattern> patterns = new ArrayList<>();
// private List<String> replacements = new ArrayList<>();
//
// @Override
// public String transform(String s) throws TransformationException {
// for (int i = 0; i < patterns.size(); i++) {
// Pattern p = patterns.get(i);
// String r = replacements.get(i);
//
// Matcher m = p.matcher(s);
// if (m.find()) {
// s = m.replaceAll(r);
// if (this.multiTransform == false) return s;
// }
// }
// return s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
//
// for (Map.Entry<String, String> entry : this.dictionary.entrySet()) {
// Pattern p = Pattern.compile(entry.getKey());
// patterns.add(p);
// replacements.add(entry.getValue());
// }
// }
//
// public boolean isMultiTransform() {
// return multiTransform;
// }
// public void setMultiTransform(boolean multiTransform) {
// this.multiTransform = multiTransform;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
// Path: src/test/java/org/kew/rmf/transformers/DictionaryRegexTransformerTest.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryRegexTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryRegexTransformerTest {
public class TestDictionary extends LinkedHashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test | public void test() throws IOException, TransformationException { |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/DictionaryRegexTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/DictionaryRegexTransformer.java
// public class DictionaryRegexTransformer implements Transformer {
//
// private Dictionary dictionary;
// private boolean multiTransform = false;
//
// private List<Pattern> patterns = new ArrayList<>();
// private List<String> replacements = new ArrayList<>();
//
// @Override
// public String transform(String s) throws TransformationException {
// for (int i = 0; i < patterns.size(); i++) {
// Pattern p = patterns.get(i);
// String r = replacements.get(i);
//
// Matcher m = p.matcher(s);
// if (m.find()) {
// s = m.replaceAll(r);
// if (this.multiTransform == false) return s;
// }
// }
// return s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
//
// for (Map.Entry<String, String> entry : this.dictionary.entrySet()) {
// Pattern p = Pattern.compile(entry.getKey());
// patterns.add(p);
// replacements.add(entry.getValue());
// }
// }
//
// public boolean isMultiTransform() {
// return multiTransform;
// }
// public void setMultiTransform(boolean multiTransform) {
// this.multiTransform = multiTransform;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryRegexTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryRegexTransformerTest {
public class TestDictionary extends LinkedHashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test
public void test() throws IOException, TransformationException {
Dictionary dict = new TestDictionary();
| // Path: src/main/java/org/kew/rmf/transformers/DictionaryRegexTransformer.java
// public class DictionaryRegexTransformer implements Transformer {
//
// private Dictionary dictionary;
// private boolean multiTransform = false;
//
// private List<Pattern> patterns = new ArrayList<>();
// private List<String> replacements = new ArrayList<>();
//
// @Override
// public String transform(String s) throws TransformationException {
// for (int i = 0; i < patterns.size(); i++) {
// Pattern p = patterns.get(i);
// String r = replacements.get(i);
//
// Matcher m = p.matcher(s);
// if (m.find()) {
// s = m.replaceAll(r);
// if (this.multiTransform == false) return s;
// }
// }
// return s;
// }
//
// public Dictionary getDictionary() {
// return dictionary;
// }
// public void setDictionary(Dictionary dictionary) {
// this.dictionary = dictionary;
//
// for (Map.Entry<String, String> entry : this.dictionary.entrySet()) {
// Pattern p = Pattern.compile(entry.getKey());
// patterns.add(p);
// replacements.add(entry.getValue());
// }
// }
//
// public boolean isMultiTransform() {
// return multiTransform;
// }
// public void setMultiTransform(boolean multiTransform) {
// this.multiTransform = multiTransform;
// }
// }
//
// Path: src/main/java/org/kew/rmf/transformers/TransformationException.java
// public class TransformationException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public TransformationException() {
// super();
// }
//
// public TransformationException(String message) {
// super(message);
// }
//
// public TransformationException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/kew/rmf/utils/Dictionary.java
// public interface Dictionary {
// public Set<Map.Entry<String,String>> entrySet();
// public String get(String key);
// }
// Path: src/test/java/org/kew/rmf/transformers/DictionaryRegexTransformerTest.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.LinkedHashMap;
import org.junit.Test;
import org.kew.rmf.transformers.DictionaryRegexTransformer;
import org.kew.rmf.transformers.TransformationException;
import org.kew.rmf.utils.Dictionary;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers;
public class DictionaryRegexTransformerTest {
public class TestDictionary extends LinkedHashMap<String,String> implements Dictionary {
private static final long serialVersionUID = 1L;
public TestDictionary() {
put("a", "b");
put("c", "d");
}
@Override
public String get(String key) {
return super.get(key);
}
}
@Test
public void test() throws IOException, TransformationException {
Dictionary dict = new TestDictionary();
| DictionaryRegexTransformer transformer = new DictionaryRegexTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java
// public class StripBasionymAuthorTransformer implements Transformer {
//
// private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)");
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// // replace ALL bits in brackets, then remove double whitespaces and surrounding whitespaces
// s = bitsInBrackets.matcher(s).replaceAll(" ");
// s = shrinkWhitespace.transform(s);
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripBasionymAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java
// public class StripBasionymAuthorTransformer implements Transformer {
//
// private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)");
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// // replace ALL bits in brackets, then remove double whitespaces and surrounding whitespaces
// s = bitsInBrackets.matcher(s).replaceAll(" ");
// s = shrinkWhitespace.transform(s);
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripBasionymAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | Transformer transformer = new StripBasionymAuthorTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java
// public class StripBasionymAuthorTransformer implements Transformer {
//
// private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)");
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// // replace ALL bits in brackets, then remove double whitespaces and surrounding whitespaces
// s = bitsInBrackets.matcher(s).replaceAll(" ");
// s = shrinkWhitespace.transform(s);
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripBasionymAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformer.java
// public class StripBasionymAuthorTransformer implements Transformer {
//
// private Pattern bitsInBrackets = Pattern.compile("\\([^)]*\\)");
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// // replace ALL bits in brackets, then remove double whitespaces and surrounding whitespaces
// s = bitsInBrackets.matcher(s).replaceAll(" ");
// s = shrinkWhitespace.transform(s);
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/StripBasionymAuthorTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripBasionymAuthorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripBasionymAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | Transformer transformer = new StripBasionymAuthorTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/StripExAuthorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripExAuthorTransformer.java
// public class StripExAuthorTransformer implements Transformer{
//
// // TODO: Check this is general enough, e.g. word boundaries instead?
// protected static final String EX_MARKER = " ex ";
// protected static final String EX_MARKER_REGEX = "( [Ee][Xx] )";
//
// private Pattern exPattern = Pattern.compile(".*" + EX_MARKER_REGEX);
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// if (s.toLowerCase(Locale.ENGLISH).indexOf(EX_MARKER) != -1) {
// s = exPattern.matcher(s).replaceAll("");
// }
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripExAuthorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripExAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripExAuthorTransformer.java
// public class StripExAuthorTransformer implements Transformer{
//
// // TODO: Check this is general enough, e.g. word boundaries instead?
// protected static final String EX_MARKER = " ex ";
// protected static final String EX_MARKER_REGEX = "( [Ee][Xx] )";
//
// private Pattern exPattern = Pattern.compile(".*" + EX_MARKER_REGEX);
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// if (s.toLowerCase(Locale.ENGLISH).indexOf(EX_MARKER) != -1) {
// s = exPattern.matcher(s).replaceAll("");
// }
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/StripExAuthorTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripExAuthorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripExAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | Transformer transformer = new StripExAuthorTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/StripExAuthorTransformerTest.java | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripExAuthorTransformer.java
// public class StripExAuthorTransformer implements Transformer{
//
// // TODO: Check this is general enough, e.g. word boundaries instead?
// protected static final String EX_MARKER = " ex ";
// protected static final String EX_MARKER_REGEX = "( [Ee][Xx] )";
//
// private Pattern exPattern = Pattern.compile(".*" + EX_MARKER_REGEX);
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// if (s.toLowerCase(Locale.ENGLISH).indexOf(EX_MARKER) != -1) {
// s = exPattern.matcher(s).replaceAll("");
// }
// return s;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripExAuthorTransformer; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripExAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | // Path: src/main/java/org/kew/rmf/transformers/Transformer.java
// public interface Transformer {
// /**
// * Transform <code>s</code> into another String.
// * @param s The string to transform
// * @return The transformed string
// * @throws TransformationException If there is a problem with the transformer, e.g. unable to load external resource.
// */
// public String transform(String s) throws TransformationException;
// }
//
// Path: src/main/java/org/kew/rmf/transformers/authors/StripExAuthorTransformer.java
// public class StripExAuthorTransformer implements Transformer{
//
// // TODO: Check this is general enough, e.g. word boundaries instead?
// protected static final String EX_MARKER = " ex ";
// protected static final String EX_MARKER_REGEX = "( [Ee][Xx] )";
//
// private Pattern exPattern = Pattern.compile(".*" + EX_MARKER_REGEX);
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// if (s.toLowerCase(Locale.ENGLISH).indexOf(EX_MARKER) != -1) {
// s = exPattern.matcher(s).replaceAll("");
// }
// return s;
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/StripExAuthorTransformerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.kew.rmf.transformers.Transformer;
import org.kew.rmf.transformers.authors.StripExAuthorTransformer;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class StripExAuthorTransformerTest {
@Test
public void stripItSimple() throws Exception { | Transformer transformer = new StripExAuthorTransformer(); |
RBGKew/String-Transformers | src/test/java/org/kew/rmf/transformers/authors/ShrunkAuthorsTest.java | // Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java
// public class ShrunkAuthors implements Transformer {
//
// private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
// private SurnameExtractor surnameExtractor = new SurnameExtractor();
//
// private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
// private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
//
// private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
//
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
// private StripNonAlphanumericCharactersTransformer safeStripNonAlphanumerics = new StripNonAlphanumericCharactersTransformer();
//
// private StringShrinkerTransformer stringShrinker = new StringShrinkerTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// s = dotFDotCleaner.transform(s);
// s = surnameExtractor.transform(s);
//
// String pub = stripBasionymAuthor.transform(s);
// String bas = stripPublishingAuthor.transform(s);
//
// List<String> surnames = new ArrayList<>();
// for (String authors : new String[] {bas, pub}) {
// authors = inEx.matcher(authors).replaceAll(" ");
// authors = shrinkWhitespace.transform(authors);
// authors = safeStripNonAlphanumerics.transform(authors);
// for (String author : authors.split(" ")) {
// // shrink each identified author surname to shrinkTo if set
// author = stringShrinker.transform(author);
// author = author.trim();
// if (author.length() > 0) {
// surnames.add(author);
// }
// }
// }
// return StringUtils.join(surnames, " ").toLowerCase(Locale.ENGLISH);
// }
//
// public Integer getShrinkTo() {
// return stringShrinker.getLength();
// }
// public void setShrinkTo(int shrinkTo) {
// stringShrinker.setLength(shrinkTo);
// }
// }
| import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.authors.ShrunkAuthors; | /*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkAuthorsTest {
@Test
public void need_to_remove_initials() { | // Path: src/main/java/org/kew/rmf/transformers/authors/ShrunkAuthors.java
// public class ShrunkAuthors implements Transformer {
//
// private DotFDotCleaner dotFDotCleaner = new DotFDotCleaner();
// private SurnameExtractor surnameExtractor = new SurnameExtractor();
//
// private StripBasionymAuthorTransformer stripBasionymAuthor =new StripBasionymAuthorTransformer();
// private StripPublishingAuthorTransformer stripPublishingAuthor = new StripPublishingAuthorTransformer();
//
// private Pattern inEx = Pattern.compile(StripExAuthorTransformer.EX_MARKER_REGEX + "|" + StripInAuthorTransformer.IN_MARKER_REGEX);
//
// private SqueezeWhitespaceTransformer shrinkWhitespace = new SqueezeWhitespaceTransformer();
// private StripNonAlphanumericCharactersTransformer safeStripNonAlphanumerics = new StripNonAlphanumericCharactersTransformer();
//
// private StringShrinkerTransformer stringShrinker = new StringShrinkerTransformer();
//
// @Override
// public String transform(String s) {
// if (s == null) return null;
//
// s = dotFDotCleaner.transform(s);
// s = surnameExtractor.transform(s);
//
// String pub = stripBasionymAuthor.transform(s);
// String bas = stripPublishingAuthor.transform(s);
//
// List<String> surnames = new ArrayList<>();
// for (String authors : new String[] {bas, pub}) {
// authors = inEx.matcher(authors).replaceAll(" ");
// authors = shrinkWhitespace.transform(authors);
// authors = safeStripNonAlphanumerics.transform(authors);
// for (String author : authors.split(" ")) {
// // shrink each identified author surname to shrinkTo if set
// author = stringShrinker.transform(author);
// author = author.trim();
// if (author.length() > 0) {
// surnames.add(author);
// }
// }
// }
// return StringUtils.join(surnames, " ").toLowerCase(Locale.ENGLISH);
// }
//
// public Integer getShrinkTo() {
// return stringShrinker.getLength();
// }
// public void setShrinkTo(int shrinkTo) {
// stringShrinker.setLength(shrinkTo);
// }
// }
// Path: src/test/java/org/kew/rmf/transformers/authors/ShrunkAuthorsTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import org.kew.rmf.transformers.authors.ShrunkAuthors;
/*
* Copyright © 2012, 2013, 2014 Royal Botanic Gardens, Kew.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.kew.rmf.transformers.authors;
public class ShrunkAuthorsTest {
@Test
public void need_to_remove_initials() { | ShrunkAuthors transformer = new ShrunkAuthors(); |
turn/sorcerer | src/main/java/com/turn/sorcerer/module/ModuleType.java | // Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/util/email/EmailType.java
// public class EmailType {
//
// private boolean enabled = false;
//
// private String admin = "";
//
// private String host = "";
//
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public String getAdmins() {
// return this.admin;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public String toString() {
// return "enabled:" + this.enabled + " host:" + host + " admin:" + admin;
// }
// }
| import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.util.email.EmailType;
import java.util.List;
import com.google.common.base.MoreObjects; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.module;
/**
* Module type object created from Sorcerer configuration
*
* @author tshiou
*/
public class ModuleType {
private String name;
private List<String> pipelines;
| // Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/util/email/EmailType.java
// public class EmailType {
//
// private boolean enabled = false;
//
// private String admin = "";
//
// private String host = "";
//
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public String getAdmins() {
// return this.admin;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public String toString() {
// return "enabled:" + this.enabled + " host:" + host + " admin:" + admin;
// }
// }
// Path: src/main/java/com/turn/sorcerer/module/ModuleType.java
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.util.email.EmailType;
import java.util.List;
import com.google.common.base.MoreObjects;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.module;
/**
* Module type object created from Sorcerer configuration
*
* @author tshiou
*/
public class ModuleType {
private String name;
private List<String> pipelines;
| private EmailType email = new EmailType(); |
turn/sorcerer | src/main/java/com/turn/sorcerer/module/ModuleType.java | // Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/util/email/EmailType.java
// public class EmailType {
//
// private boolean enabled = false;
//
// private String admin = "";
//
// private String host = "";
//
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public String getAdmins() {
// return this.admin;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public String toString() {
// return "enabled:" + this.enabled + " host:" + host + " admin:" + admin;
// }
// }
| import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.util.email.EmailType;
import java.util.List;
import com.google.common.base.MoreObjects; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.module;
/**
* Module type object created from Sorcerer configuration
*
* @author tshiou
*/
public class ModuleType {
private String name;
private List<String> pipelines;
private EmailType email = new EmailType();
private Integer retention = 0;
private List<String> packages;
| // Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/util/email/EmailType.java
// public class EmailType {
//
// private boolean enabled = false;
//
// private String admin = "";
//
// private String host = "";
//
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public String getAdmins() {
// return this.admin;
// }
//
// public String getHost() {
// return this.host;
// }
//
// public String toString() {
// return "enabled:" + this.enabled + " host:" + host + " admin:" + admin;
// }
// }
// Path: src/main/java/com/turn/sorcerer/module/ModuleType.java
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.util.email.EmailType;
import java.util.List;
import com.google.common.base.MoreObjects;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.module;
/**
* Module type object created from Sorcerer configuration
*
* @author tshiou
*/
public class ModuleType {
private String name;
private List<String> pipelines;
private EmailType email = new EmailType();
private Integer retention = 0;
private List<String> packages;
| private StatusStorageType storage; |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/impl/ZookeeperStatusStorage.java | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/util/PathUtil.java
// public class PathUtil {
//
// public static String stripPrePostSlashes(String s) {
// String ret = s;
// if (s.charAt(0) == '/') {
// ret = s.substring(1);
// }
// return stripPostSlash(ret);
// }
//
// public static String stripPostSlash(String s) {
// String ret = s;
// if (s.charAt(s.length() - 1) == '/') {
// ret = ret.substring(0, ret.length() - 1);
// }
// return ret;
// }
// }
| import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.impl.util.PathUtil;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | private Integer sessionTimeout = 60000;
@Inject(optional = true)
@Named(CONNECTION_TIMEOUT)
private Integer connectionTimeout = 60000;
@Inject(optional = true)
@Named(RETRY_DURATION)
private Integer retryDuration;
@Inject(optional = true)
@Named(RETRY_INTERVAL)
private Integer retryInterval;
private CuratorFramework curator;
private boolean initialized = false;
private static final Joiner PATH = Joiner.on('/').skipNulls();
@Override
public void init() throws IOException {
logger.info("Initializing Zookeeper storage: {}", connectionString);
curator = CuratorFrameworkFactory.newClient(
connectionString, sessionTimeout, connectionTimeout,
new RetryUntilElapsed(retryDuration, retryInterval)
);
curator.start();
initialized = true;
// Strip slash suffixes | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/util/PathUtil.java
// public class PathUtil {
//
// public static String stripPrePostSlashes(String s) {
// String ret = s;
// if (s.charAt(0) == '/') {
// ret = s.substring(1);
// }
// return stripPostSlash(ret);
// }
//
// public static String stripPostSlash(String s) {
// String ret = s;
// if (s.charAt(s.length() - 1) == '/') {
// ret = ret.substring(0, ret.length() - 1);
// }
// return ret;
// }
// }
// Path: src/main/java/com/turn/sorcerer/status/impl/ZookeeperStatusStorage.java
import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.impl.util.PathUtil;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private Integer sessionTimeout = 60000;
@Inject(optional = true)
@Named(CONNECTION_TIMEOUT)
private Integer connectionTimeout = 60000;
@Inject(optional = true)
@Named(RETRY_DURATION)
private Integer retryDuration;
@Inject(optional = true)
@Named(RETRY_INTERVAL)
private Integer retryInterval;
private CuratorFramework curator;
private boolean initialized = false;
private static final Joiner PATH = Joiner.on('/').skipNulls();
@Override
public void init() throws IOException {
logger.info("Initializing Zookeeper storage: {}", connectionString);
curator = CuratorFrameworkFactory.newClient(
connectionString, sessionTimeout, connectionTimeout,
new RetryUntilElapsed(retryDuration, retryInterval)
);
curator.start();
initialized = true;
// Strip slash suffixes | this.root = PathUtil.stripPostSlash(root); |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/impl/ZookeeperStatusStorage.java | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/util/PathUtil.java
// public class PathUtil {
//
// public static String stripPrePostSlashes(String s) {
// String ret = s;
// if (s.charAt(0) == '/') {
// ret = s.substring(1);
// }
// return stripPostSlash(ret);
// }
//
// public static String stripPostSlash(String s) {
// String ret = s;
// if (s.charAt(s.length() - 1) == '/') {
// ret = ret.substring(0, ret.length() - 1);
// }
// return ret;
// }
// }
| import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.impl.util.PathUtil;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | } catch (Exception e) {
throw new IOException(e);
}
}
@Override
public StatusStorage setType(String type) {
// Strip path separator prefix or suffix
this.type = PathUtil.stripPrePostSlashes(type);
return this;
}
@Override
public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
String path = PATH.join(root, type, identifier, id);
try {
if (curator.checkExists().forPath(path) == null) {
return new DateTime(0);
}
return new DateTime(curator.checkExists().forPath(path).getMtime());
} catch (Exception e) {
throw new IOException(e);
}
}
@Override | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/util/PathUtil.java
// public class PathUtil {
//
// public static String stripPrePostSlashes(String s) {
// String ret = s;
// if (s.charAt(0) == '/') {
// ret = s.substring(1);
// }
// return stripPostSlash(ret);
// }
//
// public static String stripPostSlash(String s) {
// String ret = s;
// if (s.charAt(s.length() - 1) == '/') {
// ret = ret.substring(0, ret.length() - 1);
// }
// return ret;
// }
// }
// Path: src/main/java/com/turn/sorcerer/status/impl/ZookeeperStatusStorage.java
import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.impl.util.PathUtil;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import com.google.common.base.Joiner;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryUntilElapsed;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public StatusStorage setType(String type) {
// Strip path separator prefix or suffix
this.type = PathUtil.stripPrePostSlashes(type);
return this;
}
@Override
public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
String path = PATH.join(root, type, identifier, id);
try {
if (curator.checkExists().forPath(path) == null) {
return new DateTime(0);
}
return new DateTime(curator.checkExists().forPath(path).getMtime());
} catch (Exception e) {
throw new IOException(e);
}
}
@Override | public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException { |
turn/sorcerer | src/main/java/com/turn/sorcerer/pipeline/impl/CronPipeline.java | // Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/util/CronExpression.java
// public class CronExpression {
//
// private org.quartz.CronExpression cronExpression;
//
// public CronExpression(String cronString) {
// try {
// cronExpression = new org.quartz.CronExpression(cronString);
// } catch (ParseException e) {
// e.printStackTrace();
// }
// }
//
// public DateTime getNextTimeAfter(DateTime dt) {
// return new DateTime(cronExpression.getNextValidTimeAfter(dt.toDate()));
// }
// }
| import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.util.CronExpression;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.pipeline.impl;
/**
* Cron implementation of Pipeline
*
* @author tshiou
*/
public class CronPipeline implements Pipeline {
private static final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyMMdd");
| // Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/util/CronExpression.java
// public class CronExpression {
//
// private org.quartz.CronExpression cronExpression;
//
// public CronExpression(String cronString) {
// try {
// cronExpression = new org.quartz.CronExpression(cronString);
// } catch (ParseException e) {
// e.printStackTrace();
// }
// }
//
// public DateTime getNextTimeAfter(DateTime dt) {
// return new DateTime(cronExpression.getNextValidTimeAfter(dt.toDate()));
// }
// }
// Path: src/main/java/com/turn/sorcerer/pipeline/impl/CronPipeline.java
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.util.CronExpression;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.pipeline.impl;
/**
* Cron implementation of Pipeline
*
* @author tshiou
*/
public class CronPipeline implements Pipeline {
private static final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyMMdd");
| private final CronExpression cronExp; |
turn/sorcerer | src/test/java/com/turn/sorcerer/tasks/TestTask5.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
| import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task
*
* @author tshiou
*/
@SorcererTask(name = "test_task_5")
public class TestTask5 extends TestTask {
public static final String TASK_NAME = TestTask5.class.getSimpleName();
private static final int TASK_COUNT = 8;
@Override | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
// Path: src/test/java/com/turn/sorcerer/tasks/TestTask5.java
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task
*
* @author tshiou
*/
@SorcererTask(name = "test_task_5")
public class TestTask5 extends TestTask {
public static final String TASK_NAME = TestTask5.class.getSimpleName();
private static final int TASK_COUNT = 8;
@Override | public Collection<Dependency> getDependencies(int iterNo) { |
turn/sorcerer | src/main/java/com/turn/sorcerer/task/Task.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
| import com.turn.sorcerer.dependency.Dependency;
import java.util.Collection; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task;
/**
* Represents the smallest unit of action in the Sorcerer workflow. Should
* be implemented by any class whose instances are intended to be executed
* in a pipeline by Sorcerer.
*
* <p>
* This interface should be implemented to provide Sorcerer with the
* initialization and execution code of a task in the workflow.
* </p>
*
* <p>
* The execution of the implemented methods are such:
* <ol>
* <li>
* <b>Initialization</b> by calling {@code init()}.
* </li>
* <li>
* <b>Check dependencies</b> by calling {@code check()} method of each
* {@code Dependency} instance provided in {@code getDependencies()}.
* </li>
* <li>
* <b>Execution by calling</b> {@code exec()}
* </li>
* </ol>
* See {@link com.turn.sorcerer.executor.TaskExecutor} for specific details on
* task execution.
* </p>
*
* <p>
* Classes that implement this interface should be annotated with
* {@code SorcererTask(name)} for Sorcerer to register the implementation.
* The {@code name} field in the SorcererTask annotation will be used to map
* the implementation to the corresponding task configuration of the same name.
* </p>
*
* @author tshiou
* @see com.turn.sorcerer.executor.TaskExecutor
* @see com.turn.sorcerer.task.executable.ExecutableTask
* @see com.turn.sorcerer.dependency.Dependency
*/
public interface Task {
/**
* Initializes the task
*
* <p>
* First method called by Sorcerer in the execution of a task. Any task
* initialization code should be put in the implementation of this
* method.
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param context Context object containing task execution context.
* See {@link com.turn.sorcerer.task.Context}.
*/
void init(final Context context);
/**
* Executes the task
*
* <p>
* Implementation of this method should contain the "meat" of the task.
* This method will not be called if the dependency checking phase returns
* false. This of course means that this method will be called after both
* {@code init()} and {@code checkDependencies()}. The successful execution
* of this method will result in the task being committed to a successful
* completed state.
* </p>
*
* <p>
* Obviously if an exception is thrown the task will be committed to an
* ERROR state. Additionally, exceptions thrown by this method will be
* caught by Sorcerer, wrapped in a {code SorcererException}, logged,
* and then an email will be sent to the admins with the exception as the
* email body (if enabled).
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#execute
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param context Context object containing task execution context.
* See {@link com.turn.sorcerer.task.Context}.
* @throws Exception Will be wrapped by a {@code SorcererException} before
* being thrown into a higher context.
*/
void exec(final Context context) throws Exception;
/**
* Provides a Collection of this task's dependencies
*
* <p>
* This method should provide a collection of all the dependencies of this
* task. Sorcerer will iterate over the collection, and call the
* {@code check()} method of the {@code Dependency} instance. Once any of
* the Dependencies return false, Sorcerer will consider the task
* ineligible to be scheduled.
* </p>
*
* <p>
* Note that Sorcerer calls this method <i>after</i> {@code init()}.
* </p>
*
* <p>
* If any complex dependency logic is required (for example if the user
* desires a task be executed if one of many dependencies are fulfilled)
* then the logic should be contained in a custom implementation of the
* {@link com.turn.sorcerer.dependency.Dependency} class.
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param iterNo Iteration number of the task being executed
* @return Collection of Dependency objects
*/ | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
// Path: src/main/java/com/turn/sorcerer/task/Task.java
import com.turn.sorcerer.dependency.Dependency;
import java.util.Collection;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task;
/**
* Represents the smallest unit of action in the Sorcerer workflow. Should
* be implemented by any class whose instances are intended to be executed
* in a pipeline by Sorcerer.
*
* <p>
* This interface should be implemented to provide Sorcerer with the
* initialization and execution code of a task in the workflow.
* </p>
*
* <p>
* The execution of the implemented methods are such:
* <ol>
* <li>
* <b>Initialization</b> by calling {@code init()}.
* </li>
* <li>
* <b>Check dependencies</b> by calling {@code check()} method of each
* {@code Dependency} instance provided in {@code getDependencies()}.
* </li>
* <li>
* <b>Execution by calling</b> {@code exec()}
* </li>
* </ol>
* See {@link com.turn.sorcerer.executor.TaskExecutor} for specific details on
* task execution.
* </p>
*
* <p>
* Classes that implement this interface should be annotated with
* {@code SorcererTask(name)} for Sorcerer to register the implementation.
* The {@code name} field in the SorcererTask annotation will be used to map
* the implementation to the corresponding task configuration of the same name.
* </p>
*
* @author tshiou
* @see com.turn.sorcerer.executor.TaskExecutor
* @see com.turn.sorcerer.task.executable.ExecutableTask
* @see com.turn.sorcerer.dependency.Dependency
*/
public interface Task {
/**
* Initializes the task
*
* <p>
* First method called by Sorcerer in the execution of a task. Any task
* initialization code should be put in the implementation of this
* method.
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param context Context object containing task execution context.
* See {@link com.turn.sorcerer.task.Context}.
*/
void init(final Context context);
/**
* Executes the task
*
* <p>
* Implementation of this method should contain the "meat" of the task.
* This method will not be called if the dependency checking phase returns
* false. This of course means that this method will be called after both
* {@code init()} and {@code checkDependencies()}. The successful execution
* of this method will result in the task being committed to a successful
* completed state.
* </p>
*
* <p>
* Obviously if an exception is thrown the task will be committed to an
* ERROR state. Additionally, exceptions thrown by this method will be
* caught by Sorcerer, wrapped in a {code SorcererException}, logged,
* and then an email will be sent to the admins with the exception as the
* email body (if enabled).
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#execute
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param context Context object containing task execution context.
* See {@link com.turn.sorcerer.task.Context}.
* @throws Exception Will be wrapped by a {@code SorcererException} before
* being thrown into a higher context.
*/
void exec(final Context context) throws Exception;
/**
* Provides a Collection of this task's dependencies
*
* <p>
* This method should provide a collection of all the dependencies of this
* task. Sorcerer will iterate over the collection, and call the
* {@code check()} method of the {@code Dependency} instance. Once any of
* the Dependencies return false, Sorcerer will consider the task
* ineligible to be scheduled.
* </p>
*
* <p>
* Note that Sorcerer calls this method <i>after</i> {@code init()}.
* </p>
*
* <p>
* If any complex dependency logic is required (for example if the user
* desires a task be executed if one of many dependencies are fulfilled)
* then the logic should be contained in a custom implementation of the
* {@link com.turn.sorcerer.dependency.Dependency} class.
* </p>
*
* @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
* @see com.turn.sorcerer.executor.TaskExecutor#call
*
* @param iterNo Iteration number of the task being executed
* @return Collection of Dependency objects
*/ | Collection<Dependency> getDependencies(int iterNo); |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
| import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorage implements StatusStorage {
private static final Logger logger =
LoggerFactory.getLogger(MemoryStatusStorage.class);
| // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
// Path: src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java
import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorage implements StatusStorage {
private static final Logger logger =
LoggerFactory.getLogger(MemoryStatusStorage.class);
| private final Table<String, Integer, ConcurrentMap<Status, DateTime>> store; |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/type/impl/MemoryStatusStorageType.java | // Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java
// public class MemoryStatusStorage implements StatusStorage {
//
// private static final Logger logger =
// LoggerFactory.getLogger(MemoryStatusStorage.class);
//
// private final Table<String, Integer, ConcurrentMap<Status, DateTime>> store;
//
// public MemoryStatusStorage() {
// logger.debug("New instance of memory status storage");
// store = HashBasedTable.create();
// }
//
// @Override
// public void init() throws IOException {
//
// }
//
// @Override
// public StatusStorage setType(String type) {
// return this;
// }
//
// @Override
// public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null) {
// return null;
// }
//
// DateTime lastDt = new DateTime().withYear(1970);
//
// for (DateTime dt : statuses.values()) {
// if (dt.isAfter(lastDt)) {
// lastDt = dt;
// }
// }
//
// return lastDt;
// }
//
// @Override
// public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses != null) {
// return statuses.get(status);
// }
//
// return null;
// }
//
// @Override
// public int getCurrentIterNo(String identifier) throws IOException {
// int maxIterNo = 0;
// for (Integer i : store.columnKeySet()) {
// maxIterNo = Math.max(i, maxIterNo);
// }
// return maxIterNo;
// }
//
// @Override
// public Status checkStatus(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null || statuses.size() == 0) {
// return Status.PENDING;
// }
//
// Set<Status> stati = statuses.keySet();
//
// if (stati.contains(Status.SUCCESS)) {
// return Status.SUCCESS;
// }
//
// if (stati.contains(Status.IN_PROGRESS)) {
// return Status.IN_PROGRESS;
// }
//
// if (stati.contains(Status.ERROR)) {
// return Status.ERROR;
// }
//
// return Status.PENDING;
// }
//
// @Override
// public void clearAllStatuses(String identifier, int jobId) throws IOException {
// store.remove(identifier, jobId);
// }
//
// @Override
// public void removeStatus(String identifier, int jobId, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// statuses.remove(status);
// }
//
// @Override
// public void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// if (statuses == null || overwrite) {
// statuses = new ConcurrentHashMap<Status, DateTime>();
// store.put(identifier, jobId, statuses);
// }
//
// statuses.put(status, time);
// }
// }
| import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.status.impl.MemoryStatusStorage; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.type.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorageType implements StatusStorageType {
private String dummy;
@Override | // Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java
// public class MemoryStatusStorage implements StatusStorage {
//
// private static final Logger logger =
// LoggerFactory.getLogger(MemoryStatusStorage.class);
//
// private final Table<String, Integer, ConcurrentMap<Status, DateTime>> store;
//
// public MemoryStatusStorage() {
// logger.debug("New instance of memory status storage");
// store = HashBasedTable.create();
// }
//
// @Override
// public void init() throws IOException {
//
// }
//
// @Override
// public StatusStorage setType(String type) {
// return this;
// }
//
// @Override
// public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null) {
// return null;
// }
//
// DateTime lastDt = new DateTime().withYear(1970);
//
// for (DateTime dt : statuses.values()) {
// if (dt.isAfter(lastDt)) {
// lastDt = dt;
// }
// }
//
// return lastDt;
// }
//
// @Override
// public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses != null) {
// return statuses.get(status);
// }
//
// return null;
// }
//
// @Override
// public int getCurrentIterNo(String identifier) throws IOException {
// int maxIterNo = 0;
// for (Integer i : store.columnKeySet()) {
// maxIterNo = Math.max(i, maxIterNo);
// }
// return maxIterNo;
// }
//
// @Override
// public Status checkStatus(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null || statuses.size() == 0) {
// return Status.PENDING;
// }
//
// Set<Status> stati = statuses.keySet();
//
// if (stati.contains(Status.SUCCESS)) {
// return Status.SUCCESS;
// }
//
// if (stati.contains(Status.IN_PROGRESS)) {
// return Status.IN_PROGRESS;
// }
//
// if (stati.contains(Status.ERROR)) {
// return Status.ERROR;
// }
//
// return Status.PENDING;
// }
//
// @Override
// public void clearAllStatuses(String identifier, int jobId) throws IOException {
// store.remove(identifier, jobId);
// }
//
// @Override
// public void removeStatus(String identifier, int jobId, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// statuses.remove(status);
// }
//
// @Override
// public void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// if (statuses == null || overwrite) {
// statuses = new ConcurrentHashMap<Status, DateTime>();
// store.put(identifier, jobId, statuses);
// }
//
// statuses.put(status, time);
// }
// }
// Path: src/main/java/com/turn/sorcerer/status/type/impl/MemoryStatusStorageType.java
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.status.impl.MemoryStatusStorage;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.type.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorageType implements StatusStorageType {
private String dummy;
@Override | public Class<? extends StatusStorage> getStorageClass() { |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/type/impl/MemoryStatusStorageType.java | // Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java
// public class MemoryStatusStorage implements StatusStorage {
//
// private static final Logger logger =
// LoggerFactory.getLogger(MemoryStatusStorage.class);
//
// private final Table<String, Integer, ConcurrentMap<Status, DateTime>> store;
//
// public MemoryStatusStorage() {
// logger.debug("New instance of memory status storage");
// store = HashBasedTable.create();
// }
//
// @Override
// public void init() throws IOException {
//
// }
//
// @Override
// public StatusStorage setType(String type) {
// return this;
// }
//
// @Override
// public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null) {
// return null;
// }
//
// DateTime lastDt = new DateTime().withYear(1970);
//
// for (DateTime dt : statuses.values()) {
// if (dt.isAfter(lastDt)) {
// lastDt = dt;
// }
// }
//
// return lastDt;
// }
//
// @Override
// public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses != null) {
// return statuses.get(status);
// }
//
// return null;
// }
//
// @Override
// public int getCurrentIterNo(String identifier) throws IOException {
// int maxIterNo = 0;
// for (Integer i : store.columnKeySet()) {
// maxIterNo = Math.max(i, maxIterNo);
// }
// return maxIterNo;
// }
//
// @Override
// public Status checkStatus(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null || statuses.size() == 0) {
// return Status.PENDING;
// }
//
// Set<Status> stati = statuses.keySet();
//
// if (stati.contains(Status.SUCCESS)) {
// return Status.SUCCESS;
// }
//
// if (stati.contains(Status.IN_PROGRESS)) {
// return Status.IN_PROGRESS;
// }
//
// if (stati.contains(Status.ERROR)) {
// return Status.ERROR;
// }
//
// return Status.PENDING;
// }
//
// @Override
// public void clearAllStatuses(String identifier, int jobId) throws IOException {
// store.remove(identifier, jobId);
// }
//
// @Override
// public void removeStatus(String identifier, int jobId, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// statuses.remove(status);
// }
//
// @Override
// public void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// if (statuses == null || overwrite) {
// statuses = new ConcurrentHashMap<Status, DateTime>();
// store.put(identifier, jobId, statuses);
// }
//
// statuses.put(status, time);
// }
// }
| import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.status.impl.MemoryStatusStorage; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.type.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorageType implements StatusStorageType {
private String dummy;
@Override
public Class<? extends StatusStorage> getStorageClass() { | // Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
//
// Path: src/main/java/com/turn/sorcerer/status/type/StatusStorageType.java
// public interface StatusStorageType {
//
// Class<? extends StatusStorage> getStorageClass();
//
// String name();
// }
//
// Path: src/main/java/com/turn/sorcerer/status/impl/MemoryStatusStorage.java
// public class MemoryStatusStorage implements StatusStorage {
//
// private static final Logger logger =
// LoggerFactory.getLogger(MemoryStatusStorage.class);
//
// private final Table<String, Integer, ConcurrentMap<Status, DateTime>> store;
//
// public MemoryStatusStorage() {
// logger.debug("New instance of memory status storage");
// store = HashBasedTable.create();
// }
//
// @Override
// public void init() throws IOException {
//
// }
//
// @Override
// public StatusStorage setType(String type) {
// return this;
// }
//
// @Override
// public DateTime getLastUpdateTime(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null) {
// return null;
// }
//
// DateTime lastDt = new DateTime().withYear(1970);
//
// for (DateTime dt : statuses.values()) {
// if (dt.isAfter(lastDt)) {
// lastDt = dt;
// }
// }
//
// return lastDt;
// }
//
// @Override
// public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses != null) {
// return statuses.get(status);
// }
//
// return null;
// }
//
// @Override
// public int getCurrentIterNo(String identifier) throws IOException {
// int maxIterNo = 0;
// for (Integer i : store.columnKeySet()) {
// maxIterNo = Math.max(i, maxIterNo);
// }
// return maxIterNo;
// }
//
// @Override
// public Status checkStatus(String identifier, int id) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, id);
//
// if (statuses == null || statuses.size() == 0) {
// return Status.PENDING;
// }
//
// Set<Status> stati = statuses.keySet();
//
// if (stati.contains(Status.SUCCESS)) {
// return Status.SUCCESS;
// }
//
// if (stati.contains(Status.IN_PROGRESS)) {
// return Status.IN_PROGRESS;
// }
//
// if (stati.contains(Status.ERROR)) {
// return Status.ERROR;
// }
//
// return Status.PENDING;
// }
//
// @Override
// public void clearAllStatuses(String identifier, int jobId) throws IOException {
// store.remove(identifier, jobId);
// }
//
// @Override
// public void removeStatus(String identifier, int jobId, Status status) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// statuses.remove(status);
// }
//
// @Override
// public void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException {
// ConcurrentMap<Status, DateTime> statuses = store.get(identifier, jobId);
//
// if (statuses == null || overwrite) {
// statuses = new ConcurrentHashMap<Status, DateTime>();
// store.put(identifier, jobId, statuses);
// }
//
// statuses.put(status, time);
// }
// }
// Path: src/main/java/com/turn/sorcerer/status/type/impl/MemoryStatusStorageType.java
import com.turn.sorcerer.status.StatusStorage;
import com.turn.sorcerer.status.type.StatusStorageType;
import com.turn.sorcerer.status.impl.MemoryStatusStorage;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.status.type.impl;
/**
* Class Description Here
*
* @author tshiou
*/
public class MemoryStatusStorageType implements StatusStorageType {
private String dummy;
@Override
public Class<? extends StatusStorage> getStorageClass() { | return MemoryStatusStorage.class; |
turn/sorcerer | src/main/java/com/turn/sorcerer/task/Context.java | // Path: src/main/java/com/turn/sorcerer/util/TypedDictionary.java
// public class TypedDictionary {
// private Map<String, Object> map;
//
// public TypedDictionary() {
// map = Maps.newHashMap();
// }
//
// public <E> E get(String key, Class<E> type) {
// if (!map.containsKey(key)) return null;
// Object o = map.get(key);
// if (o == null) return null;
// return type.cast(o);
// }
//
// public boolean getBool(String key) {
// return get(key, Boolean.class);
// }
//
// public long getLong(String key) {
// return get(key, Long.class);
// }
//
// public String getString(String key) {
// return get(key, String.class);
// }
//
// public double getDouble(String key) {
// return get(key, Double.class);
// }
//
// public boolean getBool(String key, boolean def) {
// Boolean i = get(key, Boolean.class);
// return i == null? def: i;
// }
//
// public long getLong(String key, long def) {
// Long i = get(key, Long.class);
// return i == null? def: i;
// }
//
// public String getString(String key, String def) {
// String i = get(key, String.class);
// return i == null? def: i;
// }
//
// public double getDouble(String key, double def) {
// Double i = get(key, Double.class);
// return i == null? def: i;
// }
//
// public void put(String key, Object o) {
// map.put(key, o);
// }
//
// public void putAll(Map<String, ? extends Object> props) {
// if (props == null || props.size() == 0) {
// return;
// }
//
// this.map.putAll(props);
// }
//
// public void putAll(TypedDictionary other) {
// if (other == null || other.size() == 0) {
// return;
// }
//
// this.map.putAll(other.map);
// }
//
// public int size() {
// return map.size();
// }
// }
| import com.turn.sorcerer.util.TypedDictionary;
import java.util.Map;
import com.google.common.collect.Maps; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task;
/**
* Provides task context including iteration number and properties
*
* @author tshiou
*/
public class Context {
private int iterationNumber; | // Path: src/main/java/com/turn/sorcerer/util/TypedDictionary.java
// public class TypedDictionary {
// private Map<String, Object> map;
//
// public TypedDictionary() {
// map = Maps.newHashMap();
// }
//
// public <E> E get(String key, Class<E> type) {
// if (!map.containsKey(key)) return null;
// Object o = map.get(key);
// if (o == null) return null;
// return type.cast(o);
// }
//
// public boolean getBool(String key) {
// return get(key, Boolean.class);
// }
//
// public long getLong(String key) {
// return get(key, Long.class);
// }
//
// public String getString(String key) {
// return get(key, String.class);
// }
//
// public double getDouble(String key) {
// return get(key, Double.class);
// }
//
// public boolean getBool(String key, boolean def) {
// Boolean i = get(key, Boolean.class);
// return i == null? def: i;
// }
//
// public long getLong(String key, long def) {
// Long i = get(key, Long.class);
// return i == null? def: i;
// }
//
// public String getString(String key, String def) {
// String i = get(key, String.class);
// return i == null? def: i;
// }
//
// public double getDouble(String key, double def) {
// Double i = get(key, Double.class);
// return i == null? def: i;
// }
//
// public void put(String key, Object o) {
// map.put(key, o);
// }
//
// public void putAll(Map<String, ? extends Object> props) {
// if (props == null || props.size() == 0) {
// return;
// }
//
// this.map.putAll(props);
// }
//
// public void putAll(TypedDictionary other) {
// if (other == null || other.size() == 0) {
// return;
// }
//
// this.map.putAll(other.map);
// }
//
// public int size() {
// return map.size();
// }
// }
// Path: src/main/java/com/turn/sorcerer/task/Context.java
import com.turn.sorcerer.util.TypedDictionary;
import java.util.Map;
import com.google.common.collect.Maps;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task;
/**
* Provides task context including iteration number and properties
*
* @author tshiou
*/
public class Context {
private int iterationNumber; | private final TypedDictionary properties; |
turn/sorcerer | src/main/java/com/turn/sorcerer/config/impl/InfomasAnnotationProcessor.java | // Path: src/main/java/com/turn/sorcerer/config/AnnotationProcessor.java
// public interface AnnotationProcessor {
//
// void process(Collection<String> ... pkgs);
// }
//
// Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.config.AnnotationProcessor;
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.pipeline.SorcererPipeline;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import eu.infomas.annotation.AnnotationDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | public Class<? extends Annotation>[] annotations() {
return new Class[] {
SorcererTask.class,
SorcererPipeline.class
};
}
@SuppressWarnings("unchecked")
@Override
public void reportTypeAnnotation(Class<? extends Annotation> a, String s) {
if (a == SorcererTask.class) {
Class c;
try {
c = Class.forName(s);
} catch (ClassNotFoundException e) {
logger.error("Could not find class " + s);
return;
}
Annotation anno = c.getAnnotation(SorcererTask.class);
SorcererTask sorcererAnno = (SorcererTask) anno;
// Annotation must provide name
if (sorcererAnno.name() == null) {
logger.error("Sorcerer task annotation found on class " + s +
" but no name provided!");
return;
}
// Class must extend Task | // Path: src/main/java/com/turn/sorcerer/config/AnnotationProcessor.java
// public interface AnnotationProcessor {
//
// void process(Collection<String> ... pkgs);
// }
//
// Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/main/java/com/turn/sorcerer/config/impl/InfomasAnnotationProcessor.java
import com.turn.sorcerer.config.AnnotationProcessor;
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.pipeline.SorcererPipeline;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import eu.infomas.annotation.AnnotationDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public Class<? extends Annotation>[] annotations() {
return new Class[] {
SorcererTask.class,
SorcererPipeline.class
};
}
@SuppressWarnings("unchecked")
@Override
public void reportTypeAnnotation(Class<? extends Annotation> a, String s) {
if (a == SorcererTask.class) {
Class c;
try {
c = Class.forName(s);
} catch (ClassNotFoundException e) {
logger.error("Could not find class " + s);
return;
}
Annotation anno = c.getAnnotation(SorcererTask.class);
SorcererTask sorcererAnno = (SorcererTask) anno;
// Annotation must provide name
if (sorcererAnno.name() == null) {
logger.error("Sorcerer task annotation found on class " + s +
" but no name provided!");
return;
}
// Class must extend Task | if (Task.class.isAssignableFrom(c) == false) { |
turn/sorcerer | src/main/java/com/turn/sorcerer/config/impl/InfomasAnnotationProcessor.java | // Path: src/main/java/com/turn/sorcerer/config/AnnotationProcessor.java
// public interface AnnotationProcessor {
//
// void process(Collection<String> ... pkgs);
// }
//
// Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.config.AnnotationProcessor;
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.pipeline.SorcererPipeline;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import eu.infomas.annotation.AnnotationDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
// Class must extend Task
if (Task.class.isAssignableFrom(c) == false) {
logger.error("Sorcerer task annotation found but class " + s +
" does not extend Task!");
return;
}
SorcererRegistry.get().registerTaskClass(sorcererAnno.name(), c);
} else if (a == SorcererPipeline.class) {
Class c;
try {
c = Class.forName(s);
} catch (ClassNotFoundException e) {
logger.error("Could not find class " + s);
return;
}
Annotation anno = c.getAnnotation(SorcererPipeline.class);
SorcererPipeline sorcererAnno = (SorcererPipeline) anno;
// Annotation must provide name
if (sorcererAnno.name() == null) {
logger.error("Sorcerer pipeline annotation found on class " + s +
" but no name provided!");
return;
}
// Class must extend Task | // Path: src/main/java/com/turn/sorcerer/config/AnnotationProcessor.java
// public interface AnnotationProcessor {
//
// void process(Collection<String> ... pkgs);
// }
//
// Path: src/main/java/com/turn/sorcerer/pipeline/Pipeline.java
// public interface Pipeline {
//
// /**
// * Provides the current iteration number of a pipeline
// *
// * <p>
// * This method should be implemented to trigger the scheduling of a
// * pipeline based on the iteration number. Sorcerer will use the value
// * returned by this method to schedule pipelines. Each time a new iteration
// * number is provided by this method, Sorcerer will instantiate and
// * schedule a new pipeline.
// * </p>
// *
// * <p>
// * Note: This method will be called periodically (as defined by the
// * {@code interval} field of a pipeline configuration) and so it should
// * be stateless. Sorcerer instantiates a Pipeline instance using its
// * injector and then calls this method to generate the current iteration
// * number.
// * </p>
// *
// * @return Current iteration number
// */
// Integer getCurrentIterationNumber();
//
// Integer getPreviousIterationNumber(int curr, int prev);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/main/java/com/turn/sorcerer/config/impl/InfomasAnnotationProcessor.java
import com.turn.sorcerer.config.AnnotationProcessor;
import com.turn.sorcerer.pipeline.Pipeline;
import com.turn.sorcerer.pipeline.SorcererPipeline;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import eu.infomas.annotation.AnnotationDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
// Class must extend Task
if (Task.class.isAssignableFrom(c) == false) {
logger.error("Sorcerer task annotation found but class " + s +
" does not extend Task!");
return;
}
SorcererRegistry.get().registerTaskClass(sorcererAnno.name(), c);
} else if (a == SorcererPipeline.class) {
Class c;
try {
c = Class.forName(s);
} catch (ClassNotFoundException e) {
logger.error("Could not find class " + s);
return;
}
Annotation anno = c.getAnnotation(SorcererPipeline.class);
SorcererPipeline sorcererAnno = (SorcererPipeline) anno;
// Annotation must provide name
if (sorcererAnno.name() == null) {
logger.error("Sorcerer pipeline annotation found on class " + s +
" but no name provided!");
return;
}
// Class must extend Task | if (Pipeline.class.isAssignableFrom(c) == false) { |
turn/sorcerer | src/main/java/com/turn/sorcerer/status/impl/HDFSStatusStorage.java | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
| import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | if (fs == null) {
try {
fs = FileSystem.get(new Configuration());
} catch (IOException e) {
logger.error("Filesystem unreachable!", e);
throw e;
}
}
long maxTS = 0;
Path directoryPath = new Path(getStatusPath(identifier, id));
FileStatus[] fileStatuses;
try {
fileStatuses = fs.listStatus(directoryPath);
} catch (FileNotFoundException fnfe ) {
return new DateTime(0);
}
for (FileStatus fileStatus : fileStatuses) {
maxTS = Math.max(fileStatus.getModificationTime(), maxTS);
}
return new DateTime(maxTS);
}
@Override | // Path: src/main/java/com/turn/sorcerer/status/Status.java
// public enum Status {
//
// /**
// * Represents a task that is a part of a scheduled pipeline but is not yet
// * eligible for execution, or more specifically the previous tasks in the
// * workflow have not completed or one of
// * {@link com.turn.sorcerer.task.Task#getDependencies(int)} is returning
// * false
// */
// PENDING("PENDING"),
//
// /**
// * Represents either:
// *
// * <li>A task that is in-progress, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} method is running
// * </li>
// *
// * <li>
// * A pipeline whose initial task has been launched but the pipeline is not
// * complete, or more specifically all of its memeber tasks have not
// * completed successfully.
// * </li>
// */
// IN_PROGRESS("RUNNING"),
//
// /**
// * Represents either:
// *
// * <li>
// * A successfully completed task, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} has completed with no
// * exceptions
// * </li>
// *
// * <li>
// * A successfully completed pipeline, or more specifically a pipeline
// * with all member tasks successfully completed.
// * </li>
// */
// SUCCESS("SUCCESS"),
//
// /**
// * Represents a task with a previous iteration run that resulted in an
// * error state, or more specifically
// * {@link com.turn.sorcerer.task.Task#exec} was executed with an exception
// * thrown
// */
// ERROR("ERROR"),
// ;
//
// // String representation of status
// private String string;
//
// private Status(String string) {
// this.string = string;
// }
//
// /**
// * Returns string representation of state.
// */
// public String getString() {
// return string;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/status/StatusStorage.java
// public interface StatusStorage {
//
// String toString();
//
// void init() throws IOException;
//
// StatusStorage setType(String type);
//
// DateTime getLastUpdateTime(String identifier, int id) throws IOException;
//
// DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException;
//
// int getCurrentIterNo(String identifier) throws IOException;
//
// Status checkStatus(String identifier, int id) throws IOException;
//
// void clearAllStatuses(String identifier, int jobId) throws IOException;
//
// void removeStatus(String identifier, int jobId, Status status) throws IOException;
//
// void commitStatus(String identifier, int jobId, Status status, DateTime time, boolean overwrite) throws IOException;
//
// }
// Path: src/main/java/com/turn/sorcerer/status/impl/HDFSStatusStorage.java
import com.turn.sorcerer.status.Status;
import com.turn.sorcerer.status.StatusStorage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (fs == null) {
try {
fs = FileSystem.get(new Configuration());
} catch (IOException e) {
logger.error("Filesystem unreachable!", e);
throw e;
}
}
long maxTS = 0;
Path directoryPath = new Path(getStatusPath(identifier, id));
FileStatus[] fileStatuses;
try {
fileStatuses = fs.listStatus(directoryPath);
} catch (FileNotFoundException fnfe ) {
return new DateTime(0);
}
for (FileStatus fileStatus : fileStatuses) {
maxTS = Math.max(fileStatus.getModificationTime(), maxTS);
}
return new DateTime(maxTS);
}
@Override | public DateTime getStatusUpdateTime(String identifier, int id, Status status) throws IOException { |
turn/sorcerer | src/test/java/com/turn/sorcerer/tasks/TestTask4.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/impl/SorcererTaskDependency.java
// public class SorcererTaskDependency implements Dependency {
//
// private static final Logger logger =
// LoggerFactory.getLogger(SorcererTaskDependency.class);
//
// // Requisite task type
// private final TaskType task;
//
// // Requisite task iteration number
// // If not provided the iteration number will be injected "just-in-time"
// private Integer customIterNo = null;
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param type Task type
// */
// public SorcererTaskDependency(TaskType type) {
// this.task = type;
// }
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * @param type Task type
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(TaskType type, int iterNo) {
// this(type);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskClass Class which implements Task
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass)
// throws SorcererException {
//
// SorcererTask anno = taskClass.getAnnotation(SorcererTask.class);
// if (anno == null) {
// logger.error("Annotation not found on " + taskClass.toString());
// this.task = null;
// throw new SorcererException(taskClass.getName());
// }
//
// String taskName = anno.name();
// if (taskName == null) {
// logger.error("No taskName found in annotation on " + taskClass.toString());
// this.task = null;
// return;
// }
//
// this.task = SorcererInjector.get().getTaskType(taskName);
//
// // Could not get task type from registry
// if (this.task == null) {
// throw new SorcererException(taskClass.getName());
// }
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * @param taskClass Class which implements Task
// * @param iterNo Iteration number of task dependency
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass, int iterNo)
// throws SorcererException {
// this(taskClass);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskName Task name
// */
// public SorcererTaskDependency(String taskName) {
// this.task = SorcererInjector.get().getTaskType(taskName);
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * @param taskName Task name
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(String taskName, int iterNo) {
// this(taskName);
// this.customIterNo = iterNo;
// }
//
// @Override
// public boolean check(int iterNo) {
// return task != null && StatusManager.get().isTaskComplete(
// task, customIterNo == null ? iterNo : customIterNo);
// }
// }
| import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.dependency.impl.SorcererTaskDependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection;
import com.google.common.collect.ImmutableList; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task. Specifically a singleton task.
*
* @author tshiou
*/
@SorcererTask(name = "test_task_4")
public class TestTask4 extends TestTask {
public static final String TASK_NAME = TestTask4.class.getSimpleName();
private static final int TASK_COUNT = 3;
@Override | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/impl/SorcererTaskDependency.java
// public class SorcererTaskDependency implements Dependency {
//
// private static final Logger logger =
// LoggerFactory.getLogger(SorcererTaskDependency.class);
//
// // Requisite task type
// private final TaskType task;
//
// // Requisite task iteration number
// // If not provided the iteration number will be injected "just-in-time"
// private Integer customIterNo = null;
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param type Task type
// */
// public SorcererTaskDependency(TaskType type) {
// this.task = type;
// }
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * @param type Task type
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(TaskType type, int iterNo) {
// this(type);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskClass Class which implements Task
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass)
// throws SorcererException {
//
// SorcererTask anno = taskClass.getAnnotation(SorcererTask.class);
// if (anno == null) {
// logger.error("Annotation not found on " + taskClass.toString());
// this.task = null;
// throw new SorcererException(taskClass.getName());
// }
//
// String taskName = anno.name();
// if (taskName == null) {
// logger.error("No taskName found in annotation on " + taskClass.toString());
// this.task = null;
// return;
// }
//
// this.task = SorcererInjector.get().getTaskType(taskName);
//
// // Could not get task type from registry
// if (this.task == null) {
// throw new SorcererException(taskClass.getName());
// }
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * @param taskClass Class which implements Task
// * @param iterNo Iteration number of task dependency
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass, int iterNo)
// throws SorcererException {
// this(taskClass);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskName Task name
// */
// public SorcererTaskDependency(String taskName) {
// this.task = SorcererInjector.get().getTaskType(taskName);
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * @param taskName Task name
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(String taskName, int iterNo) {
// this(taskName);
// this.customIterNo = iterNo;
// }
//
// @Override
// public boolean check(int iterNo) {
// return task != null && StatusManager.get().isTaskComplete(
// task, customIterNo == null ? iterNo : customIterNo);
// }
// }
// Path: src/test/java/com/turn/sorcerer/tasks/TestTask4.java
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.dependency.impl.SorcererTaskDependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection;
import com.google.common.collect.ImmutableList;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task. Specifically a singleton task.
*
* @author tshiou
*/
@SorcererTask(name = "test_task_4")
public class TestTask4 extends TestTask {
public static final String TASK_NAME = TestTask4.class.getSimpleName();
private static final int TASK_COUNT = 3;
@Override | public Collection<Dependency> getDependencies(int iterNo) { |
turn/sorcerer | src/test/java/com/turn/sorcerer/tasks/TestTask4.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/impl/SorcererTaskDependency.java
// public class SorcererTaskDependency implements Dependency {
//
// private static final Logger logger =
// LoggerFactory.getLogger(SorcererTaskDependency.class);
//
// // Requisite task type
// private final TaskType task;
//
// // Requisite task iteration number
// // If not provided the iteration number will be injected "just-in-time"
// private Integer customIterNo = null;
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param type Task type
// */
// public SorcererTaskDependency(TaskType type) {
// this.task = type;
// }
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * @param type Task type
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(TaskType type, int iterNo) {
// this(type);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskClass Class which implements Task
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass)
// throws SorcererException {
//
// SorcererTask anno = taskClass.getAnnotation(SorcererTask.class);
// if (anno == null) {
// logger.error("Annotation not found on " + taskClass.toString());
// this.task = null;
// throw new SorcererException(taskClass.getName());
// }
//
// String taskName = anno.name();
// if (taskName == null) {
// logger.error("No taskName found in annotation on " + taskClass.toString());
// this.task = null;
// return;
// }
//
// this.task = SorcererInjector.get().getTaskType(taskName);
//
// // Could not get task type from registry
// if (this.task == null) {
// throw new SorcererException(taskClass.getName());
// }
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * @param taskClass Class which implements Task
// * @param iterNo Iteration number of task dependency
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass, int iterNo)
// throws SorcererException {
// this(taskClass);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskName Task name
// */
// public SorcererTaskDependency(String taskName) {
// this.task = SorcererInjector.get().getTaskType(taskName);
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * @param taskName Task name
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(String taskName, int iterNo) {
// this(taskName);
// this.customIterNo = iterNo;
// }
//
// @Override
// public boolean check(int iterNo) {
// return task != null && StatusManager.get().isTaskComplete(
// task, customIterNo == null ? iterNo : customIterNo);
// }
// }
| import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.dependency.impl.SorcererTaskDependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection;
import com.google.common.collect.ImmutableList; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task. Specifically a singleton task.
*
* @author tshiou
*/
@SorcererTask(name = "test_task_4")
public class TestTask4 extends TestTask {
public static final String TASK_NAME = TestTask4.class.getSimpleName();
private static final int TASK_COUNT = 3;
@Override
public Collection<Dependency> getDependencies(int iterNo) {
return ImmutableList.<Dependency>builder() | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/impl/SorcererTaskDependency.java
// public class SorcererTaskDependency implements Dependency {
//
// private static final Logger logger =
// LoggerFactory.getLogger(SorcererTaskDependency.class);
//
// // Requisite task type
// private final TaskType task;
//
// // Requisite task iteration number
// // If not provided the iteration number will be injected "just-in-time"
// private Integer customIterNo = null;
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param type Task type
// */
// public SorcererTaskDependency(TaskType type) {
// this.task = type;
// }
//
// /**
// * Task dependency constructor based on provided TaskType
// *
// * @param type Task type
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(TaskType type, int iterNo) {
// this(type);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskClass Class which implements Task
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass)
// throws SorcererException {
//
// SorcererTask anno = taskClass.getAnnotation(SorcererTask.class);
// if (anno == null) {
// logger.error("Annotation not found on " + taskClass.toString());
// this.task = null;
// throw new SorcererException(taskClass.getName());
// }
//
// String taskName = anno.name();
// if (taskName == null) {
// logger.error("No taskName found in annotation on " + taskClass.toString());
// this.task = null;
// return;
// }
//
// this.task = SorcererInjector.get().getTaskType(taskName);
//
// // Could not get task type from registry
// if (this.task == null) {
// throw new SorcererException(taskClass.getName());
// }
// }
//
// /**
// * Task dependency can be based on a class that implements {@code Task}
// *
// * <p>
// * The class that is provided must implement {@code Task}, have the
// * {@code SorcererTask} annotation, and also be registered in Sorcerer.
// * If any of these requirements are not met then this constructor will
// * throw a SorcererException.
// * </p>
// *
// * @param taskClass Class which implements Task
// * @param iterNo Iteration number of task dependency
// * @throws SorcererException
// */
// public SorcererTaskDependency(Class<? extends Task> taskClass, int iterNo)
// throws SorcererException {
// this(taskClass);
// this.customIterNo = iterNo;
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * <p>
// * The iteration number of the requisite task will be injected at
// * dependency checking runtime (see {@link #check(int)}).
// * </p>
// *
// * @param taskName Task name
// */
// public SorcererTaskDependency(String taskName) {
// this.task = SorcererInjector.get().getTaskType(taskName);
// }
//
// /**
// * Task dependency constructor based on provided task name
// *
// * @param taskName Task name
// * @param iterNo Iteration number of task dependency
// */
// public SorcererTaskDependency(String taskName, int iterNo) {
// this(taskName);
// this.customIterNo = iterNo;
// }
//
// @Override
// public boolean check(int iterNo) {
// return task != null && StatusManager.get().isTaskComplete(
// task, customIterNo == null ? iterNo : customIterNo);
// }
// }
// Path: src/test/java/com/turn/sorcerer/tasks/TestTask4.java
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.dependency.impl.SorcererTaskDependency;
import com.turn.sorcerer.task.SorcererTask;
import java.util.Collection;
import com.google.common.collect.ImmutableList;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Test task. Specifically a singleton task.
*
* @author tshiou
*/
@SorcererTask(name = "test_task_4")
public class TestTask4 extends TestTask {
public static final String TASK_NAME = TestTask4.class.getSimpleName();
private static final int TASK_COUNT = 3;
@Override
public Collection<Dependency> getDependencies(int iterNo) {
return ImmutableList.<Dependency>builder() | .add(new SorcererTaskDependency("test_task_2")) |
turn/sorcerer | src/test/java/com/turn/sorcerer/tasks/TestTask.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.Task;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Base task class for sorcerer workflow scheduler testing
*
* @author tshiou
*/
public abstract class TestTask implements Task {
private static final Logger logger =
LoggerFactory.getLogger(TestTask.class);
@Override | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/test/java/com/turn/sorcerer/tasks/TestTask.java
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.Task;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Base task class for sorcerer workflow scheduler testing
*
* @author tshiou
*/
public abstract class TestTask implements Task {
private static final Logger logger =
LoggerFactory.getLogger(TestTask.class);
@Override | public void init(Context context) {} |
turn/sorcerer | src/test/java/com/turn/sorcerer/tasks/TestTask.java | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.Task;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Base task class for sorcerer workflow scheduler testing
*
* @author tshiou
*/
public abstract class TestTask implements Task {
private static final Logger logger =
LoggerFactory.getLogger(TestTask.class);
@Override
public void init(Context context) {}
@Override
public void exec(Context context) throws Exception {
for (int i = getTaskCount(); i >= 0 ; i--) {
logger.info(name() + " count " + i + " for sequence number " + context.getIterationNumber());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
protected abstract String name();
protected abstract int getTaskCount();
@Override | // Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/test/java/com/turn/sorcerer/tasks/TestTask.java
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.Task;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.tasks;
/**
* Base task class for sorcerer workflow scheduler testing
*
* @author tshiou
*/
public abstract class TestTask implements Task {
private static final Logger logger =
LoggerFactory.getLogger(TestTask.class);
@Override
public void init(Context context) {}
@Override
public void exec(Context context) throws Exception {
for (int i = getTaskCount(); i >= 0 ; i--) {
logger.info(name() + " count " + i + " for sequence number " + context.getIterationNumber());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
protected abstract String name();
protected abstract int getTaskCount();
@Override | public Collection<Dependency> getDependencies(int iterNo) { |
turn/sorcerer | src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java
import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override | public void init(Context context) { |
turn/sorcerer | src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override
public void init(Context context) {
}
@Override | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java
import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override
public void init(Context context) {
}
@Override | public void exec(Context context) throws SorcererException { } |
turn/sorcerer | src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
| import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List; | /*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override
public void init(Context context) {
}
@Override
public void exec(Context context) throws SorcererException { }
@Override | // Path: src/main/java/com/turn/sorcerer/exception/SorcererException.java
// public class SorcererException extends Exception {
//
// public SorcererException() {
// super();
// }
//
// public SorcererException(String message) {
// super(message);
// }
//
// public SorcererException(Throwable t) {
// super(t);
// }
//
// public SorcererException(String message, Throwable t) {
// super(message, t);
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/dependency/Dependency.java
// public interface Dependency {
//
// /**
// * Checks if the required dependency is fulfilled
// *
// * <p>
// * Implementation of this method should represent a dependency that a task
// * requires.
// * </p>
// *
// * @param iterNo Current iteration number
// * @return Return true if dependency requirement is fulfilled
// */
// boolean check(int iterNo);
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Context.java
// public class Context {
//
// private int iterationNumber;
// private final TypedDictionary properties;
// private final Map<String, Long> metrics = Maps.newHashMap();
//
// public Context(int iterationNumber) {
// this.iterationNumber = iterationNumber;
// this.properties = new TypedDictionary();
// }
//
// public Context(int iterationNumber, TypedDictionary parameters) {
// properties = new TypedDictionary();
// this.iterationNumber = iterationNumber;
// properties.putAll(parameters);
// }
//
//
// public int getIterationNumber() {
// return this.iterationNumber;
// }
//
// public void addMetric(String key, Long value) {
// metrics.put(key, value);
// }
//
// public void putProperty(String key, Object value) {
// properties.put(key, value);
// }
//
// public TypedDictionary getProperties() {
// return this.properties;
// }
// }
//
// Path: src/main/java/com/turn/sorcerer/task/Task.java
// public interface Task {
//
// /**
// * Initializes the task
// *
// * <p>
// * First method called by Sorcerer in the execution of a task. Any task
// * initialization code should be put in the implementation of this
// * method.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#initialize
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// */
// void init(final Context context);
//
// /**
// * Executes the task
// *
// * <p>
// * Implementation of this method should contain the "meat" of the task.
// * This method will not be called if the dependency checking phase returns
// * false. This of course means that this method will be called after both
// * {@code init()} and {@code checkDependencies()}. The successful execution
// * of this method will result in the task being committed to a successful
// * completed state.
// * </p>
// *
// * <p>
// * Obviously if an exception is thrown the task will be committed to an
// * ERROR state. Additionally, exceptions thrown by this method will be
// * caught by Sorcerer, wrapped in a {code SorcererException}, logged,
// * and then an email will be sent to the admins with the exception as the
// * email body (if enabled).
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#execute
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param context Context object containing task execution context.
// * See {@link com.turn.sorcerer.task.Context}.
// * @throws Exception Will be wrapped by a {@code SorcererException} before
// * being thrown into a higher context.
// */
// void exec(final Context context) throws Exception;
//
// /**
// * Provides a Collection of this task's dependencies
// *
// * <p>
// * This method should provide a collection of all the dependencies of this
// * task. Sorcerer will iterate over the collection, and call the
// * {@code check()} method of the {@code Dependency} instance. Once any of
// * the Dependencies return false, Sorcerer will consider the task
// * ineligible to be scheduled.
// * </p>
// *
// * <p>
// * Note that Sorcerer calls this method <i>after</i> {@code init()}.
// * </p>
// *
// * <p>
// * If any complex dependency logic is required (for example if the user
// * desires a task be executed if one of many dependencies are fulfilled)
// * then the logic should be contained in a custom implementation of the
// * {@link com.turn.sorcerer.dependency.Dependency} class.
// * </p>
// *
// * @see com.turn.sorcerer.task.executable.ExecutableTask#checkDependencies
// * @see com.turn.sorcerer.executor.TaskExecutor#call
// *
// * @param iterNo Iteration number of the task being executed
// * @return Collection of Dependency objects
// */
// Collection<Dependency> getDependencies(int iterNo);
//
// void abort();
// }
// Path: src/main/java/com/turn/sorcerer/task/impl/DefaultTask.java
import com.turn.sorcerer.exception.SorcererException;
import com.turn.sorcerer.dependency.Dependency;
import com.turn.sorcerer.task.Context;
import com.turn.sorcerer.task.SorcererTask;
import com.turn.sorcerer.task.Task;
import java.util.List;
/*
* Copyright (c) 2015, Turn Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE file.
*/
package com.turn.sorcerer.task.impl;
/**
* Class Description Here
*
* @author tshiou
*/
@SorcererTask(name = "_default_task")
public class DefaultTask implements Task {
@Override
public void init(Context context) {
}
@Override
public void exec(Context context) throws SorcererException { }
@Override | public List<Dependency> getDependencies(int iterNo) { |
xcurator/xcurator | test/edu/toronto/cs/xcurator/cli/mapping/XbrlEntityFilteringTest.java | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
| import edu.toronto.cs.xcurator.common.DataDocument;
import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli.mapping;
/**
*
* @author Amir
*/
public class XbrlEntityFilteringTest extends TestCase {
public XbrlEntityFilteringTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(XbrlEntityFilteringTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of process method, of class XbrlEntityFiltering.
*/
public void testProcess() {
System.out.println("process");
List<DataDocument> dataDocuments = null; | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
// Path: test/edu/toronto/cs/xcurator/cli/mapping/XbrlEntityFilteringTest.java
import edu.toronto.cs.xcurator.common.DataDocument;
import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli.mapping;
/**
*
* @author Amir
*/
public class XbrlEntityFilteringTest extends TestCase {
public XbrlEntityFilteringTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(XbrlEntityFilteringTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of process method, of class XbrlEntityFiltering.
*/
public void testProcess() {
System.out.println("process");
List<DataDocument> dataDocuments = null; | Mapping mapping = null; |
xcurator/xcurator | src/edu/toronto/cs/xcurator/eval/GoldStandardGenerator.java | // Path: src/edu/toronto/cs/xcurator/utils/StrUtils.java
// public class StrUtils {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String nextRandString() {
// return new BigInteger(130, random).toString(32);
// }
//
// public static void main(String[] args) {
// for (int i = 1; i < 100; i++) {
// System.out.println(nextRandString());
// }
// }
// }
| import edu.toronto.cs.xcurator.utils.StrUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.semanticweb.yars.nx.parser.NxParser;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; | tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// tf.setOutputProperty(OutputKeys.INDENT, "yes");
// tf.setOutputProperty(OutputKeys.METHOD, "xml");
// tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(dataDocument);
StreamResult sr = new StreamResult(new File(xmlout));
tf.transform(domSource, sr);
} catch (FileNotFoundException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | TransformerException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void modifyValues(Node node) {
// do something with the current node instead of System.out
// System.out.println(node);
// System.out.println("NodeName:" + node.getNodeName());
// System.out.println("NodeValue:" + node.getNodeValue());
// System.out.println("NodeType:" + node.getNodeType());
if (node.getNodeType() == Node.TEXT_NODE) {
// System.out.println("TextContent:" + node.getTextContent()); | // Path: src/edu/toronto/cs/xcurator/utils/StrUtils.java
// public class StrUtils {
//
// private static final SecureRandom random = new SecureRandom();
//
// public static String nextRandString() {
// return new BigInteger(130, random).toString(32);
// }
//
// public static void main(String[] args) {
// for (int i = 1; i < 100; i++) {
// System.out.println(nextRandString());
// }
// }
// }
// Path: src/edu/toronto/cs/xcurator/eval/GoldStandardGenerator.java
import edu.toronto.cs.xcurator.utils.StrUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.semanticweb.yars.nx.parser.NxParser;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
// tf.setOutputProperty(OutputKeys.INDENT, "yes");
// tf.setOutputProperty(OutputKeys.METHOD, "xml");
// tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource domSource = new DOMSource(dataDocument);
StreamResult sr = new StreamResult(new File(xmlout));
tf.transform(domSource, sr);
} catch (FileNotFoundException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | TransformerException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inputStream.close();
} catch (IOException ex) {
Logger.getLogger(GoldStandardGenerator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void modifyValues(Node node) {
// do something with the current node instead of System.out
// System.out.println(node);
// System.out.println("NodeName:" + node.getNodeName());
// System.out.println("NodeValue:" + node.getNodeValue());
// System.out.println("NodeType:" + node.getNodeType());
if (node.getNodeType() == Node.TEXT_NODE) {
// System.out.println("TextContent:" + node.getTextContent()); | node.setTextContent(StrUtils.nextRandString()); |
xcurator/xcurator | src/edu/toronto/cs/xcurator/discoverer/MappingDiscoveryStep.java | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
| import edu.toronto.cs.xcurator.common.DataDocument;
import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List; | /*
* Copyright (c) 2013, University of Toronto.
*
* 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 edu.toronto.cs.xcurator.discoverer;
/**
*
* @author zhuerkan
*/
public interface MappingDiscoveryStep {
public enum TYPE {
BASIC('B'),
INTERLIKNING('I'),
KEYATTRIBUTE('K'),
REMOVE_GROUPING_NODES('G');
private final char id;
TYPE(char id) {
this.id = id;
}
public char getValue() {
return id;
}
}
/**
* Processes the mapping.
*
* @param dataDocuments A list of XML data documents to be processed
* @param mapping The map of processed entities. Note that the step should
* only modify the mapping.
*/ | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
// Path: src/edu/toronto/cs/xcurator/discoverer/MappingDiscoveryStep.java
import edu.toronto.cs.xcurator.common.DataDocument;
import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List;
/*
* Copyright (c) 2013, University of Toronto.
*
* 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 edu.toronto.cs.xcurator.discoverer;
/**
*
* @author zhuerkan
*/
public interface MappingDiscoveryStep {
public enum TYPE {
BASIC('B'),
INTERLIKNING('I'),
KEYATTRIBUTE('K'),
REMOVE_GROUPING_NODES('G');
private final char id;
TYPE(char id) {
this.id = id;
}
public char getValue() {
return id;
}
}
/**
* Processes the mapping.
*
* @param dataDocuments A list of XML data documents to be processed
* @param mapping The map of processed entities. Note that the step should
* only modify the mapping.
*/ | void process(List<DataDocument> dataDocuments, Mapping mapping); |
xcurator/xcurator | src/edu/toronto/cs/xcurator/mapping/XmlBasedMapping.java | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
| import edu.toronto.cs.xcurator.common.NsContext;
import edu.toronto.cs.xcurator.utils.IOUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; | return tagNamePrefix + ":" + mappingTagName;
}
public String getEntityNodeName() {
return tagNamePrefix + ":" + entityTagName;
}
public String getAttributeNodeName() {
return tagNamePrefix + ":" + attributeTagName;
}
public String getRelationNodeName() {
return tagNamePrefix + ":" + relationTagName;
}
public String getReferenceNodeName() {
return tagNamePrefix + ":" + referenceTagName;
}
public String getIdNodeName() {
return tagNamePrefix + ":" + idTagName;
}
@Override
public String toString() {
return "{ \"XmlBasedMapping\": "
+ "{"
+ "\"initialized\":" + "\"" + initialized + "\""
+ ", \"namespaceUri\":" + "\"" + namespaceUri + "\""
+ ", \"baseNamespaceContext\":" + "\"" + baseNamespaceContext + "\"" | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
// Path: src/edu/toronto/cs/xcurator/mapping/XmlBasedMapping.java
import edu.toronto.cs.xcurator.common.NsContext;
import edu.toronto.cs.xcurator.utils.IOUtils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
return tagNamePrefix + ":" + mappingTagName;
}
public String getEntityNodeName() {
return tagNamePrefix + ":" + entityTagName;
}
public String getAttributeNodeName() {
return tagNamePrefix + ":" + attributeTagName;
}
public String getRelationNodeName() {
return tagNamePrefix + ":" + relationTagName;
}
public String getReferenceNodeName() {
return tagNamePrefix + ":" + referenceTagName;
}
public String getIdNodeName() {
return tagNamePrefix + ":" + idTagName;
}
@Override
public String toString() {
return "{ \"XmlBasedMapping\": "
+ "{"
+ "\"initialized\":" + "\"" + initialized + "\""
+ ", \"namespaceUri\":" + "\"" + namespaceUri + "\""
+ ", \"baseNamespaceContext\":" + "\"" + baseNamespaceContext + "\"" | + ", \"entities\":" + IOUtils.printMapAsJson(entities) |
xcurator/xcurator | src/edu/toronto/cs/xcurator/eval/EvalUtil.java | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
| import edu.toronto.cs.xcurator.utils.IOUtils;
import edu.toronto.cs.xml2rdf.xml.XMLUtils;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; | System.out.println("size: " + result.size());
System.out.println();
System.out.println("ground:\n " + ground);
System.out.println("size: " + ground.size());
System.out.println();
System.out.println("intersection:\n " + intersection);
System.out.println("size: " + intersection.size());
System.out.println();
}
double pr = (double) intersection.size() / result.size();
double re = (double) intersection.size() / ground.size();
Accuracy ac = new Accuracy(pr, re);
return ac;
}
private static void printAccuracyStats(Set<String> attributeSet, Set<String> grAttributesSet, boolean verbose) {
Accuracy acAttr = evaluate(attributeSet, grAttributesSet, verbose);
final String P = df.format(acAttr.precision());
System.out.println("Prec:" + "\t" + P);
final String R = df.format(acAttr.recall());
System.out.println("Recall:" + "\t" + R);
final String F1 = df.format(acAttr.fscore(1.0));
System.out.println("F1:" + "\t" + F1);
System.out.println(P + "\t" + R + "\t" + F1);
}
public static Set<String> readAttrEntFile(String filename) { | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
// Path: src/edu/toronto/cs/xcurator/eval/EvalUtil.java
import edu.toronto.cs.xcurator.utils.IOUtils;
import edu.toronto.cs.xml2rdf.xml.XMLUtils;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
System.out.println("size: " + result.size());
System.out.println();
System.out.println("ground:\n " + ground);
System.out.println("size: " + ground.size());
System.out.println();
System.out.println("intersection:\n " + intersection);
System.out.println("size: " + intersection.size());
System.out.println();
}
double pr = (double) intersection.size() / result.size();
double re = (double) intersection.size() / ground.size();
Accuracy ac = new Accuracy(pr, re);
return ac;
}
private static void printAccuracyStats(Set<String> attributeSet, Set<String> grAttributesSet, boolean verbose) {
Accuracy acAttr = evaluate(attributeSet, grAttributesSet, verbose);
final String P = df.format(acAttr.precision());
System.out.println("Prec:" + "\t" + P);
final String R = df.format(acAttr.recall());
System.out.println("Recall:" + "\t" + R);
final String F1 = df.format(acAttr.fscore(1.0));
System.out.println("F1:" + "\t" + F1);
System.out.println(P + "\t" + R + "\t" + F1);
}
public static Set<String> readAttrEntFile(String filename) { | List<String> lines = IOUtils.readFileLineByLine(filename); |
xcurator/xcurator | test/edu/toronto/cs/xcurator/cli/CliSuite.java | // Path: test/edu/toronto/cs/xcurator/cli/config/ConfigSuite.java
// public class ConfigSuite extends TestCase {
//
// public ConfigSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("ConfigSuite");
// suite.addTest(RunConfigTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
//
// Path: test/edu/toronto/cs/xcurator/cli/mapping/MappingSuite.java
// public class MappingSuite extends TestCase {
//
// public MappingSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("MappingSuite");
// suite.addTest(MappingFactoryTest.suite());
// suite.addTest(XbrlEntityFilteringTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
| import edu.toronto.cs.xcurator.cli.config.ConfigSuite;
import edu.toronto.cs.xcurator.cli.mapping.MappingSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli;
/**
*
* @author Amir
*/
public class CliSuite extends TestCase {
public CliSuite(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite("CliSuite");
suite.addTest(CLIRunnerTest.suite()); | // Path: test/edu/toronto/cs/xcurator/cli/config/ConfigSuite.java
// public class ConfigSuite extends TestCase {
//
// public ConfigSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("ConfigSuite");
// suite.addTest(RunConfigTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
//
// Path: test/edu/toronto/cs/xcurator/cli/mapping/MappingSuite.java
// public class MappingSuite extends TestCase {
//
// public MappingSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("MappingSuite");
// suite.addTest(MappingFactoryTest.suite());
// suite.addTest(XbrlEntityFilteringTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
// Path: test/edu/toronto/cs/xcurator/cli/CliSuite.java
import edu.toronto.cs.xcurator.cli.config.ConfigSuite;
import edu.toronto.cs.xcurator.cli.mapping.MappingSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli;
/**
*
* @author Amir
*/
public class CliSuite extends TestCase {
public CliSuite(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite("CliSuite");
suite.addTest(CLIRunnerTest.suite()); | suite.addTest(MappingSuite.suite()); |
xcurator/xcurator | test/edu/toronto/cs/xcurator/cli/CliSuite.java | // Path: test/edu/toronto/cs/xcurator/cli/config/ConfigSuite.java
// public class ConfigSuite extends TestCase {
//
// public ConfigSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("ConfigSuite");
// suite.addTest(RunConfigTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
//
// Path: test/edu/toronto/cs/xcurator/cli/mapping/MappingSuite.java
// public class MappingSuite extends TestCase {
//
// public MappingSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("MappingSuite");
// suite.addTest(MappingFactoryTest.suite());
// suite.addTest(XbrlEntityFilteringTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
| import edu.toronto.cs.xcurator.cli.config.ConfigSuite;
import edu.toronto.cs.xcurator.cli.mapping.MappingSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli;
/**
*
* @author Amir
*/
public class CliSuite extends TestCase {
public CliSuite(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite("CliSuite");
suite.addTest(CLIRunnerTest.suite());
suite.addTest(MappingSuite.suite());
suite.addTest(UtilTest.suite());
suite.addTest(RdfFactoryTest.suite()); | // Path: test/edu/toronto/cs/xcurator/cli/config/ConfigSuite.java
// public class ConfigSuite extends TestCase {
//
// public ConfigSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("ConfigSuite");
// suite.addTest(RunConfigTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
//
// Path: test/edu/toronto/cs/xcurator/cli/mapping/MappingSuite.java
// public class MappingSuite extends TestCase {
//
// public MappingSuite(String testName) {
// super(testName);
// }
//
// public static Test suite() {
// TestSuite suite = new TestSuite("MappingSuite");
// suite.addTest(MappingFactoryTest.suite());
// suite.addTest(XbrlEntityFilteringTest.suite());
// return suite;
// }
//
// @Override
// protected void setUp() throws Exception {
// super.setUp();
// }
//
// @Override
// protected void tearDown() throws Exception {
// super.tearDown();
// }
//
// }
// Path: test/edu/toronto/cs/xcurator/cli/CliSuite.java
import edu.toronto.cs.xcurator.cli.config.ConfigSuite;
import edu.toronto.cs.xcurator.cli.mapping.MappingSuite;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli;
/**
*
* @author Amir
*/
public class CliSuite extends TestCase {
public CliSuite(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite("CliSuite");
suite.addTest(CLIRunnerTest.suite());
suite.addTest(MappingSuite.suite());
suite.addTest(UtilTest.suite());
suite.addTest(RdfFactoryTest.suite()); | suite.addTest(ConfigSuite.suite()); |
xcurator/xcurator | test/edu/toronto/cs/xcurator/cli/mapping/MappingFactoryTest.java | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
| import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.w3c.dom.Document; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli.mapping;
/**
*
* @author Amir
*/
public class MappingFactoryTest extends TestCase {
public MappingFactoryTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(MappingFactoryTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of createInstance method, of class MappingFactory.
*/
public void testCreateInstance_Document_String() {
System.out.println("createInstance");
Document xmlDocument = null;
String steps = "";
MappingFactory instance = null; | // Path: src/edu/toronto/cs/xcurator/mapping/Mapping.java
// public interface Mapping {
//
// /**
// * Check if this mapping is initialized.
// *
// * @return
// */
// boolean isInitialized();
//
// /**
// * Set this mapping as initialized, return success flag.
// *
// * @return true if successfully initialized, false if not successful.
// */
// boolean setInitialized();
//
// /**
// * Set the base namespace context of the XML document to be transformed
// * using this mapping. This namespace context can be overrided by individual
// * entities.
// *
// * @param nsContext
// */
// void setBaseNamespaceContext(NsContext nsContext);
//
// /**
// * Get the base namespace context of the XML document to be transformed
// * using this mapping.
// *
// * @return
// */
// NsContext getBaseNamespaceContext();
//
// void addEntity(Schema schema);
//
// Schema getEntity(String id);
//
// void removeEntity(String id);
//
// public Map<String, Schema> getEntities();
//
// Iterator<Schema> getEntityIterator();
//
// public void removeInvalidRelations();
//
// }
// Path: test/edu/toronto/cs/xcurator/cli/mapping/MappingFactoryTest.java
import edu.toronto.cs.xcurator.mapping.Mapping;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.w3c.dom.Document;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.toronto.cs.xcurator.cli.mapping;
/**
*
* @author Amir
*/
public class MappingFactoryTest extends TestCase {
public MappingFactoryTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(MappingFactoryTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of createInstance method, of class MappingFactory.
*/
public void testCreateInstance_Document_String() {
System.out.println("createInstance");
Document xmlDocument = null;
String steps = "";
MappingFactory instance = null; | Mapping expResult = null; |
xcurator/xcurator | src/edu/toronto/cs/xcurator/mapping/Schema.java | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
| import edu.toronto.cs.xcurator.common.NsContext;
import edu.toronto.cs.xcurator.utils.IOUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.Element; |
// Return the XML type from which this entity was extracted
public String getXmlTypeUri() {
return xmlTypeUri;
}
public String getRdfTypeUri() {
return rdfTypeUri;
}
public void resetRdfTypeUri(String typeUri) {
rdfTypeUri = typeUri;
}
@Override
public String toString() {
StringBuilder sbForInstances = new StringBuilder();
sbForInstances.append("[");
if (!instances.isEmpty()) {
for (Element elem : instances) {
sbForInstances.append(elem.getNodeValue()).append(", ");
}
sbForInstances.deleteCharAt(sbForInstances.length() - 1);
sbForInstances.deleteCharAt(sbForInstances.length() - 1);
}
sbForInstances.append("]");
return "{"
+ "\"Schema\": {"
+ "\"namespaceContext\":" + "\"" + namespaceContext + "\""
+ ", \"xmlTypeUri\":" + "\"" + xmlTypeUri + "\"" | // Path: src/edu/toronto/cs/xcurator/utils/IOUtils.java
// public class IOUtils {
//
// public static List<String> readFileLineByLine(String file) {
// String content = null;
// try {
// content = FileUtils.readFileToString(new File(file));
// } catch (IOException ex) {
// Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
// }
// List<String> lines = Arrays.asList(content.split("\\r\\n|\\n|\\r"));
// return lines;
// }
//
// public static <T> String printMapAsJson(Map<String, T> map) {
// StringBuilder sb = new StringBuilder();
// if (map.isEmpty()) {
// return "{}";
// }
// sb.append("{");
// for (String key : map.keySet()) {
// final Object val = (Object) map.get(key);
// sb.append("\"").append(key).append("\":");
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(val.toString());
// if (val.getClass().isPrimitive()) {
// sb.append("\"");
// }
// sb.append(",");
// }
// sb.deleteCharAt(sb.length() - 1);
// sb.append("}");
// return sb.toString();
// }
//
// public static void main(String[] args) {
// Map<String, String> map = new HashMap<>();
// map.put("hello", "345");
// map.put("bye", "byebye");
// System.out.println(printMapAsJson(map));
// }
// }
// Path: src/edu/toronto/cs/xcurator/mapping/Schema.java
import edu.toronto.cs.xcurator.common.NsContext;
import edu.toronto.cs.xcurator.utils.IOUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.Element;
// Return the XML type from which this entity was extracted
public String getXmlTypeUri() {
return xmlTypeUri;
}
public String getRdfTypeUri() {
return rdfTypeUri;
}
public void resetRdfTypeUri(String typeUri) {
rdfTypeUri = typeUri;
}
@Override
public String toString() {
StringBuilder sbForInstances = new StringBuilder();
sbForInstances.append("[");
if (!instances.isEmpty()) {
for (Element elem : instances) {
sbForInstances.append(elem.getNodeValue()).append(", ");
}
sbForInstances.deleteCharAt(sbForInstances.length() - 1);
sbForInstances.deleteCharAt(sbForInstances.length() - 1);
}
sbForInstances.append("]");
return "{"
+ "\"Schema\": {"
+ "\"namespaceContext\":" + "\"" + namespaceContext + "\""
+ ", \"xmlTypeUri\":" + "\"" + xmlTypeUri + "\"" | + ", \"relations\":" + IOUtils.printMapAsJson(relations) |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/FileUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.os.Environment;
import android.os.StatFs;
import com.devin.UtilManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream; | package com.devin.util;
/**
* <p>Description: 关于File的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class FileUtils {
/**
* 获取系统存储路径
*
* @return 系统存储路径
*/
public static String getRootDirPath() {
return Environment.getRootDirectory().getAbsolutePath();
}
/**
* 获取跟目录下的 Download 目录
* @return
*/
public static String getDownloadPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
}
/**
* 获取跟目录下的 DCIM 目录
* @return
*/
public static String getDCIMPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
}
/**
* 查询设备是否有不可被移除的sd卡
*
* @return true 有,false 没有
*/
public static boolean hasSDCard() {
return Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED) && !Environment.isExternalStorageRemovable();
}
/**
* 得到SD的目录路径
*
* @return SD的目录路径
*/
public static String getSDPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* 获取SD卡的剩余容量 单位byte
*
* @return 如果有sd卡 则返回实际剩余容量,没有则返回 0
*/
public static long getSDAvailableSize() {
if (hasSDCard()) {
StatFs stat = new StatFs(getSDPath());
// 获取空闲的数据块的数量
long availableBlocks = stat.getAvailableBlocks() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
/**
* 得到SDCard/Android/data/应用的包名/files/ 目录
*
* @return SDCard/Android/data/应用的包名/files/目录 未获取到则返回null
*/
public static String getExternalFilesDir() {
String path = null; | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/FileUtils.java
import android.os.Environment;
import android.os.StatFs;
import com.devin.UtilManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
package com.devin.util;
/**
* <p>Description: 关于File的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class FileUtils {
/**
* 获取系统存储路径
*
* @return 系统存储路径
*/
public static String getRootDirPath() {
return Environment.getRootDirectory().getAbsolutePath();
}
/**
* 获取跟目录下的 Download 目录
* @return
*/
public static String getDownloadPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
}
/**
* 获取跟目录下的 DCIM 目录
* @return
*/
public static String getDCIMPath() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
}
/**
* 查询设备是否有不可被移除的sd卡
*
* @return true 有,false 没有
*/
public static boolean hasSDCard() {
return Environment.getExternalStorageState()
.equals(Environment.MEDIA_MOUNTED) && !Environment.isExternalStorageRemovable();
}
/**
* 得到SD的目录路径
*
* @return SD的目录路径
*/
public static String getSDPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* 获取SD卡的剩余容量 单位byte
*
* @return 如果有sd卡 则返回实际剩余容量,没有则返回 0
*/
public static long getSDAvailableSize() {
if (hasSDCard()) {
StatFs stat = new StatFs(getSDPath());
// 获取空闲的数据块的数量
long availableBlocks = stat.getAvailableBlocks() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}
/**
* 得到SDCard/Android/data/应用的包名/files/ 目录
*
* @return SDCard/Android/data/应用的包名/files/目录 未获取到则返回null
*/
public static String getExternalFilesDir() {
String path = null; | File file = UtilManager.getContext().getExternalFilesDir(null); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/DensityUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import com.devin.UtilManager; | package com.devin.util;
/**
* <p>Description: 关于密度转换的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class DensityUtils {
/**
* 根据手机的分辨率从 dip 的单位 转成为 px(像素)
* @param dpValue dip
* @return px
*/
public static int dip2px( float dpValue) { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/DensityUtils.java
import com.devin.UtilManager;
package com.devin.util;
/**
* <p>Description: 关于密度转换的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class DensityUtils {
/**
* 根据手机的分辨率从 dip 的单位 转成为 px(像素)
* @param dpValue dip
* @return px
*/
public static int dip2px( float dpValue) { | final float scale = UtilManager.getContext().getResources().getDisplayMetrics().density; |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/ToastUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.support.annotation.StringRes;
import android.view.Gravity;
import android.widget.Toast;
import com.devin.UtilManager; | package com.devin.util;
/**
* <p>Description: 关于 Toast 的工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/26.
*/
public class ToastUtils {
/**
* Make a standard toast that just contains a text view with the text from a resource.
* @param resId The resource id of the string resource to use. Can be formatted tex
*/
public static void showCenter(@StringRes int resId) { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/ToastUtils.java
import android.support.annotation.StringRes;
import android.view.Gravity;
import android.widget.Toast;
import com.devin.UtilManager;
package com.devin.util;
/**
* <p>Description: 关于 Toast 的工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/26.
*/
public class ToastUtils {
/**
* Make a standard toast that just contains a text view with the text from a resource.
* @param resId The resource id of the string resource to use. Can be formatted tex
*/
public static void showCenter(@StringRes int resId) { | showCenter(UtilManager.getContext().getResources().getString(resId)); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/ImageLoader.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
| import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform; | /**
* 加载URI
*
* @param context
* @param uri
* @param imageView
*/
public static void loadUri(Context context, Uri uri, @DrawableRes int placeholder, ImageView imageView) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder);
Glide.with(context)
.load(uri)
.apply(requestOptions)
.into(imageView);
}
//======================================================================
/**
* 加载图片
*
* @param imgUrl
* @param imageView
*/
public static void load(String imgUrl, ImageView imageView) { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/ImageLoader.java
import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform;
/**
* 加载URI
*
* @param context
* @param uri
* @param imageView
*/
public static void loadUri(Context context, Uri uri, @DrawableRes int placeholder, ImageView imageView) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder);
Glide.with(context)
.load(uri)
.apply(requestOptions)
.into(imageView);
}
//======================================================================
/**
* 加载图片
*
* @param imgUrl
* @param imageView
*/
public static void load(String imgUrl, ImageView imageView) { | load(UtilManager.getContext(), imgUrl, imageView); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/ImageLoader.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
| import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform; | loadRound(UtilManager.getContext(), imgUrl, imageView, radiusDp);
}
/**
* 加载圆角图
*
* @param context
* @param imgUrl
* @param imageView
* @param radiusDp
*/
public static void loadRound(Context context, String imgUrl, ImageView imageView, int radiusDp) {
loadRound(context, imgUrl, R.drawable.shape_default_round_bg, imageView, radiusDp);
}
/**
* 加载圆角图
*
* @param context
* @param imgUrl
* @param placeholder
* @param imageView
* @param radiusDp
*/
public static void loadRound(Context context, String imgUrl, @DrawableRes int placeholder, ImageView imageView, int radiusDp) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder) | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/ImageLoader.java
import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform;
loadRound(UtilManager.getContext(), imgUrl, imageView, radiusDp);
}
/**
* 加载圆角图
*
* @param context
* @param imgUrl
* @param imageView
* @param radiusDp
*/
public static void loadRound(Context context, String imgUrl, ImageView imageView, int radiusDp) {
loadRound(context, imgUrl, R.drawable.shape_default_round_bg, imageView, radiusDp);
}
/**
* 加载圆角图
*
* @param context
* @param imgUrl
* @param placeholder
* @param imageView
* @param radiusDp
*/
public static void loadRound(Context context, String imgUrl, @DrawableRes int placeholder, ImageView imageView, int radiusDp) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder) | .transform(new GlideRoundTransform(radiusDp)); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/ImageLoader.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
| import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform; | */
public static void loadCircle(String imgUrl, ImageView imageView) {
loadCircle(UtilManager.getContext(), imgUrl, imageView);
}
/**
* 加载圆图
*
* @param context
* @param imgUrl
* @param imageView
*/
public static void loadCircle(Context context, String imgUrl, ImageView imageView) {
loadCircle(context, imgUrl, R.drawable.shape_default_circle_bg, imageView);
}
/**
* 加载圆图
*
* @param context
* @param imgUrl
* @param placeholder
* @param imageView
*/
public static void loadCircle(Context context, String imgUrl, @DrawableRes int placeholder, ImageView imageView) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder) | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// private Paint mBorderPaint;
// private float mBorderWidth;
//
// public GlideCircleTransform() {
// super();
// }
//
// public GlideCircleTransform(int borderWidth, int borderColor) {
// super();
// mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;
//
// mBorderPaint = new Paint();
// mBorderPaint.setDither(true);
// mBorderPaint.setAntiAlias(true);
// mBorderPaint.setColor(borderColor);
// mBorderPaint.setStyle(Paint.Style.STROKE);
// mBorderPaint.setStrokeWidth(mBorderWidth);
// }
//
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// return circleCrop(pool, toTransform);
// }
//
// private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
//
// int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// if (mBorderPaint != null) {
// float borderRadius = r - mBorderWidth / 2;
// canvas.drawCircle(r, r, borderRadius, mBorderPaint);
// }
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
//
// Path: utilslibrary/src/main/java/com/devin/glide/GlideRoundTransform.java
// public class GlideRoundTransform extends CenterCrop {
// private float radius;
//
//
// public GlideRoundTransform(int dp) {
// super();
// this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
//
// }
//
// @Override
// protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
// Bitmap transform = super.transform(pool, toTransform, outWidth, outHeight);
// return roundCrop(pool, transform);
// }
//
// private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
// if (source == null) {
// return null;
// }
// Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
// canvas.drawRoundRect(rectF, radius, radius, paint);
// return result;
// }
//
//
// @Override
// public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
//
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/ImageLoader.java
import android.content.Context;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.devin.UtilManager;
import com.devin.glide.GlideCircleTransform;
import com.devin.glide.GlideRoundTransform;
*/
public static void loadCircle(String imgUrl, ImageView imageView) {
loadCircle(UtilManager.getContext(), imgUrl, imageView);
}
/**
* 加载圆图
*
* @param context
* @param imgUrl
* @param imageView
*/
public static void loadCircle(Context context, String imgUrl, ImageView imageView) {
loadCircle(context, imgUrl, R.drawable.shape_default_circle_bg, imageView);
}
/**
* 加载圆图
*
* @param context
* @param imgUrl
* @param placeholder
* @param imageView
*/
public static void loadCircle(Context context, String imgUrl, @DrawableRes int placeholder, ImageView imageView) {
RequestOptions requestOptions =
new RequestOptions()
.placeholder(placeholder)
.error(placeholder) | .transform(new GlideCircleTransform()); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/StrXmlUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.support.annotation.StringRes;
import com.devin.UtilManager; | package com.devin.util;
/**
* <p>Description: 关于string.xml 转 String 的工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/26.
*/
public class StrXmlUtils {
/**
* @param resId
* @return
*/
public static String getString(@StringRes int resId) { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/StrXmlUtils.java
import android.support.annotation.StringRes;
import com.devin.UtilManager;
package com.devin.util;
/**
* <p>Description: 关于string.xml 转 String 的工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/26.
*/
public class StrXmlUtils {
/**
* @param resId
* @return
*/
public static String getString(@StringRes int resId) { | return UtilManager.getContext().getResources().getString(resId); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/ClipboardUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import com.devin.UtilManager; | package com.devin.util;
/**
* <p>Description: 关于剪切板的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class ClipboardUtils {
/**
* 复制文本到剪切板
*
* @param text 文本
*/
public static void copy2Clipboard(String text) { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/ClipboardUtils.java
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import com.devin.UtilManager;
package com.devin.util;
/**
* <p>Description: 关于剪切板的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class ClipboardUtils {
/**
* 复制文本到剪切板
*
* @param text 文本
*/
public static void copy2Clipboard(String text) { | ClipboardManager clipboardManager = (ClipboardManager) UtilManager.getContext() |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/BitmapUtils.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.devin.UtilManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream; | * 根据路径查看是否是图片 支持(.jpg", ".jpeg", ".png", ".bmp")
*
* @param path 路径
* @return true 是,false 不是。
*/
private boolean isImageFile(String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
String[] imgSuffix = {".jpg", ".jpeg", ".png", ".bmp"};
for (String str : imgSuffix) {
if (path.toLowerCase().endsWith(str)) {
return true;
}
}
return false;
}
/**
* 下载并保存图片(需子线程调用)
*
* @param url 图片url
* @param dirPath 存储路径
* @param fileName 图片名称
* @return 下载结果
*/
public static boolean downloadImg(String url, String dirPath, String fileName) {
try { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/BitmapUtils.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.devin.UtilManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
* 根据路径查看是否是图片 支持(.jpg", ".jpeg", ".png", ".bmp")
*
* @param path 路径
* @return true 是,false 不是。
*/
private boolean isImageFile(String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
String[] imgSuffix = {".jpg", ".jpeg", ".png", ".bmp"};
for (String str : imgSuffix) {
if (path.toLowerCase().endsWith(str)) {
return true;
}
}
return false;
}
/**
* 下载并保存图片(需子线程调用)
*
* @param url 图片url
* @param dirPath 存储路径
* @param fileName 图片名称
* @return 下载结果
*/
public static boolean downloadImg(String url, String dirPath, String fileName) {
try { | File imgFile = Glide.with(UtilManager.getContext()).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get(); |
sundevin/utilsLibrary | utilslibrary/src/main/java/com/devin/util/AppInfo.java | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
| import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import com.devin.UtilManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | package com.devin.util;
/**
* <p>Description: 关于当前app信息的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class AppInfo {
/**
* 获取当前应用 的包名
*
* @return
*/
public static String getPackageName() { | // Path: utilslibrary/src/main/java/com/devin/UtilManager.java
// public class UtilManager {
//
// private static Context mContext;
//
// /**
// * 初始化工具类集合
// * @param context context
// */
// public static void init(Context context) {
// mContext = context.getApplicationContext();
// }
//
// public static Context getContext() {
// return mContext;
// }
// }
// Path: utilslibrary/src/main/java/com/devin/util/AppInfo.java
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import com.devin.UtilManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package com.devin.util;
/**
* <p>Description: 关于当前app信息的一些工具类
* <p>Company:
* <p>Email:bjxm2013@163.com
* <p>Created by Devin Sun on 2017/4/25.
*/
public class AppInfo {
/**
* 获取当前应用 的包名
*
* @return
*/
public static String getPackageName() { | return UtilManager.getContext().getPackageName(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.