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 |
|---|---|---|---|---|---|---|
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/patches/block/FastHopper.java | // Path: src/main/java/guichaguri/betterfps/api/IFastHopper.java
// public interface IFastHopper extends IHopper {
//
// /**
// * Whether this hopper is picking up dropped items
// */
// boolean canPickupItems();
//
// /**
// * Updates {@link #canPickupItems}
// */
// void updateFastHopper();
//
// }
//
// Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
//
// Path: src/main/java/guichaguri/betterfps/patchers/FastHopperPatcher.java
// public class FastHopperPatcher implements IClassPatcher {
//
// public static final String PICKUP_ITEMS = "pickupItems";
//
// @Override
// public void patch(Patch patch) {
// ClassNode source = patch.getSourceClass();
// ClassNode target = patch.getTargetClass();
//
// MethodNode method = ASMUtils.findMethod(target, Mappings.M_captureDroppedItems);
// if(method == null) return; // Method doesn't exist?
//
// MethodNode pickupItem = patch.getMethod(PICKUP_ITEMS);
//
// InsnList inst = method.instructions;
//
// List<JumpInsnNode> ifNullNodes = ASMUtils.findNodes(inst, JumpInsnNode.class, Opcodes.IFNULL);
// LocalVariableNode inv = ASMUtils.findVariable(method, Mappings.C_IInventory);
//
// if(ifNullNodes == null || ifNullNodes.isEmpty() || inv == null) return; // Wut
//
// JumpInsnNode ifNull = null;
// JumpInsnNode ifEnd = null;
//
// for(JumpInsnNode node : ifNullNodes) {
// AbstractInsnNode previous = node.getPrevious();
//
// if(previous instanceof VarInsnNode) {
// if(((VarInsnNode)previous).var == inv.index) {
// ifNull = node;
// break;
// }
// }
// }
//
// if(ifNull == null) return; // Wut
//
// for(int i = inst.indexOf(ifNull.label) - 1; i >= 0; i--) {
// AbstractInsnNode node = inst.get(i);
// if(node instanceof JumpInsnNode && node.getOpcode() == Opcodes.GOTO) {
// ifEnd = (JumpInsnNode)node;
// break;
// }
// }
//
// if(ifEnd == null) return; // Wut
//
// InsnList ifCanPickupItems = ASMUtils.insertMethod(source, pickupItem, target, method, ifNull.label, false);
// ifCanPickupItems.add(new JumpInsnNode(Opcodes.IFEQ, ifEnd.label));
// inst.insert(ifNull.label, ifCanPickupItems);
// }
//
// }
| import guichaguri.betterfps.api.IFastHopper;
import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import guichaguri.betterfps.transformers.annotations.Patcher;
import guichaguri.betterfps.transformers.annotations.Reference;
import guichaguri.betterfps.patchers.FastHopperPatcher;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.IHopper;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; | package guichaguri.betterfps.patches.block;
/**
* @author Guilherme Chaguri
*/
@Patcher(FastHopperPatcher.class)
@Condition(Conditions.FAST_HOPPER) | // Path: src/main/java/guichaguri/betterfps/api/IFastHopper.java
// public interface IFastHopper extends IHopper {
//
// /**
// * Whether this hopper is picking up dropped items
// */
// boolean canPickupItems();
//
// /**
// * Updates {@link #canPickupItems}
// */
// void updateFastHopper();
//
// }
//
// Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
//
// Path: src/main/java/guichaguri/betterfps/patchers/FastHopperPatcher.java
// public class FastHopperPatcher implements IClassPatcher {
//
// public static final String PICKUP_ITEMS = "pickupItems";
//
// @Override
// public void patch(Patch patch) {
// ClassNode source = patch.getSourceClass();
// ClassNode target = patch.getTargetClass();
//
// MethodNode method = ASMUtils.findMethod(target, Mappings.M_captureDroppedItems);
// if(method == null) return; // Method doesn't exist?
//
// MethodNode pickupItem = patch.getMethod(PICKUP_ITEMS);
//
// InsnList inst = method.instructions;
//
// List<JumpInsnNode> ifNullNodes = ASMUtils.findNodes(inst, JumpInsnNode.class, Opcodes.IFNULL);
// LocalVariableNode inv = ASMUtils.findVariable(method, Mappings.C_IInventory);
//
// if(ifNullNodes == null || ifNullNodes.isEmpty() || inv == null) return; // Wut
//
// JumpInsnNode ifNull = null;
// JumpInsnNode ifEnd = null;
//
// for(JumpInsnNode node : ifNullNodes) {
// AbstractInsnNode previous = node.getPrevious();
//
// if(previous instanceof VarInsnNode) {
// if(((VarInsnNode)previous).var == inv.index) {
// ifNull = node;
// break;
// }
// }
// }
//
// if(ifNull == null) return; // Wut
//
// for(int i = inst.indexOf(ifNull.label) - 1; i >= 0; i--) {
// AbstractInsnNode node = inst.get(i);
// if(node instanceof JumpInsnNode && node.getOpcode() == Opcodes.GOTO) {
// ifEnd = (JumpInsnNode)node;
// break;
// }
// }
//
// if(ifEnd == null) return; // Wut
//
// InsnList ifCanPickupItems = ASMUtils.insertMethod(source, pickupItem, target, method, ifNull.label, false);
// ifCanPickupItems.add(new JumpInsnNode(Opcodes.IFEQ, ifEnd.label));
// inst.insert(ifNull.label, ifCanPickupItems);
// }
//
// }
// Path: src/main/java/guichaguri/betterfps/patches/block/FastHopper.java
import guichaguri.betterfps.api.IFastHopper;
import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import guichaguri.betterfps.transformers.annotations.Patcher;
import guichaguri.betterfps.transformers.annotations.Reference;
import guichaguri.betterfps.patchers.FastHopperPatcher;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.IHopper;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
package guichaguri.betterfps.patches.block;
/**
* @author Guilherme Chaguri
*/
@Patcher(FastHopperPatcher.class)
@Condition(Conditions.FAST_HOPPER) | public abstract class FastHopper extends TileEntityHopper implements IFastHopper { |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/patches/misc/ServerPatch.java | // Path: src/main/java/guichaguri/betterfps/UpdateChecker.java
// public class UpdateChecker implements Runnable {
//
// private static boolean updateCheck = false;
// private static boolean done = false;
// private static String updateVersion = null;
// private static String updateDownload = null;
//
// public static void check() {
// if(!BetterFpsHelper.getConfig().updateChecker) {
// done = true;
// return;
// }
// if(!updateCheck) {
// updateCheck = true;
// checkForced();
// }
// }
//
// public static void checkForced() {
// done = false;
// Thread thread = new Thread(new UpdateChecker(), "BetterFps Update Checker");
// thread.setDaemon(true);
// thread.start();
// }
//
// public static void showChat(EntityPlayerSP player) {
// if(!done) return;
// if(updateVersion == null && updateDownload == null) return;
// if(!BetterFps.CLIENT) return;
//
// TextComponentTranslation title = new TextComponentTranslation("betterfps.update.available", updateVersion);
// title.setStyle(title.getStyle().setColor(TextFormatting.GREEN).setBold(true));
//
// TextComponentString buttons = new TextComponentString(" ");
// buttons.setStyle(buttons.getStyle().setColor(TextFormatting.YELLOW));
// buttons.appendSibling(createButton(updateDownload, "betterfps.update.button.download"));
// buttons.appendText(" ");
// buttons.appendSibling(createButton(BetterFps.URL, "betterfps.update.button.more"));
//
// int phrase = (int)(Math.random() * 12) + 1;
// TextComponentTranslation desc = new TextComponentTranslation("betterfps.update.phrase." + phrase);
// desc.setStyle(desc.getStyle().setColor(TextFormatting.GRAY));
//
// if(updateVersion.length() < 8) {
// title.appendSibling(buttons);
// player.sendStatusMessage(title, false);
// player.sendStatusMessage(desc, false);
// } else {
// player.sendStatusMessage(title, false);
// player.sendStatusMessage(buttons, false);
// player.sendStatusMessage(desc, false);
// }
//
// updateVersion = null;
// updateDownload = null;
// }
//
// private static void showConsole() {
// if(!done) return;
// if(updateVersion == null && updateDownload == null) return;
//
// BetterFpsHelper.LOG.info("BetterFps " + updateVersion + " is available");
// BetterFpsHelper.LOG.info("Download: " + updateDownload);
// BetterFpsHelper.LOG.info("More: " + BetterFps.URL);
//
// updateVersion = null;
// updateDownload = null;
// }
//
// private static TextComponentTranslation createButton(String link, String key) {
// TextComponentTranslation sib = new TextComponentTranslation(key);
// Style style = sib.getStyle();
// style.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link));
// TextComponentTranslation h = new TextComponentTranslation(key + ".info");
// h.setStyle(h.getStyle().setColor(TextFormatting.RED));
// style.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, h));
// sib.setStyle(style);
// return sib;
// }
//
// @Override
// public void run() {
// try {
// URL url = new URL(BetterFps.UPDATE_URL);
// InputStream in = url.openStream();
// JsonParser parser = new JsonParser();
// JsonObject obj = parser.parse(new InputStreamReader(in)).getAsJsonObject();
// JsonObject versions = obj.getAsJsonObject("versions");
//
// if(!versions.has(BetterFps.MC_VERSION)) return;
// JsonArray array = versions.getAsJsonArray(BetterFps.MC_VERSION);
// if(array.size() == 0) return;
//
// JsonObject latest = array.get(0).getAsJsonObject();
// String version = latest.get("name").getAsString();
//
// if(!version.contains(BetterFps.VERSION)) {
// updateVersion = version;
// updateDownload = latest.get("url").getAsString();
// }
//
// done = true;
//
// if(!BetterFps.CLIENT) {
// showConsole();
// } else {
// if(Minecraft.getMinecraft().player != null) {
// showChat(Minecraft.getMinecraft().player);
// }
// }
// } catch(Exception ex) {
// BetterFpsHelper.LOG.warn("Could not check for updates: " + ex.getMessage());
// } finally {
// done = true;
// }
// }
// }
| import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import guichaguri.betterfps.UpdateChecker;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerProfileCache;
import net.minecraft.util.datafix.DataFixer; | package guichaguri.betterfps.patches.misc;
/**
* @author Guilherme Chaguri
*/
public abstract class ServerPatch extends MinecraftServer {
public ServerPatch(File anvil, Proxy proxy, DataFixer fixer, YggdrasilAuthenticationService auth, MinecraftSessionService session, GameProfileRepository profiles, PlayerProfileCache offlineProfiles) {
super(anvil, proxy, fixer, auth, session, profiles, offlineProfiles);
}
@Copy(Mode.APPEND)
@Override
public boolean init() throws IOException { | // Path: src/main/java/guichaguri/betterfps/UpdateChecker.java
// public class UpdateChecker implements Runnable {
//
// private static boolean updateCheck = false;
// private static boolean done = false;
// private static String updateVersion = null;
// private static String updateDownload = null;
//
// public static void check() {
// if(!BetterFpsHelper.getConfig().updateChecker) {
// done = true;
// return;
// }
// if(!updateCheck) {
// updateCheck = true;
// checkForced();
// }
// }
//
// public static void checkForced() {
// done = false;
// Thread thread = new Thread(new UpdateChecker(), "BetterFps Update Checker");
// thread.setDaemon(true);
// thread.start();
// }
//
// public static void showChat(EntityPlayerSP player) {
// if(!done) return;
// if(updateVersion == null && updateDownload == null) return;
// if(!BetterFps.CLIENT) return;
//
// TextComponentTranslation title = new TextComponentTranslation("betterfps.update.available", updateVersion);
// title.setStyle(title.getStyle().setColor(TextFormatting.GREEN).setBold(true));
//
// TextComponentString buttons = new TextComponentString(" ");
// buttons.setStyle(buttons.getStyle().setColor(TextFormatting.YELLOW));
// buttons.appendSibling(createButton(updateDownload, "betterfps.update.button.download"));
// buttons.appendText(" ");
// buttons.appendSibling(createButton(BetterFps.URL, "betterfps.update.button.more"));
//
// int phrase = (int)(Math.random() * 12) + 1;
// TextComponentTranslation desc = new TextComponentTranslation("betterfps.update.phrase." + phrase);
// desc.setStyle(desc.getStyle().setColor(TextFormatting.GRAY));
//
// if(updateVersion.length() < 8) {
// title.appendSibling(buttons);
// player.sendStatusMessage(title, false);
// player.sendStatusMessage(desc, false);
// } else {
// player.sendStatusMessage(title, false);
// player.sendStatusMessage(buttons, false);
// player.sendStatusMessage(desc, false);
// }
//
// updateVersion = null;
// updateDownload = null;
// }
//
// private static void showConsole() {
// if(!done) return;
// if(updateVersion == null && updateDownload == null) return;
//
// BetterFpsHelper.LOG.info("BetterFps " + updateVersion + " is available");
// BetterFpsHelper.LOG.info("Download: " + updateDownload);
// BetterFpsHelper.LOG.info("More: " + BetterFps.URL);
//
// updateVersion = null;
// updateDownload = null;
// }
//
// private static TextComponentTranslation createButton(String link, String key) {
// TextComponentTranslation sib = new TextComponentTranslation(key);
// Style style = sib.getStyle();
// style.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link));
// TextComponentTranslation h = new TextComponentTranslation(key + ".info");
// h.setStyle(h.getStyle().setColor(TextFormatting.RED));
// style.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, h));
// sib.setStyle(style);
// return sib;
// }
//
// @Override
// public void run() {
// try {
// URL url = new URL(BetterFps.UPDATE_URL);
// InputStream in = url.openStream();
// JsonParser parser = new JsonParser();
// JsonObject obj = parser.parse(new InputStreamReader(in)).getAsJsonObject();
// JsonObject versions = obj.getAsJsonObject("versions");
//
// if(!versions.has(BetterFps.MC_VERSION)) return;
// JsonArray array = versions.getAsJsonArray(BetterFps.MC_VERSION);
// if(array.size() == 0) return;
//
// JsonObject latest = array.get(0).getAsJsonObject();
// String version = latest.get("name").getAsString();
//
// if(!version.contains(BetterFps.VERSION)) {
// updateVersion = version;
// updateDownload = latest.get("url").getAsString();
// }
//
// done = true;
//
// if(!BetterFps.CLIENT) {
// showConsole();
// } else {
// if(Minecraft.getMinecraft().player != null) {
// showChat(Minecraft.getMinecraft().player);
// }
// }
// } catch(Exception ex) {
// BetterFpsHelper.LOG.warn("Could not check for updates: " + ex.getMessage());
// } finally {
// done = true;
// }
// }
// }
// Path: src/main/java/guichaguri/betterfps/patches/misc/ServerPatch.java
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import guichaguri.betterfps.UpdateChecker;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerProfileCache;
import net.minecraft.util.datafix.DataFixer;
package guichaguri.betterfps.patches.misc;
/**
* @author Guilherme Chaguri
*/
public abstract class ServerPatch extends MinecraftServer {
public ServerPatch(File anvil, Proxy proxy, DataFixer fixer, YggdrasilAuthenticationService auth, MinecraftSessionService session, GameProfileRepository profiles, PlayerProfileCache offlineProfiles) {
super(anvil, proxy, fixer, auth, session, profiles, offlineProfiles);
}
@Copy(Mode.APPEND)
@Override
public boolean init() throws IOException { | UpdateChecker.check(); |
Guichaguri/BetterFps | src/test/java/guichaguri/betterfps/test/math/RivensFullMathTest.java | // Path: src/main/java/guichaguri/betterfps/math/RivensFullMath.java
// public class RivensFullMath {
//
// private static final float BF_SIN_TO_COS;
// private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_COUNT;
// private static final float BF_radFull, BF_radToIndex;
// private static final float[] BF_sinFull;
//
// static {
// BF_SIN_TO_COS = (float) (Math.PI * 0.5f);
//
// BF_SIN_BITS = 12;
// BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// BF_radFull = (float) (Math.PI * 2.0);
// BF_radToIndex = BF_SIN_COUNT / BF_radFull;
//
// BF_sinFull = new float[BF_SIN_COUNT];
// for (int i = 0; i < BF_SIN_COUNT; i++) {
// BF_sinFull[i] = (float) Math.sin((i + Math.min(1, i % (BF_SIN_COUNT / 4)) * 0.5) / BF_SIN_COUNT * BF_radFull);
// }
// }
//
// public static float sin(float rad) {
// return BF_sinFull[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float rad) {
// return sin(rad + BF_SIN_TO_COS);
// }
//
// }
| import guichaguri.betterfps.math.RivensFullMath;
import org.junit.Assert;
import org.junit.Test; | package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class RivensFullMathTest {
@Test
public void testSine() { | // Path: src/main/java/guichaguri/betterfps/math/RivensFullMath.java
// public class RivensFullMath {
//
// private static final float BF_SIN_TO_COS;
// private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_COUNT;
// private static final float BF_radFull, BF_radToIndex;
// private static final float[] BF_sinFull;
//
// static {
// BF_SIN_TO_COS = (float) (Math.PI * 0.5f);
//
// BF_SIN_BITS = 12;
// BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// BF_radFull = (float) (Math.PI * 2.0);
// BF_radToIndex = BF_SIN_COUNT / BF_radFull;
//
// BF_sinFull = new float[BF_SIN_COUNT];
// for (int i = 0; i < BF_SIN_COUNT; i++) {
// BF_sinFull[i] = (float) Math.sin((i + Math.min(1, i % (BF_SIN_COUNT / 4)) * 0.5) / BF_SIN_COUNT * BF_radFull);
// }
// }
//
// public static float sin(float rad) {
// return BF_sinFull[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float rad) {
// return sin(rad + BF_SIN_TO_COS);
// }
//
// }
// Path: src/test/java/guichaguri/betterfps/test/math/RivensFullMathTest.java
import guichaguri.betterfps.math.RivensFullMath;
import org.junit.Assert;
import org.junit.Test;
package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class RivensFullMathTest {
@Test
public void testSine() { | float sine = RivensFullMath.sin(1); |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/transformers/Patch.java | // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java
// public class BetterFpsHelper {
//
// public static final Logger LOG = LogManager.getLogger("BetterFps");
//
// private static BetterFpsConfig INSTANCE = null;
// private static File CONFIG_FILE = null;
//
// public static BetterFpsConfig getConfig() {
// if(INSTANCE == null) loadConfig();
// return INSTANCE;
// }
//
// public static void loadConfig() {
// File configPath;
// if(BetterFps.GAME_DIR == null) {
// configPath = new File("config");
// } else {
// configPath = new File(BetterFps.GAME_DIR, "config");
// }
//
// CONFIG_FILE = new File(configPath, "betterfps.json");
//
// // Temporary code - Import old config file to the new one
// File oldConfig;
// if(BetterFps.GAME_DIR == null) {
// oldConfig = new File("config" + File.pathSeparator + "betterfps.json");
// } else {
// oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json");
// }
// if(oldConfig.exists()) {
// FileReader reader = null;
// try {
// reader = new FileReader(oldConfig);
// INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);
// saveConfig();
// return;
// } catch(Exception ex) {
// LOG.error("Could not load the old config file. It will be deleted.");
// } finally {
// IOUtils.closeQuietly(reader);
// oldConfig.deleteOnExit();
// }
// }
// // -------
//
// FileReader reader = null;
// try {
// if(CONFIG_FILE.exists()) {
// reader = new FileReader(CONFIG_FILE);
// INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);
// }
// } catch(Exception ex) {
// LOG.error("Could not load the config file", ex);
// } finally {
// IOUtils.closeQuietly(reader);
// }
//
// if(INSTANCE == null) INSTANCE = new BetterFpsConfig();
//
// saveConfig();
// }
//
// public static void saveConfig() {
// FileWriter writer = null;
// try {
// if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs();
// writer = new FileWriter(CONFIG_FILE);
// new Gson().toJson(INSTANCE, writer);
// } catch(Exception ex) {
// LOG.error("Could not save the config file", ex);
// } finally {
// IOUtils.closeQuietly(writer);
// }
// }
//
// }
| import guichaguri.betterfps.BetterFpsHelper;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import guichaguri.betterfps.transformers.annotations.Patcher;
import guichaguri.betterfps.transformers.annotations.Reference;
import java.util.HashMap;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode; | }
}
// Copy Interfaces
for(String i : sourceClass.interfaces) {
if(!targetClass.interfaces.contains(i)) {
targetClass.interfaces.add(i);
}
}
}
/**
* Patches methods using a custom {@link IClassPatcher}
*/
protected void patch() {
AnnotationNode patcher = ASMUtils.getAnnotation(sourceClass.invisibleAnnotations, Patcher.class);
if(patcher != null) {
Type patcherClass = ASMUtils.getAnnotationValue(patcher, "value", Type.class);
try {
Class c = Class.forName(patcherClass.getClassName());
IClassPatcher cp = (IClassPatcher)c.newInstance();
// Find the references for the custom patcher
findReferences();
// Patch it!
cp.patch(this);
} catch(Exception ex) { | // Path: src/main/java/guichaguri/betterfps/BetterFpsHelper.java
// public class BetterFpsHelper {
//
// public static final Logger LOG = LogManager.getLogger("BetterFps");
//
// private static BetterFpsConfig INSTANCE = null;
// private static File CONFIG_FILE = null;
//
// public static BetterFpsConfig getConfig() {
// if(INSTANCE == null) loadConfig();
// return INSTANCE;
// }
//
// public static void loadConfig() {
// File configPath;
// if(BetterFps.GAME_DIR == null) {
// configPath = new File("config");
// } else {
// configPath = new File(BetterFps.GAME_DIR, "config");
// }
//
// CONFIG_FILE = new File(configPath, "betterfps.json");
//
// // Temporary code - Import old config file to the new one
// File oldConfig;
// if(BetterFps.GAME_DIR == null) {
// oldConfig = new File("config" + File.pathSeparator + "betterfps.json");
// } else {
// oldConfig = new File(BetterFps.GAME_DIR, "config" + File.pathSeparator + "betterfps.json");
// }
// if(oldConfig.exists()) {
// FileReader reader = null;
// try {
// reader = new FileReader(oldConfig);
// INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);
// saveConfig();
// return;
// } catch(Exception ex) {
// LOG.error("Could not load the old config file. It will be deleted.");
// } finally {
// IOUtils.closeQuietly(reader);
// oldConfig.deleteOnExit();
// }
// }
// // -------
//
// FileReader reader = null;
// try {
// if(CONFIG_FILE.exists()) {
// reader = new FileReader(CONFIG_FILE);
// INSTANCE = new Gson().fromJson(reader, BetterFpsConfig.class);
// }
// } catch(Exception ex) {
// LOG.error("Could not load the config file", ex);
// } finally {
// IOUtils.closeQuietly(reader);
// }
//
// if(INSTANCE == null) INSTANCE = new BetterFpsConfig();
//
// saveConfig();
// }
//
// public static void saveConfig() {
// FileWriter writer = null;
// try {
// if(!CONFIG_FILE.exists()) CONFIG_FILE.getParentFile().mkdirs();
// writer = new FileWriter(CONFIG_FILE);
// new Gson().toJson(INSTANCE, writer);
// } catch(Exception ex) {
// LOG.error("Could not save the config file", ex);
// } finally {
// IOUtils.closeQuietly(writer);
// }
// }
//
// }
// Path: src/main/java/guichaguri/betterfps/transformers/Patch.java
import guichaguri.betterfps.BetterFpsHelper;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import guichaguri.betterfps.transformers.annotations.Patcher;
import guichaguri.betterfps.transformers.annotations.Reference;
import java.util.HashMap;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
}
}
// Copy Interfaces
for(String i : sourceClass.interfaces) {
if(!targetClass.interfaces.contains(i)) {
targetClass.interfaces.add(i);
}
}
}
/**
* Patches methods using a custom {@link IClassPatcher}
*/
protected void patch() {
AnnotationNode patcher = ASMUtils.getAnnotation(sourceClass.invisibleAnnotations, Patcher.class);
if(patcher != null) {
Type patcherClass = ASMUtils.getAnnotationValue(patcher, "value", Type.class);
try {
Class c = Class.forName(patcherClass.getClassName());
IClassPatcher cp = (IClassPatcher)c.newInstance();
// Find the references for the custom patcher
findReferences();
// Patch it!
cp.patch(this);
} catch(Exception ex) { | BetterFpsHelper.LOG.error("Couldn't patch class {} with {}", targetClass.name, sourceClass.name); |
Guichaguri/BetterFps | src/test/java/guichaguri/betterfps/test/math/TaylorMathTest.java | // Path: src/main/java/guichaguri/betterfps/math/TaylorMath.java
// public class TaylorMath {
// private static final float BF_SIN_TO_COS;
// static {
// BF_SIN_TO_COS = (float)(Math.PI * 0.5f);
// }
//
// public static float sin(float rad) {
// double x = rad;
//
// double x2 = x * x;
// double x3 = x2 * x;
// double x5 = x2 * x3;
// double x7 = x2 * x5;
// double x9 = x2 * x7;
// double x11 = x2 * x9;
// double x13 = x2 * x11;
// double x15 = x2 * x13;
// double x17 = x2 * x15;
//
// double val = x;
// val -= x3 * 0.16666666666666666666666666666667;
// val += x5 * 0.00833333333333333333333333333333;
// val -= x7 * 1.984126984126984126984126984127e-4;
// val += x9 * 2.7557319223985890652557319223986e-6;
// val -= x11 * 2.5052108385441718775052108385442e-8;
// val += x13 * 1.6059043836821614599392377170155e-10;
// val -= x15 * 7.6471637318198164759011319857881e-13;
// val += x17 * 2.8114572543455207631989455830103e-15;
// return (float) val;
// }
//
// public static float cos(float rad) {
// return sin(rad + BF_SIN_TO_COS);
// }
//
// }
| import guichaguri.betterfps.math.TaylorMath;
import org.junit.Assert;
import org.junit.Test; | package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class TaylorMathTest {
@Test
public void testSine() { | // Path: src/main/java/guichaguri/betterfps/math/TaylorMath.java
// public class TaylorMath {
// private static final float BF_SIN_TO_COS;
// static {
// BF_SIN_TO_COS = (float)(Math.PI * 0.5f);
// }
//
// public static float sin(float rad) {
// double x = rad;
//
// double x2 = x * x;
// double x3 = x2 * x;
// double x5 = x2 * x3;
// double x7 = x2 * x5;
// double x9 = x2 * x7;
// double x11 = x2 * x9;
// double x13 = x2 * x11;
// double x15 = x2 * x13;
// double x17 = x2 * x15;
//
// double val = x;
// val -= x3 * 0.16666666666666666666666666666667;
// val += x5 * 0.00833333333333333333333333333333;
// val -= x7 * 1.984126984126984126984126984127e-4;
// val += x9 * 2.7557319223985890652557319223986e-6;
// val -= x11 * 2.5052108385441718775052108385442e-8;
// val += x13 * 1.6059043836821614599392377170155e-10;
// val -= x15 * 7.6471637318198164759011319857881e-13;
// val += x17 * 2.8114572543455207631989455830103e-15;
// return (float) val;
// }
//
// public static float cos(float rad) {
// return sin(rad + BF_SIN_TO_COS);
// }
//
// }
// Path: src/test/java/guichaguri/betterfps/test/math/TaylorMathTest.java
import guichaguri.betterfps.math.TaylorMath;
import org.junit.Assert;
import org.junit.Test;
package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class TaylorMathTest {
@Test
public void testSine() { | float sine = TaylorMath.sin(1); |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/patches/misc/FogPatch.java | // Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
| import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.IResourceManager; | package guichaguri.betterfps.patches.misc;
/**
* @author Guilherme Chaguri
*/
public abstract class FogPatch extends EntityRenderer {
public FogPatch(Minecraft mc, IResourceManager manager) {
super(mc, manager);
}
@Copy(Mode.REPLACE) | // Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
// Path: src/main/java/guichaguri/betterfps/patches/misc/FogPatch.java
import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.EntityRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.IResourceManager;
package guichaguri.betterfps.patches.misc;
/**
* @author Guilherme Chaguri
*/
public abstract class FogPatch extends EntityRenderer {
public FogPatch(Minecraft mc, IResourceManager manager) {
super(mc, manager);
}
@Copy(Mode.REPLACE) | @Condition(Conditions.FOG_DISABLED) |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/transformers/annotations/Patcher.java | // Path: src/main/java/guichaguri/betterfps/transformers/IClassPatcher.java
// public interface IClassPatcher {
//
// void patch(Patch patch);
// }
| import guichaguri.betterfps.transformers.IClassPatcher;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package guichaguri.betterfps.transformers.annotations;
/**
* Defines a custom class patcher.
* @see IClassPatcher
* @author Guilherme Chaguri
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface Patcher {
| // Path: src/main/java/guichaguri/betterfps/transformers/IClassPatcher.java
// public interface IClassPatcher {
//
// void patch(Patch patch);
// }
// Path: src/main/java/guichaguri/betterfps/transformers/annotations/Patcher.java
import guichaguri.betterfps.transformers.IClassPatcher;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package guichaguri.betterfps.transformers.annotations;
/**
* Defines a custom class patcher.
* @see IClassPatcher
* @author Guilherme Chaguri
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface Patcher {
| Class<? extends IClassPatcher> value(); |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/installer/GuiInstallOptions.java | // Path: src/main/java/guichaguri/betterfps/BetterFps.java
// public class BetterFps {
//
// public static final String MC_VERSION = "1.12";
// public static final String VERSION = "1.4.7";
// public static final String URL = "http://guichaguri.github.io/BetterFps/";
// public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json";
//
// public static boolean CLIENT = false;
// public static File GAME_DIR = null;
//
// }
| import com.eclipsesource.json.JsonObject;
import guichaguri.betterfps.BetterFps;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.swing.*; | package guichaguri.betterfps.installer;
/**
* @author Guilherme Chaguri
*/
public class GuiInstallOptions extends JDialog implements ActionListener, FocusListener {
private final String BROWSE = "browse_directories";
private final String INSTALL = "install";
| // Path: src/main/java/guichaguri/betterfps/BetterFps.java
// public class BetterFps {
//
// public static final String MC_VERSION = "1.12";
// public static final String VERSION = "1.4.7";
// public static final String URL = "http://guichaguri.github.io/BetterFps/";
// public static final String UPDATE_URL = "http://widget.mcf.li/mc-mods/minecraft/229876-betterfps.json";
//
// public static boolean CLIENT = false;
// public static File GAME_DIR = null;
//
// }
// Path: src/main/java/guichaguri/betterfps/installer/GuiInstallOptions.java
import com.eclipsesource.json.JsonObject;
import guichaguri.betterfps.BetterFps;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
package guichaguri.betterfps.installer;
/**
* @author Guilherme Chaguri
*/
public class GuiInstallOptions extends JDialog implements ActionListener, FocusListener {
private final String BROWSE = "browse_directories";
private final String INSTALL = "install";
| private final String DEFAULT_PROFILE = "BetterFps"; |
Guichaguri/BetterFps | src/test/java/guichaguri/betterfps/test/math/LibGDXMathTest.java | // Path: src/main/java/guichaguri/betterfps/math/LibGDXMath.java
// public class LibGDXMath {
// public static final float BF_PI = 3.1415927f;
//
// private static final int BF_SIN_BITS = 14; // 16KB. Adjust for accuracy.
// private static final int BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// private static final int BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// private static final float BF_radFull = BF_PI * 2;
// private static final float BF_degFull = 360;
// private static final float BF_radToIndex = BF_SIN_COUNT / BF_radFull;
// private static final float BF_degToIndex = BF_SIN_COUNT / BF_degFull;
//
// public static final float BF_degreesToRadians = BF_PI / 180;
//
// private static final float[] BF_table = new float[BF_SIN_COUNT];
//
// static {
// for(int i = 0; i < BF_SIN_COUNT; i++) {
// BF_table[i] = (float)Math.sin((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// }
// for (int i = 0; i < 360; i += 90) {
// BF_table[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.sin(i * BF_degreesToRadians);
// }
// }
//
//
// public static float sin(float radians) {
// return BF_table[(int)(radians * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float radians) {
// return BF_table[(int)((radians + BF_PI / 2) * BF_radToIndex) & BF_SIN_MASK];
// }
// }
| import guichaguri.betterfps.math.LibGDXMath;
import org.junit.Assert;
import org.junit.Test; | package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class LibGDXMathTest {
@Test
public void testSine() { | // Path: src/main/java/guichaguri/betterfps/math/LibGDXMath.java
// public class LibGDXMath {
// public static final float BF_PI = 3.1415927f;
//
// private static final int BF_SIN_BITS = 14; // 16KB. Adjust for accuracy.
// private static final int BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// private static final int BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// private static final float BF_radFull = BF_PI * 2;
// private static final float BF_degFull = 360;
// private static final float BF_radToIndex = BF_SIN_COUNT / BF_radFull;
// private static final float BF_degToIndex = BF_SIN_COUNT / BF_degFull;
//
// public static final float BF_degreesToRadians = BF_PI / 180;
//
// private static final float[] BF_table = new float[BF_SIN_COUNT];
//
// static {
// for(int i = 0; i < BF_SIN_COUNT; i++) {
// BF_table[i] = (float)Math.sin((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// }
// for (int i = 0; i < 360; i += 90) {
// BF_table[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.sin(i * BF_degreesToRadians);
// }
// }
//
//
// public static float sin(float radians) {
// return BF_table[(int)(radians * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float radians) {
// return BF_table[(int)((radians + BF_PI / 2) * BF_radToIndex) & BF_SIN_MASK];
// }
// }
// Path: src/test/java/guichaguri/betterfps/test/math/LibGDXMathTest.java
import guichaguri.betterfps.math.LibGDXMath;
import org.junit.Assert;
import org.junit.Test;
package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class LibGDXMathTest {
@Test
public void testSine() { | float sine = LibGDXMath.sin(1); |
Guichaguri/BetterFps | src/test/java/guichaguri/betterfps/test/math/RivensMathTest.java | // Path: src/main/java/guichaguri/betterfps/math/RivensMath.java
// public class RivensMath {
//
// private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_COUNT;
// private static final float BF_radFull, BF_radToIndex;
// private static final float BF_degFull, BF_degToIndex;
// private static final float[] BF_sin, BF_cos;
//
// static {
// BF_SIN_BITS = 12;
// BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// BF_radFull = (float) (Math.PI * 2.0);
// BF_degFull = (float) (360.0);
// BF_radToIndex = BF_SIN_COUNT / BF_radFull;
// BF_degToIndex = BF_SIN_COUNT / BF_degFull;
//
// BF_sin = new float[BF_SIN_COUNT];
// BF_cos = new float[BF_SIN_COUNT];
//
// for (int i = 0; i < BF_SIN_COUNT; i++) {
// BF_sin[i] = (float) Math.sin((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// BF_cos[i] = (float) Math.cos((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// }
//
// // Four cardinal directions (credits: Nate)
// for (int i = 0; i < 360; i += 90) {
// BF_sin[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.sin(i * Math.PI / 180.0);
// BF_cos[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.cos(i * Math.PI / 180.0);
// }
// }
//
// public static float sin(float rad) {
// return BF_sin[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float rad) {
// return BF_cos[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// }
| import guichaguri.betterfps.math.RivensMath;
import org.junit.Assert;
import org.junit.Test; | package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class RivensMathTest {
@Test
public void testSine() { | // Path: src/main/java/guichaguri/betterfps/math/RivensMath.java
// public class RivensMath {
//
// private static final int BF_SIN_BITS, BF_SIN_MASK, BF_SIN_COUNT;
// private static final float BF_radFull, BF_radToIndex;
// private static final float BF_degFull, BF_degToIndex;
// private static final float[] BF_sin, BF_cos;
//
// static {
// BF_SIN_BITS = 12;
// BF_SIN_MASK = ~(-1 << BF_SIN_BITS);
// BF_SIN_COUNT = BF_SIN_MASK + 1;
//
// BF_radFull = (float) (Math.PI * 2.0);
// BF_degFull = (float) (360.0);
// BF_radToIndex = BF_SIN_COUNT / BF_radFull;
// BF_degToIndex = BF_SIN_COUNT / BF_degFull;
//
// BF_sin = new float[BF_SIN_COUNT];
// BF_cos = new float[BF_SIN_COUNT];
//
// for (int i = 0; i < BF_SIN_COUNT; i++) {
// BF_sin[i] = (float) Math.sin((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// BF_cos[i] = (float) Math.cos((i + 0.5f) / BF_SIN_COUNT * BF_radFull);
// }
//
// // Four cardinal directions (credits: Nate)
// for (int i = 0; i < 360; i += 90) {
// BF_sin[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.sin(i * Math.PI / 180.0);
// BF_cos[(int)(i * BF_degToIndex) & BF_SIN_MASK] = (float)Math.cos(i * Math.PI / 180.0);
// }
// }
//
// public static float sin(float rad) {
// return BF_sin[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// public static float cos(float rad) {
// return BF_cos[(int)(rad * BF_radToIndex) & BF_SIN_MASK];
// }
//
// }
// Path: src/test/java/guichaguri/betterfps/test/math/RivensMathTest.java
import guichaguri.betterfps.math.RivensMath;
import org.junit.Assert;
import org.junit.Test;
package guichaguri.betterfps.test.math;
/**
* @author Guilherme Chaguri
*/
public class RivensMathTest {
@Test
public void testSine() { | float sine = RivensMath.sin(1); |
Guichaguri/BetterFps | src/main/java/guichaguri/betterfps/patches/block/FastHopperBlock.java | // Path: src/main/java/guichaguri/betterfps/api/IFastHopper.java
// public interface IFastHopper extends IHopper {
//
// /**
// * Whether this hopper is picking up dropped items
// */
// boolean canPickupItems();
//
// /**
// * Updates {@link #canPickupItems}
// */
// void updateFastHopper();
//
// }
//
// Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
| import guichaguri.betterfps.api.IFastHopper;
import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World; | package guichaguri.betterfps.patches.block;
/**
* @author Guilherme Chaguri
*/
@Condition(Conditions.FAST_HOPPER)
public abstract class FastHopperBlock extends Block {
protected FastHopperBlock(Material materialIn) {
super(materialIn);
}
@Copy(Mode.APPEND)
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block neighborBlock, BlockPos pos2) {
TileEntity te = worldIn.getTileEntity(pos); | // Path: src/main/java/guichaguri/betterfps/api/IFastHopper.java
// public interface IFastHopper extends IHopper {
//
// /**
// * Whether this hopper is picking up dropped items
// */
// boolean canPickupItems();
//
// /**
// * Updates {@link #canPickupItems}
// */
// void updateFastHopper();
//
// }
//
// Path: src/main/java/guichaguri/betterfps/transformers/Conditions.java
// public class Conditions {
//
// protected static final List<Mappings> patched = new ArrayList<Mappings>();
//
// public static final String FAST_HOPPER = "fastHopper";
// public static final String FAST_BEACON = "fastBeacon";
// public static final String FAST_SEARCH = "fastSearch";
// public static final String FAST_BEAM_RENDER = "fastBeaconBeamRender";
// public static final String FOG_DISABLED = "fogDisabled";
//
// /**
// * Checks whether the condition identifier is met
// */
// public static boolean shouldPatch(String condition) {
// BetterFpsConfig config = BetterFpsHelper.getConfig();
//
// if(condition.equals(FAST_HOPPER)) {
// return config.fastHopper;
// } else if(condition.equals(FAST_BEACON)) {
// return config.fastBeacon;
// } else if(condition.equals(FAST_SEARCH)) {
// return config.fastSearch;
// } else if(condition.equals(FAST_BEAM_RENDER)) {
// return !config.beaconBeam;
// } else if(condition.equals(FOG_DISABLED)) {
// return !config.fog;
// }
//
// return true;
// }
//
// /**
// * Checks whether the {@link Condition} annotation has its condition met
// */
// public static boolean shouldPatch(List<AnnotationNode> annotations) {
// AnnotationNode condition = ASMUtils.getAnnotation(annotations, Condition.class);
// if(condition != null) {
// String id = ASMUtils.getAnnotationValue(condition, "value", String.class);
// return id == null || shouldPatch(id);
// }
// return true;
// }
//
// public static boolean isPatched(Mappings name) {
// return patched.contains(name);
// }
//
// }
// Path: src/main/java/guichaguri/betterfps/patches/block/FastHopperBlock.java
import guichaguri.betterfps.api.IFastHopper;
import guichaguri.betterfps.transformers.Conditions;
import guichaguri.betterfps.transformers.annotations.Condition;
import guichaguri.betterfps.transformers.annotations.Copy;
import guichaguri.betterfps.transformers.annotations.Copy.Mode;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
package guichaguri.betterfps.patches.block;
/**
* @author Guilherme Chaguri
*/
@Condition(Conditions.FAST_HOPPER)
public abstract class FastHopperBlock extends Block {
protected FastHopperBlock(Material materialIn) {
super(materialIn);
}
@Copy(Mode.APPEND)
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block neighborBlock, BlockPos pos2) {
TileEntity te = worldIn.getTileEntity(pos); | if(te != null && te instanceof IFastHopper) { |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java | // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
| // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
| List<FilterDef> filters = new ArrayList<>(); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java | // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
| // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
| class SimpleChain implements FilterChain { |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java | // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
class SimpleChain implements FilterChain {
int cursor;
HttpServerExchange exchange;
| // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
class SimpleChain implements FilterChain {
int cursor;
HttpServerExchange exchange;
| Request request; |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java | // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
class SimpleChain implements FilterChain {
int cursor;
HttpServerExchange exchange;
Request request;
| // Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
// public class FilterDef implements Predicate, Filter {
//
// final Predicate predicate;
//
// final Filter filter;
//
// public FilterDef(Predicate predicate, Filter filter) {
// this.predicate = Objects.requireNonNull(predicate);
// this.filter = Objects.requireNonNull(filter);
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.predicate.resolve(value);
// }
//
// @Override
// public void filter(Request req, Response res, FilterChain chain)
// throws Exception {
// this.filter.filter(req, res, chain);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/internal/FiltersHandler.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.def.FilterDef;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class FiltersHandler implements HttpHandler {
HttpHandler next;
List<FilterDef> filters = new ArrayList<>();
public FiltersHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (filters.size() < 1) {
next.handleRequest(exchange);
return;
}
SimpleChain chain = new SimpleChain(exchange);
chain.next();
}
public void add(FilterDef model) {
this.filters.add(model);
}
enum ChainState {
HasNext, NoMore;
}
class SimpleChain implements FilterChain {
int cursor;
HttpServerExchange exchange;
Request request;
| Response response; |
taichi/siden | siden-core/src/test/java/ninja/siden/internal/Testing.java | // Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
| import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import mockit.Mock;
import mockit.MockUp;
import ninja.siden.util.Using;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public interface Testing {
static CloseableHttpClient client() {
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(2000)
.build());
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
return builder.build();
}
@FunctionalInterface
interface ResponseConsumer {
void accept(HttpResponse response) throws Exception;
}
static void request(HttpUriRequest request, ResponseConsumer fn)
throws Exception { | // Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: siden-core/src/test/java/ninja/siden/internal/Testing.java
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import mockit.Mock;
import mockit.MockUp;
import ninja.siden.util.Using;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public interface Testing {
static CloseableHttpClient client() {
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(2000)
.build());
builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
return builder.build();
}
@FunctionalInterface
interface ResponseConsumer {
void accept(HttpResponse response) throws Exception;
}
static void request(HttpUriRequest request, ResponseConsumer fn)
throws Exception { | Using.consume(Testing::client, c -> fn.accept(c.execute(request))); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/MethodOverrideHandler.java | // Path: siden-core/src/main/java/ninja/siden/HttpMethod.java
// public enum HttpMethod implements Predicate {
//
// GET(Methods.GET), HEAD(Methods.HEAD), POST(Methods.POST), PUT(Methods.PUT), DELETE(
// Methods.DELETE), TRACE(Methods.TRACE), OPTIONS(Methods.OPTIONS), CONNECT(
// Methods.CONNECT), PATCH(new HttpString("PATCH")), LINK(
// new HttpString("LINK")), UNLINK(new HttpString("UNLINK"));
//
// static final Map<HttpString, HttpMethod> methods = new HashMap<>();
// static {
// for (HttpMethod hm : HttpMethod.values()) {
// methods.put(hm.rawdata, hm);
// }
// }
//
// HttpString rawdata;
//
// private HttpMethod(HttpString string) {
// this.rawdata = string;
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.rawdata.equals(value.getRequestMethod());
// }
//
// public static HttpMethod of(HttpServerExchange exchange) {
// return methods.getOrDefault(exchange.getRequestMethod(), GET);
// }
//
// public static Optional<HttpString> find(String method) {
// if (method == null || method.isEmpty()) {
// return Optional.empty();
// }
// String m = method.toUpperCase();
// return Optional.ofNullable(methods.get(new HttpString(m))).map(
// hm -> hm.rawdata);
// }
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import java.util.Optional;
import ninja.siden.HttpMethod; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class MethodOverrideHandler implements HttpHandler {
static final HttpString HEADER = new HttpString("X-HTTP-Method-Override");
static final String FORM = "_method";
HttpHandler next;
public MethodOverrideHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (Methods.POST.equals(exchange.getRequestMethod())) {
String newMethod = exchange.getRequestHeaders().getFirst(HEADER); | // Path: siden-core/src/main/java/ninja/siden/HttpMethod.java
// public enum HttpMethod implements Predicate {
//
// GET(Methods.GET), HEAD(Methods.HEAD), POST(Methods.POST), PUT(Methods.PUT), DELETE(
// Methods.DELETE), TRACE(Methods.TRACE), OPTIONS(Methods.OPTIONS), CONNECT(
// Methods.CONNECT), PATCH(new HttpString("PATCH")), LINK(
// new HttpString("LINK")), UNLINK(new HttpString("UNLINK"));
//
// static final Map<HttpString, HttpMethod> methods = new HashMap<>();
// static {
// for (HttpMethod hm : HttpMethod.values()) {
// methods.put(hm.rawdata, hm);
// }
// }
//
// HttpString rawdata;
//
// private HttpMethod(HttpString string) {
// this.rawdata = string;
// }
//
// @Override
// public boolean resolve(HttpServerExchange value) {
// return this.rawdata.equals(value.getRequestMethod());
// }
//
// public static HttpMethod of(HttpServerExchange exchange) {
// return methods.getOrDefault(exchange.getRequestMethod(), GET);
// }
//
// public static Optional<HttpString> find(String method) {
// if (method == null || method.isEmpty()) {
// return Optional.empty();
// }
// String m = method.toUpperCase();
// return Optional.ofNullable(methods.get(new HttpString(m))).map(
// hm -> hm.rawdata);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/internal/MethodOverrideHandler.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.form.FormData;
import io.undertow.server.handlers.form.FormDataParser;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import java.util.Optional;
import ninja.siden.HttpMethod;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class MethodOverrideHandler implements HttpHandler {
static final HttpString HEADER = new HttpString("X-HTTP-Method-Override");
static final String FORM = "_method";
HttpHandler next;
public MethodOverrideHandler(HttpHandler next) {
this.next = next;
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
if (Methods.POST.equals(exchange.getRequestMethod())) {
String newMethod = exchange.getRequestHeaders().getFirst(HEADER); | Optional<HttpString> opt = HttpMethod.find(newMethod); |
taichi/siden | siden-core/src/main/java/ninja/siden/Connection.java | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import io.undertow.websockets.core.WebSocketChannel;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
* @see io.undertow.websockets.core.WebSocketChannel
*/
public interface Connection extends AttributeContainer {
// endpoint methods
CompletableFuture<Void> send(String text);
CompletableFuture<Void> send(ByteBuffer payload);
CompletableFuture<Void> ping(ByteBuffer payload);
CompletableFuture<Void> pong(ByteBuffer payload);
CompletableFuture<Void> close();
CompletableFuture<Void> close(int code, String reason);
| // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/Connection.java
import io.undertow.websockets.core.WebSocketChannel;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
* @see io.undertow.websockets.core.WebSocketChannel
*/
public interface Connection extends AttributeContainer {
// endpoint methods
CompletableFuture<Void> send(String text);
CompletableFuture<Void> send(ByteBuffer payload);
CompletableFuture<Void> ping(ByteBuffer payload);
CompletableFuture<Void> pong(ByteBuffer payload);
CompletableFuture<Void> close();
CompletableFuture<Void> close(int code, String reason);
| void sendStream(ExceptionalConsumer<OutputStream, Exception> fn); |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/WebSocketTracker.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
| import java.nio.ByteBuffer;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class WebSocketTracker implements WebSocketFactory, WebSocketMXBean {
final WebSocketFactory original;
RequestMeter onConnect = new RequestMeter();
RequestMeter onText = new RequestMeter();
RequestMeter onBinary = new RequestMeter();
RequestMeter onPong = new RequestMeter();
RequestMeter onPing = new RequestMeter();
RequestMeter onClose = new RequestMeter();
public WebSocketTracker(WebSocketFactory original) {
this.original = original;
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/WebSocketTracker.java
import java.nio.ByteBuffer;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class WebSocketTracker implements WebSocketFactory, WebSocketMXBean {
final WebSocketFactory original;
RequestMeter onConnect = new RequestMeter();
RequestMeter onText = new RequestMeter();
RequestMeter onBinary = new RequestMeter();
RequestMeter onPong = new RequestMeter();
RequestMeter onPing = new RequestMeter();
RequestMeter onClose = new RequestMeter();
public WebSocketTracker(WebSocketFactory original) {
this.original = original;
}
@Override | public WebSocket create(Connection connection) { |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/WebSocketTracker.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
| import java.nio.ByteBuffer;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class WebSocketTracker implements WebSocketFactory, WebSocketMXBean {
final WebSocketFactory original;
RequestMeter onConnect = new RequestMeter();
RequestMeter onText = new RequestMeter();
RequestMeter onBinary = new RequestMeter();
RequestMeter onPong = new RequestMeter();
RequestMeter onPing = new RequestMeter();
RequestMeter onClose = new RequestMeter();
public WebSocketTracker(WebSocketFactory original) {
this.original = original;
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/WebSocketTracker.java
import java.nio.ByteBuffer;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class WebSocketTracker implements WebSocketFactory, WebSocketMXBean {
final WebSocketFactory original;
RequestMeter onConnect = new RequestMeter();
RequestMeter onText = new RequestMeter();
RequestMeter onBinary = new RequestMeter();
RequestMeter onPong = new RequestMeter();
RequestMeter onPing = new RequestMeter();
RequestMeter onClose = new RequestMeter();
public WebSocketTracker(WebSocketFactory original) {
this.original = original;
}
@Override | public WebSocket create(Connection connection) { |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/RouteTracker.java | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
| import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.Route; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RouteTracker implements Route, RequestMXBean {
Route original;
RequestMeter totalResult = new RequestMeter();
public RouteTracker(Route original) {
this.original = original;
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/RouteTracker.java
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.Route;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RouteTracker implements Route, RequestMXBean {
Route original;
RequestMeter totalResult = new RequestMeter();
public RouteTracker(Route original) {
this.original = original;
}
@Override | public Object handle(Request request, Response response) throws Exception { |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/RouteTracker.java | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
| import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.Route; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RouteTracker implements Route, RequestMXBean {
Route original;
RequestMeter totalResult = new RequestMeter();
public RouteTracker(Route original) {
this.original = original;
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/RouteTracker.java
import ninja.siden.Request;
import ninja.siden.Response;
import ninja.siden.Route;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RouteTracker implements Route, RequestMXBean {
Route original;
RequestMeter totalResult = new RequestMeter();
public RouteTracker(Route original) {
this.original = original;
}
@Override | public Object handle(Request request, Response response) throws Exception { |
taichi/siden | siden-core/src/main/java/ninja/siden/def/ExceptionalRoutingDef.java | // Path: siden-core/src/main/java/ninja/siden/ExceptionalRoute.java
// @FunctionalInterface
// public interface ExceptionalRoute<EX extends Throwable> {
//
// Object handle(EX ex, Request request, Response response);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
| import ninja.siden.ExceptionalRoute;
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ExceptionalRoutingDef<EX extends Throwable> implements
RendererCustomizer<ExceptionalRoutingDef<EX>> {
Class<EX> type; | // Path: siden-core/src/main/java/ninja/siden/ExceptionalRoute.java
// @FunctionalInterface
// public interface ExceptionalRoute<EX extends Throwable> {
//
// Object handle(EX ex, Request request, Response response);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
// Path: siden-core/src/main/java/ninja/siden/def/ExceptionalRoutingDef.java
import ninja.siden.ExceptionalRoute;
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ExceptionalRoutingDef<EX extends Throwable> implements
RendererCustomizer<ExceptionalRoutingDef<EX>> {
Class<EX> type; | ExceptionalRoute<EX> route; |
taichi/siden | siden-core/src/main/java/ninja/siden/def/ExceptionalRoutingDef.java | // Path: siden-core/src/main/java/ninja/siden/ExceptionalRoute.java
// @FunctionalInterface
// public interface ExceptionalRoute<EX extends Throwable> {
//
// Object handle(EX ex, Request request, Response response);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
| import ninja.siden.ExceptionalRoute;
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ExceptionalRoutingDef<EX extends Throwable> implements
RendererCustomizer<ExceptionalRoutingDef<EX>> {
Class<EX> type;
ExceptionalRoute<EX> route; | // Path: siden-core/src/main/java/ninja/siden/ExceptionalRoute.java
// @FunctionalInterface
// public interface ExceptionalRoute<EX extends Throwable> {
//
// Object handle(EX ex, Request request, Response response);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
// Path: siden-core/src/main/java/ninja/siden/def/ExceptionalRoutingDef.java
import ninja.siden.ExceptionalRoute;
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ExceptionalRoutingDef<EX extends Throwable> implements
RendererCustomizer<ExceptionalRoutingDef<EX>> {
Class<EX> type;
ExceptionalRoute<EX> route; | Renderer<?> renderer; |
taichi/siden | siden-core/src/test/java/ninja/siden/jmx/ObjectNamesTest.java | // Path: siden-core/src/main/java/ninja/siden/jmx/ObjectNames.java
// public interface ObjectNames {
//
// static ObjectName to(CharSequence name) {
// try {
// return new ObjectName(name.toString());
// } catch (MalformedObjectNameException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// static ObjectName to(CharSequence domain, List<String> props) {
// if (props.size() % 2 != 0) {
// throw new IllegalArgumentException();
// }
// StringBuilder stb = new StringBuilder(domain);
// stb.append(":");
// for (Iterator<String> i = props.iterator(); i.hasNext();) {
// stb.append(i.next());
// stb.append('=');
// stb.append(i.next());
// if (i.hasNext()) {
// stb.append(',');
// }
// }
// return to(stb);
// }
// }
| import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import javax.management.ObjectName;
import ninja.siden.jmx.ObjectNames;
import org.junit.Test; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class ObjectNamesTest {
@Test
public void to() throws Exception { | // Path: siden-core/src/main/java/ninja/siden/jmx/ObjectNames.java
// public interface ObjectNames {
//
// static ObjectName to(CharSequence name) {
// try {
// return new ObjectName(name.toString());
// } catch (MalformedObjectNameException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// static ObjectName to(CharSequence domain, List<String> props) {
// if (props.size() % 2 != 0) {
// throw new IllegalArgumentException();
// }
// StringBuilder stb = new StringBuilder(domain);
// stb.append(":");
// for (Iterator<String> i = props.iterator(); i.hasNext();) {
// stb.append(i.next());
// stb.append('=');
// stb.append(i.next());
// if (i.hasNext()) {
// stb.append(',');
// }
// }
// return to(stb);
// }
// }
// Path: siden-core/src/test/java/ninja/siden/jmx/ObjectNamesTest.java
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import javax.management.ObjectName;
import ninja.siden.jmx.ObjectNames;
import org.junit.Test;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class ObjectNamesTest {
@Test
public void to() throws Exception { | ObjectName name = ObjectNames.to("aaa.bbb:type=Z"); |
taichi/siden | siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import java.nio.ByteBuffer;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
public interface WebSocketCustomizer {
WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
WebSocketCustomizer onText( | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
import java.nio.ByteBuffer;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
public interface WebSocketCustomizer {
WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
WebSocketCustomizer onText( | ExceptionalBiConsumer<Connection, String, Exception> fn); |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
| import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder(); | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java
import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder(); | this.maxRequestTime = LongAccumulators.max(); |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
| import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder();
this.maxRequestTime = LongAccumulators.max();
this.minRequestTime = LongAccumulators.min();
this.totalRequests = new LongAdder();
}
protected void accept(final long requestTime) {
this.totalRequestTime.add(requestTime);
this.maxRequestTime.accumulate(requestTime);
this.minRequestTime.accumulate(requestTime);
this.totalRequests.increment();
}
public <EX extends Exception> void accept( | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java
import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder();
this.maxRequestTime = LongAccumulators.max();
this.minRequestTime = LongAccumulators.min();
this.totalRequests = new LongAdder();
}
protected void accept(final long requestTime) {
this.totalRequestTime.add(requestTime);
this.maxRequestTime.accumulate(requestTime);
this.minRequestTime.accumulate(requestTime);
this.totalRequests.increment();
}
public <EX extends Exception> void accept( | ExceptionalConsumer<RequestMeter, EX> fn) throws EX { |
taichi/siden | siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
| import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder();
this.maxRequestTime = LongAccumulators.max();
this.minRequestTime = LongAccumulators.min();
this.totalRequests = new LongAdder();
}
protected void accept(final long requestTime) {
this.totalRequestTime.add(requestTime);
this.maxRequestTime.accumulate(requestTime);
this.minRequestTime.accumulate(requestTime);
this.totalRequests.increment();
}
public <EX extends Exception> void accept(
ExceptionalConsumer<RequestMeter, EX> fn) throws EX {
apply(m -> {
fn.accept(m);
return null;
});
}
public <R, EX extends Exception> R apply( | // Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalFunction.java
// @FunctionalInterface
// public interface ExceptionalFunction<T, R, EX extends Exception> {
//
// R apply(T t) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/LongAccumulators.java
// public interface LongAccumulators {
//
// static LongAccumulator max() {
// return new LongAccumulator((x, y) -> x < y ? y : x, 0);
// }
//
// static LongAccumulator min() {
// return new LongAccumulator(
// (x, y) -> y < x || (x < 0 && -1 < y) ? y : x, -1);
// }
// }
// Path: siden-core/src/main/java/ninja/siden/jmx/RequestMeter.java
import java.util.Date;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.concurrent.atomic.LongAdder;
import ninja.siden.util.ExceptionalConsumer;
import ninja.siden.util.ExceptionalFunction;
import ninja.siden.util.LongAccumulators;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.jmx;
/**
* @author taichi
*/
public class RequestMeter {
static final AtomicLongFieldUpdater<RequestMeter> startTimeUpdater = AtomicLongFieldUpdater
.newUpdater(RequestMeter.class, "startTime");
volatile long startTime;
LongAdder totalRequestTime;
LongAccumulator maxRequestTime;
LongAccumulator minRequestTime;
LongAdder totalRequests;
public RequestMeter() {
this.startTime = System.currentTimeMillis();
this.totalRequestTime = new LongAdder();
this.maxRequestTime = LongAccumulators.max();
this.minRequestTime = LongAccumulators.min();
this.totalRequests = new LongAdder();
}
protected void accept(final long requestTime) {
this.totalRequestTime.add(requestTime);
this.maxRequestTime.accumulate(requestTime);
this.minRequestTime.accumulate(requestTime);
this.totalRequests.increment();
}
public <EX extends Exception> void accept(
ExceptionalConsumer<RequestMeter, EX> fn) throws EX {
apply(m -> {
fn.accept(m);
return null;
});
}
public <R, EX extends Exception> R apply( | ExceptionalFunction<RequestMeter, R, EX> fn) throws EX { |
taichi/siden | siden-core/src/main/java/ninja/siden/def/FilterDef.java | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
| import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | public void filter(Request req, Response res, FilterChain chain) |
taichi/siden | siden-core/src/main/java/ninja/siden/def/FilterDef.java | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
| import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | public void filter(Request req, Response res, FilterChain chain) |
taichi/siden | siden-core/src/main/java/ninja/siden/def/FilterDef.java | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
| import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | // Path: siden-core/src/main/java/ninja/siden/Filter.java
// @FunctionalInterface
// public interface Filter {
//
// void filter(Request req, Response res, FilterChain chain) throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/FilterChain.java
// @FunctionalInterface
// public interface FilterChain {
//
// Object next() throws Exception;
// }
//
// Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
// Path: siden-core/src/main/java/ninja/siden/def/FilterDef.java
import io.undertow.predicate.Predicate;
import io.undertow.server.HttpServerExchange;
import java.util.Objects;
import ninja.siden.Filter;
import ninja.siden.FilterChain;
import ninja.siden.Request;
import ninja.siden.Response;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class FilterDef implements Predicate, Filter {
final Predicate predicate;
final Filter filter;
public FilterDef(Predicate predicate, Filter filter) {
this.predicate = Objects.requireNonNull(predicate);
this.filter = Objects.requireNonNull(filter);
}
@Override
public boolean resolve(HttpServerExchange value) {
return this.predicate.resolve(value);
}
@Override | public void filter(Request req, Response res, FilterChain chain) |
taichi/siden | siden-core/src/main/java/ninja/siden/def/WebSocketDef.java | // Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
// public class ConnectionCallback implements WebSocketConnectionCallback {
//
// final WebSocketFactory factory;
// final Set<Connection> peers = Collections
// .newSetFromMap(new ConcurrentHashMap<>());
//
// public ConnectionCallback(WebSocketFactory factory) {
// this.factory = factory;
// }
//
// @Override
// public void onConnect(WebSocketHttpExchange exchange,
// WebSocketChannel channel) {
// try {
// Connection connection = new SidenConnection(exchange, channel,
// peers);
// WebSocket socket = factory.create(connection);
// socket.onConnect(connection);
// channel.getReceiveSetter().set(new ReceiveListenerAdapter(socket));
// channel.resumeReceives();
// } catch (IOException e) {
// UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
// IoUtils.safeClose(channel);
// } catch (Exception e) {
// IoUtils.safeClose(channel);
// }
// }
// }
| import io.undertow.predicate.Predicate;
import io.undertow.predicate.PredicatesHandler;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import ninja.siden.WebSocketFactory;
import ninja.siden.internal.ConnectionCallback;
import org.xnio.OptionMap; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class WebSocketDef {
final String template;
final Predicate predicate; | // Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
// public class ConnectionCallback implements WebSocketConnectionCallback {
//
// final WebSocketFactory factory;
// final Set<Connection> peers = Collections
// .newSetFromMap(new ConcurrentHashMap<>());
//
// public ConnectionCallback(WebSocketFactory factory) {
// this.factory = factory;
// }
//
// @Override
// public void onConnect(WebSocketHttpExchange exchange,
// WebSocketChannel channel) {
// try {
// Connection connection = new SidenConnection(exchange, channel,
// peers);
// WebSocket socket = factory.create(connection);
// socket.onConnect(connection);
// channel.getReceiveSetter().set(new ReceiveListenerAdapter(socket));
// channel.resumeReceives();
// } catch (IOException e) {
// UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
// IoUtils.safeClose(channel);
// } catch (Exception e) {
// IoUtils.safeClose(channel);
// }
// }
// }
// Path: siden-core/src/main/java/ninja/siden/def/WebSocketDef.java
import io.undertow.predicate.Predicate;
import io.undertow.predicate.PredicatesHandler;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import ninja.siden.WebSocketFactory;
import ninja.siden.internal.ConnectionCallback;
import org.xnio.OptionMap;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class WebSocketDef {
final String template;
final Predicate predicate; | final WebSocketFactory factory; |
taichi/siden | siden-core/src/main/java/ninja/siden/def/WebSocketDef.java | // Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
// public class ConnectionCallback implements WebSocketConnectionCallback {
//
// final WebSocketFactory factory;
// final Set<Connection> peers = Collections
// .newSetFromMap(new ConcurrentHashMap<>());
//
// public ConnectionCallback(WebSocketFactory factory) {
// this.factory = factory;
// }
//
// @Override
// public void onConnect(WebSocketHttpExchange exchange,
// WebSocketChannel channel) {
// try {
// Connection connection = new SidenConnection(exchange, channel,
// peers);
// WebSocket socket = factory.create(connection);
// socket.onConnect(connection);
// channel.getReceiveSetter().set(new ReceiveListenerAdapter(socket));
// channel.resumeReceives();
// } catch (IOException e) {
// UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
// IoUtils.safeClose(channel);
// } catch (Exception e) {
// IoUtils.safeClose(channel);
// }
// }
// }
| import io.undertow.predicate.Predicate;
import io.undertow.predicate.PredicatesHandler;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import ninja.siden.WebSocketFactory;
import ninja.siden.internal.ConnectionCallback;
import org.xnio.OptionMap; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class WebSocketDef {
final String template;
final Predicate predicate;
final WebSocketFactory factory;
public WebSocketDef(String template, Predicate predicate,
WebSocketFactory factory) {
super();
this.template = template;
this.predicate = predicate;
this.factory = factory;
}
public String template() {
return this.template;
}
public Predicate predicate() {
return this.predicate;
}
public WebSocketFactory factory() {
return this.factory;
}
public void addTo(PredicatesHandler ph, OptionMap config) {
ph.addPredicatedHandler(this.predicate(),
next -> new WebSocketProtocolHandshakeHandler( | // Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
// public class ConnectionCallback implements WebSocketConnectionCallback {
//
// final WebSocketFactory factory;
// final Set<Connection> peers = Collections
// .newSetFromMap(new ConcurrentHashMap<>());
//
// public ConnectionCallback(WebSocketFactory factory) {
// this.factory = factory;
// }
//
// @Override
// public void onConnect(WebSocketHttpExchange exchange,
// WebSocketChannel channel) {
// try {
// Connection connection = new SidenConnection(exchange, channel,
// peers);
// WebSocket socket = factory.create(connection);
// socket.onConnect(connection);
// channel.getReceiveSetter().set(new ReceiveListenerAdapter(socket));
// channel.resumeReceives();
// } catch (IOException e) {
// UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
// IoUtils.safeClose(channel);
// } catch (Exception e) {
// IoUtils.safeClose(channel);
// }
// }
// }
// Path: siden-core/src/main/java/ninja/siden/def/WebSocketDef.java
import io.undertow.predicate.Predicate;
import io.undertow.predicate.PredicatesHandler;
import io.undertow.websockets.WebSocketProtocolHandshakeHandler;
import ninja.siden.WebSocketFactory;
import ninja.siden.internal.ConnectionCallback;
import org.xnio.OptionMap;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class WebSocketDef {
final String template;
final Predicate predicate;
final WebSocketFactory factory;
public WebSocketDef(String template, Predicate predicate,
WebSocketFactory factory) {
super();
this.template = template;
this.predicate = predicate;
this.factory = factory;
}
public String template() {
return this.template;
}
public Predicate predicate() {
return this.predicate;
}
public WebSocketFactory factory() {
return this.factory;
}
public void addTo(PredicatesHandler ph, OptionMap config) {
ph.addPredicatedHandler(this.predicate(),
next -> new WebSocketProtocolHandshakeHandler( | new ConnectionCallback(this.factory()), next)); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
| import io.undertow.UndertowLogger;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
import org.xnio.IoUtils; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ConnectionCallback implements WebSocketConnectionCallback {
final WebSocketFactory factory; | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
import io.undertow.UndertowLogger;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
import org.xnio.IoUtils;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ConnectionCallback implements WebSocketConnectionCallback {
final WebSocketFactory factory; | final Set<Connection> peers = Collections |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
| import io.undertow.UndertowLogger;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
import org.xnio.IoUtils; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ConnectionCallback implements WebSocketConnectionCallback {
final WebSocketFactory factory;
final Set<Connection> peers = Collections
.newSetFromMap(new ConcurrentHashMap<>());
public ConnectionCallback(WebSocketFactory factory) {
this.factory = factory;
}
@Override
public void onConnect(WebSocketHttpExchange exchange,
WebSocketChannel channel) {
try {
Connection connection = new SidenConnection(exchange, channel,
peers); | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
// Path: siden-core/src/main/java/ninja/siden/internal/ConnectionCallback.java
import io.undertow.UndertowLogger;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketFactory;
import org.xnio.IoUtils;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ConnectionCallback implements WebSocketConnectionCallback {
final WebSocketFactory factory;
final Set<Connection> peers = Collections
.newSetFromMap(new ConcurrentHashMap<>());
public ConnectionCallback(WebSocketFactory factory) {
this.factory = factory;
}
@Override
public void onConnect(WebSocketHttpExchange exchange,
WebSocketChannel channel) {
try {
Connection connection = new SidenConnection(exchange, channel,
peers); | WebSocket socket = factory.create(connection); |
taichi/siden | siden-core/src/main/java/ninja/siden/def/ErrorCodeRoutingDef.java | // Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
| import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
import ninja.siden.Route; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ErrorCodeRoutingDef implements
RendererCustomizer<ErrorCodeRoutingDef> {
final int code; | // Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
// Path: siden-core/src/main/java/ninja/siden/def/ErrorCodeRoutingDef.java
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
import ninja.siden.Route;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ErrorCodeRoutingDef implements
RendererCustomizer<ErrorCodeRoutingDef> {
final int code; | final Route route; |
taichi/siden | siden-core/src/main/java/ninja/siden/def/ErrorCodeRoutingDef.java | // Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
| import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
import ninja.siden.Route; | /*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ErrorCodeRoutingDef implements
RendererCustomizer<ErrorCodeRoutingDef> {
final int code;
final Route route; | // Path: siden-core/src/main/java/ninja/siden/Renderer.java
// @FunctionalInterface
// public interface Renderer<T> {
//
// void render(T model, HttpServerExchange sink) throws IOException;
//
// public static <MODEL> Renderer<MODEL> ofStream(
// OutputStreamConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
// sink.getOutputStream()));
// }
//
// public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
// return new BlockingRenderer<MODEL>((model, sink) -> {
// OptionMap config = sink.getAttachment(Core.CONFIG);
// Writer w = new OutputStreamWriter(sink.getOutputStream(),
// config.get(Config.CHARSET));
// fn.render(model, w);
// w.flush();
// });
// }
//
// @FunctionalInterface
// public interface OutputStreamConsumer<T> {
// void render(T model, OutputStream out) throws IOException;
// }
//
// @FunctionalInterface
// public interface WriterConsumer<T> {
// void render(T model, Writer out) throws IOException;
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/RendererCustomizer.java
// public interface RendererCustomizer<T extends RendererCustomizer<T>> {
//
// <MODEL> T render(Renderer<MODEL> renderer);
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Route.java
// @FunctionalInterface
// public interface Route {
//
// Object handle(Request request, Response response) throws Exception;
// }
// Path: siden-core/src/main/java/ninja/siden/def/ErrorCodeRoutingDef.java
import ninja.siden.Renderer;
import ninja.siden.RendererCustomizer;
import ninja.siden.Route;
/*
* Copyright 2015 SATO taichi
*
* 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 ninja.siden.def;
/**
* @author taichi
*/
public class ErrorCodeRoutingDef implements
RendererCustomizer<ErrorCodeRoutingDef> {
final int code;
final Route route; | Renderer<?> renderer; |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
| // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
| List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>(); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
| // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
| List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>(); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>(); | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>(); | List<ExceptionalBiConsumer<Connection, String, Exception>> txt = new ArrayList<>(); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, String, Exception>> txt = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> bin = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> pong = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> ping = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> close = new ArrayList<>();
@Override | // Path: siden-core/src/main/java/ninja/siden/Connection.java
// public interface Connection extends AttributeContainer {
//
// // endpoint methods
//
// CompletableFuture<Void> send(String text);
//
// CompletableFuture<Void> send(ByteBuffer payload);
//
// CompletableFuture<Void> ping(ByteBuffer payload);
//
// CompletableFuture<Void> pong(ByteBuffer payload);
//
// CompletableFuture<Void> close();
//
// CompletableFuture<Void> close(int code, String reason);
//
// void sendStream(ExceptionalConsumer<OutputStream, Exception> fn);
//
// void sendWriter(ExceptionalConsumer<Writer, Exception> fn);
//
// // informations
//
// String protocolVersion();
//
// String subProtocol();
//
// boolean secure();
//
// boolean open();
//
// Set<Connection> peers();
//
// // from request
//
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// WebSocketChannel raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketCustomizer.java
// public interface WebSocketCustomizer {
//
// WebSocketCustomizer onConnect(ExceptionalConsumer<Connection, Exception> fn);
//
// WebSocketCustomizer onText(
// ExceptionalBiConsumer<Connection, String, Exception> fn);
//
// WebSocketCustomizer onBinary(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPong(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onPing(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
//
// WebSocketCustomizer onClose(
// ExceptionalBiConsumer<Connection, ByteBuffer[], Exception> fn);
// }
//
// Path: siden-core/src/main/java/ninja/siden/WebSocketFactory.java
// public interface WebSocketFactory {
//
// WebSocket create(Connection connection);
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalBiConsumer.java
// @FunctionalInterface
// public interface ExceptionalBiConsumer<T, U, EX extends Exception> {
//
// void accept(T t, U u) throws EX;
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/internal/LambdaWebSocketFactory.java
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import ninja.siden.Connection;
import ninja.siden.WebSocket;
import ninja.siden.WebSocketCustomizer;
import ninja.siden.WebSocketFactory;
import ninja.siden.util.ExceptionalBiConsumer;
import ninja.siden.util.ExceptionalConsumer;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class LambdaWebSocketFactory implements WebSocketFactory,
WebSocketCustomizer {
List<ExceptionalConsumer<Connection, Exception>> conn = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, String, Exception>> txt = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> bin = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> pong = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> ping = new ArrayList<>();
List<ExceptionalBiConsumer<Connection, ByteBuffer[], Exception>> close = new ArrayList<>();
@Override | public WebSocket create(Connection connection) { |
taichi/siden | siden-core/src/main/java/ninja/siden/Renderer.java | // Path: siden-core/src/main/java/ninja/siden/internal/BlockingRenderer.java
// public class BlockingRenderer<T> implements Renderer<T> {
//
// final Renderer<T> renderer;
//
// public BlockingRenderer(Renderer<T> renderer) {
// super();
// this.renderer = renderer;
// }
//
// @Override
// public void render(T model, HttpServerExchange sink) throws IOException {
// if (sink.isBlocking() == false) {
// sink.startBlocking();
// }
// if (sink.isInIoThread()) {
// sink.dispatch(exchange -> {
// renderer.render(model, exchange);
// });
// } else {
// renderer.render(model, sink);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
// public class Core implements HttpHandler {
//
// public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
// .create(OptionMap.class);
//
// public static final AttachmentKey<Request> REQUEST = AttachmentKey
// .create(Request.class);
//
// public static final AttachmentKey<Response> RESPONSE = AttachmentKey
// .create(Response.class);
//
// final OptionMap config;
// final HttpHandler next;
//
// public Core(OptionMap config, HttpHandler next) {
// super();
// this.config = config;
// this.next = next;
// }
//
// @Override
// public void handleRequest(HttpServerExchange exchange) throws Exception {
// exchange.putAttachment(CONFIG, config);
// exchange.putAttachment(REQUEST, new SidenRequest(exchange));
// exchange.putAttachment(RESPONSE, new SidenResponse(exchange));
// exchange.addExchangeCompleteListener((ex, next) -> {
// try {
// exchange.removeAttachment(CONFIG);
// exchange.removeAttachment(REQUEST);
// exchange.removeAttachment(RESPONSE);
// } finally {
// next.proceed();
// }
// });
// next.handleRequest(exchange);
// }
//
// public static io.undertow.predicate.Predicate adapt(Predicate<Request> fn) {
// return exchange -> {
// Request request = exchange.getAttachment(Core.REQUEST);
// return fn.test(request);
// };
// }
// }
| import io.undertow.server.HttpServerExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import ninja.siden.internal.BlockingRenderer;
import ninja.siden.internal.Core;
import org.xnio.OptionMap; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
@FunctionalInterface
public interface Renderer<T> {
void render(T model, HttpServerExchange sink) throws IOException;
public static <MODEL> Renderer<MODEL> ofStream(
OutputStreamConsumer<MODEL> fn) { | // Path: siden-core/src/main/java/ninja/siden/internal/BlockingRenderer.java
// public class BlockingRenderer<T> implements Renderer<T> {
//
// final Renderer<T> renderer;
//
// public BlockingRenderer(Renderer<T> renderer) {
// super();
// this.renderer = renderer;
// }
//
// @Override
// public void render(T model, HttpServerExchange sink) throws IOException {
// if (sink.isBlocking() == false) {
// sink.startBlocking();
// }
// if (sink.isInIoThread()) {
// sink.dispatch(exchange -> {
// renderer.render(model, exchange);
// });
// } else {
// renderer.render(model, sink);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
// public class Core implements HttpHandler {
//
// public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
// .create(OptionMap.class);
//
// public static final AttachmentKey<Request> REQUEST = AttachmentKey
// .create(Request.class);
//
// public static final AttachmentKey<Response> RESPONSE = AttachmentKey
// .create(Response.class);
//
// final OptionMap config;
// final HttpHandler next;
//
// public Core(OptionMap config, HttpHandler next) {
// super();
// this.config = config;
// this.next = next;
// }
//
// @Override
// public void handleRequest(HttpServerExchange exchange) throws Exception {
// exchange.putAttachment(CONFIG, config);
// exchange.putAttachment(REQUEST, new SidenRequest(exchange));
// exchange.putAttachment(RESPONSE, new SidenResponse(exchange));
// exchange.addExchangeCompleteListener((ex, next) -> {
// try {
// exchange.removeAttachment(CONFIG);
// exchange.removeAttachment(REQUEST);
// exchange.removeAttachment(RESPONSE);
// } finally {
// next.proceed();
// }
// });
// next.handleRequest(exchange);
// }
//
// public static io.undertow.predicate.Predicate adapt(Predicate<Request> fn) {
// return exchange -> {
// Request request = exchange.getAttachment(Core.REQUEST);
// return fn.test(request);
// };
// }
// }
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
import io.undertow.server.HttpServerExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import ninja.siden.internal.BlockingRenderer;
import ninja.siden.internal.Core;
import org.xnio.OptionMap;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
@FunctionalInterface
public interface Renderer<T> {
void render(T model, HttpServerExchange sink) throws IOException;
public static <MODEL> Renderer<MODEL> ofStream(
OutputStreamConsumer<MODEL> fn) { | return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model, |
taichi/siden | siden-core/src/main/java/ninja/siden/Renderer.java | // Path: siden-core/src/main/java/ninja/siden/internal/BlockingRenderer.java
// public class BlockingRenderer<T> implements Renderer<T> {
//
// final Renderer<T> renderer;
//
// public BlockingRenderer(Renderer<T> renderer) {
// super();
// this.renderer = renderer;
// }
//
// @Override
// public void render(T model, HttpServerExchange sink) throws IOException {
// if (sink.isBlocking() == false) {
// sink.startBlocking();
// }
// if (sink.isInIoThread()) {
// sink.dispatch(exchange -> {
// renderer.render(model, exchange);
// });
// } else {
// renderer.render(model, sink);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
// public class Core implements HttpHandler {
//
// public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
// .create(OptionMap.class);
//
// public static final AttachmentKey<Request> REQUEST = AttachmentKey
// .create(Request.class);
//
// public static final AttachmentKey<Response> RESPONSE = AttachmentKey
// .create(Response.class);
//
// final OptionMap config;
// final HttpHandler next;
//
// public Core(OptionMap config, HttpHandler next) {
// super();
// this.config = config;
// this.next = next;
// }
//
// @Override
// public void handleRequest(HttpServerExchange exchange) throws Exception {
// exchange.putAttachment(CONFIG, config);
// exchange.putAttachment(REQUEST, new SidenRequest(exchange));
// exchange.putAttachment(RESPONSE, new SidenResponse(exchange));
// exchange.addExchangeCompleteListener((ex, next) -> {
// try {
// exchange.removeAttachment(CONFIG);
// exchange.removeAttachment(REQUEST);
// exchange.removeAttachment(RESPONSE);
// } finally {
// next.proceed();
// }
// });
// next.handleRequest(exchange);
// }
//
// public static io.undertow.predicate.Predicate adapt(Predicate<Request> fn) {
// return exchange -> {
// Request request = exchange.getAttachment(Core.REQUEST);
// return fn.test(request);
// };
// }
// }
| import io.undertow.server.HttpServerExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import ninja.siden.internal.BlockingRenderer;
import ninja.siden.internal.Core;
import org.xnio.OptionMap; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
@FunctionalInterface
public interface Renderer<T> {
void render(T model, HttpServerExchange sink) throws IOException;
public static <MODEL> Renderer<MODEL> ofStream(
OutputStreamConsumer<MODEL> fn) {
return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
sink.getOutputStream()));
}
public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
return new BlockingRenderer<MODEL>((model, sink) -> { | // Path: siden-core/src/main/java/ninja/siden/internal/BlockingRenderer.java
// public class BlockingRenderer<T> implements Renderer<T> {
//
// final Renderer<T> renderer;
//
// public BlockingRenderer(Renderer<T> renderer) {
// super();
// this.renderer = renderer;
// }
//
// @Override
// public void render(T model, HttpServerExchange sink) throws IOException {
// if (sink.isBlocking() == false) {
// sink.startBlocking();
// }
// if (sink.isInIoThread()) {
// sink.dispatch(exchange -> {
// renderer.render(model, exchange);
// });
// } else {
// renderer.render(model, sink);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
// public class Core implements HttpHandler {
//
// public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
// .create(OptionMap.class);
//
// public static final AttachmentKey<Request> REQUEST = AttachmentKey
// .create(Request.class);
//
// public static final AttachmentKey<Response> RESPONSE = AttachmentKey
// .create(Response.class);
//
// final OptionMap config;
// final HttpHandler next;
//
// public Core(OptionMap config, HttpHandler next) {
// super();
// this.config = config;
// this.next = next;
// }
//
// @Override
// public void handleRequest(HttpServerExchange exchange) throws Exception {
// exchange.putAttachment(CONFIG, config);
// exchange.putAttachment(REQUEST, new SidenRequest(exchange));
// exchange.putAttachment(RESPONSE, new SidenResponse(exchange));
// exchange.addExchangeCompleteListener((ex, next) -> {
// try {
// exchange.removeAttachment(CONFIG);
// exchange.removeAttachment(REQUEST);
// exchange.removeAttachment(RESPONSE);
// } finally {
// next.proceed();
// }
// });
// next.handleRequest(exchange);
// }
//
// public static io.undertow.predicate.Predicate adapt(Predicate<Request> fn) {
// return exchange -> {
// Request request = exchange.getAttachment(Core.REQUEST);
// return fn.test(request);
// };
// }
// }
// Path: siden-core/src/main/java/ninja/siden/Renderer.java
import io.undertow.server.HttpServerExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import ninja.siden.internal.BlockingRenderer;
import ninja.siden.internal.Core;
import org.xnio.OptionMap;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden;
/**
* @author taichi
*/
@FunctionalInterface
public interface Renderer<T> {
void render(T model, HttpServerExchange sink) throws IOException;
public static <MODEL> Renderer<MODEL> ofStream(
OutputStreamConsumer<MODEL> fn) {
return new BlockingRenderer<MODEL>((model, sink) -> fn.render(model,
sink.getOutputStream()));
}
public static <MODEL> Renderer<MODEL> of(WriterConsumer<MODEL> fn) {
return new BlockingRenderer<MODEL>((model, sink) -> { | OptionMap config = sink.getAttachment(Core.CONFIG); |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/SidenSession.java | // Path: siden-core/src/main/java/ninja/siden/AttributeContainer.java
// public interface AttributeContainer extends Iterable<AttributeContainer.Attr> {
//
// /**
// * @param key
// * attribute name
// * @param newone
// * new attribute
// * @return existing value
// */
// <T> Optional<T> attr(String key, T newone);
//
// <T> Optional<T> attr(String key);
//
// /**
// * @param key
// * @return existing value
// */
// <T> Optional<T> remove(String key);
//
// interface Attr {
// String name();
//
// <T> T value();
//
// <T> T remove();
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/Session.java
// public interface Session extends AttributeContainer {
//
// String id();
//
// void invalidate();
//
// Session regenerate();
//
// io.undertow.server.session.Session raw();
// }
| import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.SessionConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Iterator;
import java.util.Optional;
import ninja.siden.AttributeContainer;
import ninja.siden.Session; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class SidenSession implements Session {
final HttpServerExchange exchange;
final io.undertow.server.session.Session delegate;
public SidenSession(HttpServerExchange exchange,
io.undertow.server.session.Session delegate) {
this.exchange = exchange;
this.delegate = delegate;
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> attr(String key, T newone) {
return Optional.ofNullable((T) this.delegate.setAttribute(key, newone));
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> attr(String key) {
return Optional.ofNullable((T) this.delegate.getAttribute(key));
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> remove(String key) {
return Optional.ofNullable((T) this.delegate.removeAttribute(key));
}
@Override
public Iterator<Attr> iterator() {
Iterator<String> names = this.delegate.getAttributeNames().iterator(); | // Path: siden-core/src/main/java/ninja/siden/AttributeContainer.java
// public interface AttributeContainer extends Iterable<AttributeContainer.Attr> {
//
// /**
// * @param key
// * attribute name
// * @param newone
// * new attribute
// * @return existing value
// */
// <T> Optional<T> attr(String key, T newone);
//
// <T> Optional<T> attr(String key);
//
// /**
// * @param key
// * @return existing value
// */
// <T> Optional<T> remove(String key);
//
// interface Attr {
// String name();
//
// <T> T value();
//
// <T> T remove();
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/Session.java
// public interface Session extends AttributeContainer {
//
// String id();
//
// void invalidate();
//
// Session regenerate();
//
// io.undertow.server.session.Session raw();
// }
// Path: siden-core/src/main/java/ninja/siden/internal/SidenSession.java
import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.SessionConfig;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.Iterator;
import java.util.Optional;
import ninja.siden.AttributeContainer;
import ninja.siden.Session;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class SidenSession implements Session {
final HttpServerExchange exchange;
final io.undertow.server.session.Session delegate;
public SidenSession(HttpServerExchange exchange,
io.undertow.server.session.Session delegate) {
this.exchange = exchange;
this.delegate = delegate;
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> attr(String key, T newone) {
return Optional.ofNullable((T) this.delegate.setAttribute(key, newone));
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> attr(String key) {
return Optional.ofNullable((T) this.delegate.getAttribute(key));
}
@Override
@SuppressWarnings("unchecked")
public <T> Optional<T> remove(String key) {
return Optional.ofNullable((T) this.delegate.removeAttribute(key));
}
@Override
public Iterator<Attr> iterator() {
Iterator<String> names = this.delegate.getAttributeNames().iterator(); | return new Iterator<AttributeContainer.Attr>() { |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/Core.java | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import java.util.function.Predicate;
import ninja.siden.Request;
import ninja.siden.Response;
import org.xnio.OptionMap; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class Core implements HttpHandler {
public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
.create(OptionMap.class);
| // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import java.util.function.Predicate;
import ninja.siden.Request;
import ninja.siden.Response;
import org.xnio.OptionMap;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class Core implements HttpHandler {
public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
.create(OptionMap.class);
| public static final AttachmentKey<Request> REQUEST = AttachmentKey |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/Core.java | // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
| import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import java.util.function.Predicate;
import ninja.siden.Request;
import ninja.siden.Response;
import org.xnio.OptionMap; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class Core implements HttpHandler {
public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
.create(OptionMap.class);
public static final AttachmentKey<Request> REQUEST = AttachmentKey
.create(Request.class);
| // Path: siden-core/src/main/java/ninja/siden/Request.java
// public interface Request extends AttributeContainer {
//
// HttpMethod method();
//
// String path();
//
// /**
// * get path parameter
// *
// * @param key
// * @return
// */
// Optional<String> params(String key);
//
// Map<String, String> params();
//
// /**
// * get query parameter
// *
// * @param key
// * @return
// */
// Optional<String> query(String key);
//
// Optional<String> header(String name);
//
// List<String> headers(String name);
//
// Map<String, List<String>> headers();
//
// Map<String, Cookie> cookies();
//
// Optional<Cookie> cookie(String name);
//
// Optional<String> form(String key);
//
// List<String> forms(String key);
//
// Map<String, List<String>> forms();
//
// Optional<File> file(String key);
//
// List<File> files(String key);
//
// Map<String, List<File>> files();
//
// Optional<String> body();
//
// /**
// * get current session or create new session.
// *
// * @return session
// */
// Session session();
//
// /**
// * get current session
// *
// * @return session or empty
// */
// Optional<Session> current();
//
// boolean xhr();
//
// String protocol();
//
// String scheme();
//
// HttpServerExchange raw();
//
// }
//
// Path: siden-core/src/main/java/ninja/siden/Response.java
// public interface Response {
//
// Response status(int code);
//
// Response header(String name, String... values);
//
// /**
// * set RFC1123 date pattern to Response header.
// *
// * @param name
// * @param date
// * @return this
// */
// Response header(String name, long date);
//
// Response headers(Map<String, String> headers);
//
// Cookie cookie(String name, String value);
//
// /**
// * @param name
// * @return existing value
// */
// Cookie removeCookie(String name);
//
// /**
// * @param contentType
// */
// Response type(String contentType);
//
// Object redirect(String location);
//
// Object redirect(int code, String location);
//
// <MODEL> Object render(MODEL model, Renderer<MODEL> renderer);
//
// <MODEL> Object render(MODEL model, String template);
//
// HttpServerExchange raw();
// }
// Path: siden-core/src/main/java/ninja/siden/internal/Core.java
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import java.util.function.Predicate;
import ninja.siden.Request;
import ninja.siden.Response;
import org.xnio.OptionMap;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class Core implements HttpHandler {
public static final AttachmentKey<OptionMap> CONFIG = AttachmentKey
.create(OptionMap.class);
public static final AttachmentKey<Request> REQUEST = AttachmentKey
.create(Request.class);
| public static final AttachmentKey<Response> RESPONSE = AttachmentKey |
taichi/siden | siden-core/src/main/java/ninja/siden/internal/ReceiveListenerAdapter.java | // Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
| import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedBinaryMessage;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.WebSocketChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import ninja.siden.WebSocket;
import ninja.siden.util.ExceptionalConsumer;
import org.xnio.Pooled; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ReceiveListenerAdapter extends AbstractReceiveListener {
final WebSocket adaptee;
public ReceiveListenerAdapter(WebSocket socket) {
this.adaptee = socket;
}
@Override
protected void onFullTextMessage(WebSocketChannel channel,
BufferedTextMessage message) throws IOException {
try {
this.adaptee.onText(message.getData());
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
protected void onFullBinaryMessage(WebSocketChannel channel,
BufferedBinaryMessage message) throws IOException {
deliver(this.adaptee::onBinary, message);
}
| // Path: siden-core/src/main/java/ninja/siden/WebSocket.java
// public interface WebSocket {
//
// default void onConnect(Connection connection) throws Exception {
// }
//
// default void onText(String payload) throws Exception {
// }
//
// default void onBinary(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPong(ByteBuffer[] payload) throws Exception {
// }
//
// default void onPing(ByteBuffer[] payload) throws Exception {
// }
//
// default void onClose(ByteBuffer[] payload) throws Exception {
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/ExceptionalConsumer.java
// @FunctionalInterface
// public interface ExceptionalConsumer<T, EX extends Exception> {
//
// void accept(T t) throws EX;
// }
// Path: siden-core/src/main/java/ninja/siden/internal/ReceiveListenerAdapter.java
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedBinaryMessage;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.WebSocketChannel;
import java.io.IOException;
import java.nio.ByteBuffer;
import ninja.siden.WebSocket;
import ninja.siden.util.ExceptionalConsumer;
import org.xnio.Pooled;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.internal;
/**
* @author taichi
*/
public class ReceiveListenerAdapter extends AbstractReceiveListener {
final WebSocket adaptee;
public ReceiveListenerAdapter(WebSocket socket) {
this.adaptee = socket;
}
@Override
protected void onFullTextMessage(WebSocketChannel channel,
BufferedTextMessage message) throws IOException {
try {
this.adaptee.onText(message.getData());
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
protected void onFullBinaryMessage(WebSocketChannel channel,
BufferedBinaryMessage message) throws IOException {
deliver(this.adaptee::onBinary, message);
}
| void deliver(ExceptionalConsumer<ByteBuffer[], Exception> deliver, |
taichi/siden | siden-react/src/main/java/ninja/siden/react/JsEngine.java | // Path: siden-core/src/main/java/ninja/siden/util/Suppress.java
// public interface Suppress {
//
// static <T, EX extends Exception> T get(ExceptionalSupplier<T, EX> supplier) {
// try {
// return supplier.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
| import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import ninja.siden.util.Suppress;
import ninja.siden.util.Using;
import org.jboss.logging.Logger; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.react;
/**
* @author taichi
*/
public class JsEngine {
static final Logger LOG = Logger.getLogger(JsEngine.class);
final ScriptEngineManager manager;
public JsEngine() {
manager = new ScriptEngineManager();
}
ScriptEngine newEngine() {
return manager.getEngineByExtension("js");
}
public void initialize(List<Path> scripts) {
ScriptEngine se = newEngine(); | // Path: siden-core/src/main/java/ninja/siden/util/Suppress.java
// public interface Suppress {
//
// static <T, EX extends Exception> T get(ExceptionalSupplier<T, EX> supplier) {
// try {
// return supplier.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: siden-react/src/main/java/ninja/siden/react/JsEngine.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import ninja.siden.util.Suppress;
import ninja.siden.util.Using;
import org.jboss.logging.Logger;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.react;
/**
* @author taichi
*/
public class JsEngine {
static final Logger LOG = Logger.getLogger(JsEngine.class);
final ScriptEngineManager manager;
public JsEngine() {
manager = new ScriptEngineManager();
}
ScriptEngine newEngine() {
return manager.getEngineByExtension("js");
}
public void initialize(List<Path> scripts) {
ScriptEngine se = newEngine(); | Suppress.get(() -> se.eval("var global = this;")); |
taichi/siden | siden-react/src/main/java/ninja/siden/react/JsEngine.java | // Path: siden-core/src/main/java/ninja/siden/util/Suppress.java
// public interface Suppress {
//
// static <T, EX extends Exception> T get(ExceptionalSupplier<T, EX> supplier) {
// try {
// return supplier.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
| import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import ninja.siden.util.Suppress;
import ninja.siden.util.Using;
import org.jboss.logging.Logger; | /*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.react;
/**
* @author taichi
*/
public class JsEngine {
static final Logger LOG = Logger.getLogger(JsEngine.class);
final ScriptEngineManager manager;
public JsEngine() {
manager = new ScriptEngineManager();
}
ScriptEngine newEngine() {
return manager.getEngineByExtension("js");
}
public void initialize(List<Path> scripts) {
ScriptEngine se = newEngine();
Suppress.get(() -> se.eval("var global = this;"));
scripts.forEach(p -> eval(se, p));
this.manager.setBindings(se.getBindings(ScriptContext.ENGINE_SCOPE));
}
public Object eval(String script) {
LOG.debug(manager.getBindings().keySet());
ScriptEngine engine = newEngine();
return Suppress.get(() -> engine.eval(script));
}
public Object eval(Path path) {
LOG.debug(manager.getBindings().keySet());
return eval(newEngine(), path);
}
Object eval(ScriptEngine engine, Path path) { | // Path: siden-core/src/main/java/ninja/siden/util/Suppress.java
// public interface Suppress {
//
// static <T, EX extends Exception> T get(ExceptionalSupplier<T, EX> supplier) {
// try {
// return supplier.get();
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// Path: siden-core/src/main/java/ninja/siden/util/Using.java
// public interface Using {
//
// static <IO extends AutoCloseable, R> R transform(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalFunction<IO, R, Exception> transformer) {
// try (IO t = supplier.get()) {
// return transformer.apply(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// static <IO extends AutoCloseable> void consume(
// ExceptionalSupplier<IO, Exception> supplier,
// ExceptionalConsumer<IO, Exception> consumer) {
// try (IO t = supplier.get()) {
// consumer.accept(t);
// } catch (RuntimeException e) {
// throw e;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: siden-react/src/main/java/ninja/siden/react/JsEngine.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import ninja.siden.util.Suppress;
import ninja.siden.util.Using;
import org.jboss.logging.Logger;
/*
* Copyright 2014 SATO taichi
*
* 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 ninja.siden.react;
/**
* @author taichi
*/
public class JsEngine {
static final Logger LOG = Logger.getLogger(JsEngine.class);
final ScriptEngineManager manager;
public JsEngine() {
manager = new ScriptEngineManager();
}
ScriptEngine newEngine() {
return manager.getEngineByExtension("js");
}
public void initialize(List<Path> scripts) {
ScriptEngine se = newEngine();
Suppress.get(() -> se.eval("var global = this;"));
scripts.forEach(p -> eval(se, p));
this.manager.setBindings(se.getBindings(ScriptContext.ENGINE_SCOPE));
}
public Object eval(String script) {
LOG.debug(manager.getBindings().keySet());
ScriptEngine engine = newEngine();
return Suppress.get(() -> engine.eval(script));
}
public Object eval(Path path) {
LOG.debug(manager.getBindings().keySet());
return eval(newEngine(), path);
}
Object eval(ScriptEngine engine, Path path) { | return Using.transform(() -> Files.newBufferedReader(path), |
beyondckw/SynchronizeOfPPT | Android_v5/src/com/newppt/android/data/SendFileClient.java | // Path: AndroidServer-v4/src/com/newppt/android/entity/DMT.java
// public class DMT implements Serializable{
//
// private int currentPage;
// private int page;
// private String filename;
//
// public String getFilename()
// {
// return filename;
// }
//
// public void setFilename(String name)
// {
// this.filename=name;
// }
//
// public int getCurrentPage()
// {
// return currentPage;
// }
//
// public int getPages()
// {
// return page;
// }
//
// public void setCurrentPage(int currentPage)
// {
// this.currentPage=currentPage;
// }
//
// public void setPage(int page)
// {
// this.page=page;
// }
// }
//
// Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
| import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.PublicKey;
import com.newppt.android.entity.DMT;
import com.newppt.android.entity.MyPath;
import android.os.Environment;
import android.os.Handler;
import android.os.Message; | package com.newppt.android.data;
public class SendFileClient extends Thread {
// private Socket s;
String ip;
int port = 8889;
Handler handler;
String typeString;
final int timeOut = 5000;
public SendFileClient(String ip, Handler handler, String type) {
// TODO Auto-generated constructor stub
this.ip = ip;
this.handler = handler;
this.typeString = type;
}
@Override
public void run() {
// TODO Auto-generated method stub
loadFile();
}
/**
* ä¸è½½æä»¶å½æ°
*/
private void loadFile() {
try {
// Socket s = new Socket(ip, port);
Socket s = new Socket();
// System.out.println("------1-4-0");
s.connect(new InetSocketAddress(ip, port), timeOut);
// System.out.println("------1-3-0");
byte[] buf = new byte[100];
DataOutputStream os = null;
os = new DataOutputStream(s.getOutputStream());
os.writeUTF(typeString);
System.out.println("-----kk----11" );
s.setSoTimeout(timeOut);
InputStream is = s.getInputStream();
// ½ÓÊÕ´«ÊäÀ´µÄÎļþÃû
int len = is.read(buf);
String fileName = new String(buf, 0, len,"GBK");
System.out.println(fileName); | // Path: AndroidServer-v4/src/com/newppt/android/entity/DMT.java
// public class DMT implements Serializable{
//
// private int currentPage;
// private int page;
// private String filename;
//
// public String getFilename()
// {
// return filename;
// }
//
// public void setFilename(String name)
// {
// this.filename=name;
// }
//
// public int getCurrentPage()
// {
// return currentPage;
// }
//
// public int getPages()
// {
// return page;
// }
//
// public void setCurrentPage(int currentPage)
// {
// this.currentPage=currentPage;
// }
//
// public void setPage(int page)
// {
// this.page=page;
// }
// }
//
// Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
// Path: Android_v5/src/com/newppt/android/data/SendFileClient.java
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.PublicKey;
import com.newppt.android.entity.DMT;
import com.newppt.android.entity.MyPath;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
package com.newppt.android.data;
public class SendFileClient extends Thread {
// private Socket s;
String ip;
int port = 8889;
Handler handler;
String typeString;
final int timeOut = 5000;
public SendFileClient(String ip, Handler handler, String type) {
// TODO Auto-generated constructor stub
this.ip = ip;
this.handler = handler;
this.typeString = type;
}
@Override
public void run() {
// TODO Auto-generated method stub
loadFile();
}
/**
* ä¸è½½æä»¶å½æ°
*/
private void loadFile() {
try {
// Socket s = new Socket(ip, port);
Socket s = new Socket();
// System.out.println("------1-4-0");
s.connect(new InetSocketAddress(ip, port), timeOut);
// System.out.println("------1-3-0");
byte[] buf = new byte[100];
DataOutputStream os = null;
os = new DataOutputStream(s.getOutputStream());
os.writeUTF(typeString);
System.out.println("-----kk----11" );
s.setSoTimeout(timeOut);
InputStream is = s.getInputStream();
// ½ÓÊÕ´«ÊäÀ´µÄÎļþÃû
int len = is.read(buf);
String fileName = new String(buf, 0, len,"GBK");
System.out.println(fileName); | String savePath = MyPath.savePptFilePath + fileName; |
beyondckw/SynchronizeOfPPT | Android_v5/src/com/newppt/android/logical/FileInfo.java | // Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
| import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.newppt.android.entity.MyPath; | package com.newppt.android.logical;
public class FileInfo {
/**
* ´´½¨Îļþ¼Ð
*
* @param savePath
*/
public static void CreateFile(String savePath) {
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
}
public static boolean fileExist(String savePath) {
File file = new File(savePath);
return file.exists();
}
/**
* »ñȡ·¾¶ÏÂËùÓÐJPGµÄÐÅÏ¢
*
* @param path
* @return
*/
public static List<JpgPathInfo> getJpgPathInfos(String path) { | // Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
// Path: Android_v5/src/com/newppt/android/logical/FileInfo.java
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.newppt.android.entity.MyPath;
package com.newppt.android.logical;
public class FileInfo {
/**
* ´´½¨Îļþ¼Ð
*
* @param savePath
*/
public static void CreateFile(String savePath) {
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
}
public static boolean fileExist(String savePath) {
File file = new File(savePath);
return file.exists();
}
/**
* »ñȡ·¾¶ÏÂËùÓÐJPGµÄÐÅÏ¢
*
* @param path
* @return
*/
public static List<JpgPathInfo> getJpgPathInfos(String path) { | File pptFile = new File(path + MyPath.pptJpg); |
beyondckw/SynchronizeOfPPT | AndroidServer-v4/src/com/newppt/android/logical/Svg.java | // Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
| import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.newppt.android.entity.MyPath; | this.currentPage = cur;
String prefix = getExt();
setGraphics();
Element svgRoot;
if (prefix.equalsIgnoreCase("ppt")) {
slide[currentPage - 1].draw(graphics);
svgRoot = doc.getDocumentElement();
graphics.getRoot(svgRoot);
// createPPTJpg(doc);
createPPTJpg2(currentPage - 1);
} else {
slidePPTx[currentPage - 1].draw(graphics);
svgRoot = doc.getDocumentElement();
graphics.getRoot(svgRoot);
createPPTXJpg(currentPage - 1);
}
return doc;
}
/**
* ´´½¨pptxµ±Ç°Ò³×ª»¯Îªjpg
*
* @param cur
* µ±Ç°Ò³
*/
public void createPPTXJpg(int cur) {
| // Path: Android_v5/src/com/newppt/android/entity/MyPath.java
// public class MyPath {
//
// public static String rootPath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPT/";
// public static String savePptFilePath = Environment.getExternalStorageDirectory() + "/"
// + "AndroidPPTFile/";
// public static String jpgPath = rootPath + "ppt.jpg";
//
// public static String pptJpg = "/ppt";
// public static String noteJpg = "/note";
//
// String fileName ="ppt.jpg";
//
// public MyPath() {
// // TODO Auto-generated constructor stub
// }
//
// public String returnRootPath() {
// return rootPath;
// }
//
// public String returnJpgPath() {
// return jpgPath;
// }
//
// public String returnFileName() {
// return fileName;
// }
//
// }
// Path: AndroidServer-v4/src/com/newppt/android/logical/Svg.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.RichTextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.newppt.android.entity.MyPath;
this.currentPage = cur;
String prefix = getExt();
setGraphics();
Element svgRoot;
if (prefix.equalsIgnoreCase("ppt")) {
slide[currentPage - 1].draw(graphics);
svgRoot = doc.getDocumentElement();
graphics.getRoot(svgRoot);
// createPPTJpg(doc);
createPPTJpg2(currentPage - 1);
} else {
slidePPTx[currentPage - 1].draw(graphics);
svgRoot = doc.getDocumentElement();
graphics.getRoot(svgRoot);
createPPTXJpg(currentPage - 1);
}
return doc;
}
/**
* ´´½¨pptxµ±Ç°Ò³×ª»¯Îªjpg
*
* @param cur
* µ±Ç°Ò³
*/
public void createPPTXJpg(int cur) {
| MyPath mypath = new MyPath(); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/util/Util.java | // Path: src/main/java/shopJava/model/Credentials.java
// public class Credentials {
//
// public final String username;
// public final String password;
//
// public Credentials(final String username, final String password) {
// this.username = username;
// this.password = password;
// }
// }
//
// Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
| import shopJava.model.Credentials;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.List;
import java.util.Optional; | package shopJava.util;
public class Util {
public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
if (!optUser.isPresent()) { // replaces if (user != null)
throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
}
final User user = optUser.get();
return checkUserLoggedIn(user, credentials);
}
public static User checkUserLoggedIn(final User user, final Credentials credentials) {
if (!user.name.equals(credentials.username)) {
throw new RuntimeException(new IllegalAccessException("Incorrect first: " + credentials.username));
}
if (!user.password.equals(credentials.password)) {
throw new RuntimeException(new IllegalAccessException("Bad password supplied for user: " + credentials.username));
}
return user;
}
public static void sleep(final int seconds) {
try {
Thread.sleep(seconds * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static int average(final int totalAmount, final int orderCount) {
return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
}
| // Path: src/main/java/shopJava/model/Credentials.java
// public class Credentials {
//
// public final String username;
// public final String password;
//
// public Credentials(final String username, final String password) {
// this.username = username;
// this.password = password;
// }
// }
//
// Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
// Path: src/main/java/shopJava/util/Util.java
import shopJava.model.Credentials;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.List;
import java.util.Optional;
package shopJava.util;
public class Util {
public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
if (!optUser.isPresent()) { // replaces if (user != null)
throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
}
final User user = optUser.get();
return checkUserLoggedIn(user, credentials);
}
public static User checkUserLoggedIn(final User user, final Credentials credentials) {
if (!user.name.equals(credentials.username)) {
throw new RuntimeException(new IllegalAccessException("Incorrect first: " + credentials.username));
}
if (!user.password.equals(credentials.password)) {
throw new RuntimeException(new IllegalAccessException("Bad password supplied for user: " + credentials.username));
}
return user;
}
public static void sleep(final int seconds) {
try {
Thread.sleep(seconds * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static int average(final int totalAmount, final int orderCount) {
return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
}
| public static int totalAmountOf(final List<Order> orders) { |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ03CompletionStage.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | private Optional<User> _findUserByName(final String name) {
final Document doc = usersCollection
.find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
CompletionStage<Optional<User>> findUserByName(final String name) {
Supplier<Optional<User>> supplier = () -> _findUserByName(name);
return CompletableFuture.supplyAsync(supplier);
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
Supplier<List<Order>> supplier = () -> _findOrdersByUsername(username);
return CompletableFuture.supplyAsync(supplier);
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ03CompletionStage.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
private Optional<User> _findUserByName(final String name) {
final Document doc = usersCollection
.find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
CompletionStage<Optional<User>> findUserByName(final String name) {
Supplier<Optional<User>> supplier = () -> _findUserByName(name);
return CompletableFuture.supplyAsync(supplier);
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
Supplier<List<Order>> supplier = () -> _findOrdersByUsername(username);
return CompletableFuture.supplyAsync(supplier);
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | .thenApply(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ09RxStreamsWithObservables.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import org.reactivestreams.Publisher;
import rx.Observable;
import rx.Single;
import shopJava.model.*;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static rx.RxReactiveStreams.toObservable;
import static rx.RxReactiveStreams.toPublisher;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | }
private Single<User> _findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first()
.toSingle()
.map(doc -> new User(doc));
}
private Observable<Order> _findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username))
.toObservable()
.map(doc -> new Order(doc));
}
Publisher<User> findUserByName(final String name) {
return toPublisher(_findUserByName(name).toObservable());
}
Publisher<Order> findOrdersByUsername(final String username) {
return toPublisher(_findOrdersByUsername(username));
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return toObservable(dao.findUserByName(credentials.username))
.toSingle() | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ09RxStreamsWithObservables.java
import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import org.reactivestreams.Publisher;
import rx.Observable;
import rx.Single;
import shopJava.model.*;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static rx.RxReactiveStreams.toObservable;
import static rx.RxReactiveStreams.toPublisher;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
}
private Single<User> _findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first()
.toSingle()
.map(doc -> new User(doc));
}
private Observable<Order> _findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username))
.toObservable()
.map(doc -> new Order(doc));
}
Publisher<User> findUserByName(final String name) {
return toPublisher(_findUserByName(name).toObservable());
}
Publisher<Order> findOrdersByUsername(final String username) {
return toPublisher(_findOrdersByUsername(username));
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return toObservable(dao.findUserByName(credentials.username))
.toSingle() | .map(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Sync.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME; | package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Sync {
public static void main(String[] args) {
new Sync();
}
private final MongoClient client = new MongoClient(new MongoClientURI(MONGODB_URI));
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Sync() {
List<String> simpsons = blockingIO_GetDataFromDB();
simpsons.forEach(simpson -> System.out.println(simpson));
}
private List<String> blockingIO_GetDataFromDB() {
final List<Document> docs = usersCollection.find().into(new ArrayList<>());
return docs
.stream() | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
// Path: src/main/java/shopJava/async_reactive/Sync.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Sync {
public static void main(String[] args) {
new Sync();
}
private final MongoClient client = new MongoClient(new MongoClientURI(MONGODB_URI));
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Sync() {
List<String> simpsons = blockingIO_GetDataFromDB();
simpsons.forEach(simpson -> System.out.println(simpson));
}
private List<String> blockingIO_GetDataFromDB() {
final List<Document> docs = usersCollection.find().into(new ArrayList<>());
return docs
.stream() | .map(doc -> new User(doc)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ08RxStreamsWithObservables.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.bson.Document;
import org.reactivestreams.Publisher;
import rx.Observable;
import rx.Single;
import shopJava.model.*;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static rx.RxReactiveStreams.toObservable;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | package shopJava.queries;
@SuppressWarnings("Convert2MethodRef")
public class QueryJ08RxStreamsWithObservables {
public static void main(String[] args) throws Exception {
new QueryJ08RxStreamsWithObservables();
}
private final DAO dao = new DAO();
private class DAO {
private final MongoCollection<Document> usersCollection;
private final MongoCollection<Document> ordersCollection;
DAO() {
final MongoClient client = MongoClients.create(MONGODB_URI);
final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
this.usersCollection = db.getCollection(USERS_COLLECTION_NAME);
this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME);
}
Publisher<Document> findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first();
}
Publisher<Document> findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username));
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return toObservable(dao.findUserByName(credentials.username))
.toSingle()
.map(doc -> new User(doc)) // no null check as we don't get null objects in the stream | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ08RxStreamsWithObservables.java
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.bson.Document;
import org.reactivestreams.Publisher;
import rx.Observable;
import rx.Single;
import shopJava.model.*;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static rx.RxReactiveStreams.toObservable;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
package shopJava.queries;
@SuppressWarnings("Convert2MethodRef")
public class QueryJ08RxStreamsWithObservables {
public static void main(String[] args) throws Exception {
new QueryJ08RxStreamsWithObservables();
}
private final DAO dao = new DAO();
private class DAO {
private final MongoCollection<Document> usersCollection;
private final MongoCollection<Document> ordersCollection;
DAO() {
final MongoClient client = MongoClients.create(MONGODB_URI);
final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
this.usersCollection = db.getCollection(USERS_COLLECTION_NAME);
this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME);
}
Publisher<Document> findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first();
}
Publisher<Document> findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username));
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return toObservable(dao.findUserByName(credentials.username))
.toSingle()
.map(doc -> new User(doc)) // no null check as we don't get null objects in the stream | .map(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ02Future.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | .find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
Future<Optional<User>> findUserByName(final String name) {
Callable<Optional<User>> callable = () -> _findUserByName(name);
return executor.submit(callable);
}
Future<List<Order>> findOrdersByUsername(final String username) {
Callable<List<Order>> callable = () -> _findOrdersByUsername(username);
return executor.submit(callable);
}
} // end DAO
private String logIn(final Credentials credentials) {
try {
final Future<Optional<User>> future = dao.findUserByName(credentials.username);
final Optional<User> optUser = future.get(); | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ02Future.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
.find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
Future<Optional<User>> findUserByName(final String name) {
Callable<Optional<User>> callable = () -> _findUserByName(name);
return executor.submit(callable);
}
Future<List<Order>> findOrdersByUsername(final String username) {
Callable<List<Order>> callable = () -> _findOrdersByUsername(username);
return executor.submit(callable);
}
} // end DAO
private String logIn(final Credentials credentials) {
try {
final Future<Optional<User>> future = dao.findUserByName(credentials.username);
final Optional<User> optUser = future.get(); | final User user = checkUserLoggedIn(optUser, credentials); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ07RxObservables.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import rx.Single;
import shopJava.model.*;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME);
}
private Single<User> _findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first()
.toSingle()
.map(doc -> new User(doc));
}
private Observable<Order> _findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username))
.toObservable()
.map(doc -> new Order(doc));
}
Single<User> findUserByName(final String name) {
return _findUserByName(name);
}
Observable<Order> findOrdersByUsername(final String username) {
return _findOrdersByUsername(username);
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ07RxObservables.java
import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import rx.Single;
import shopJava.model.*;
import java.util.concurrent.CountDownLatch;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
this.ordersCollection = db.getCollection(ORDERS_COLLECTION_NAME);
}
private Single<User> _findUserByName(final String name) {
return usersCollection
.find(eq("_id", name))
.first()
.toSingle()
.map(doc -> new User(doc));
}
private Observable<Order> _findOrdersByUsername(final String username) {
return ordersCollection
.find(eq("username", username))
.toObservable()
.map(doc -> new Order(doc));
}
Single<User> findUserByName(final String name) {
return _findUserByName(name);
}
Observable<Order> findOrdersByUsername(final String username) {
return _findOrdersByUsername(username);
}
} // end DAO
private Single<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | .map(user -> checkUserLoggedIn(user, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ04bCompletionStageCompleteRefactored.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; |
CompletionStage<Optional<User>> findUserByName(final String name) {
Supplier<Optional<User>> supplier = () -> _findUserByName(name);
return provideResultAsync(supplier, executor);
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
Supplier<List<Order>> supplier = () -> _findOrdersByUsername(username);
return provideResultAsync(supplier, executor);
}
private <T> CompletionStage<T> provideResultAsync(final Supplier<T> supplier, final ExecutorService executorService) {
final CompletableFuture<T> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
future.complete(supplier.get());
} catch (Exception e) {
future.completeExceptionally(e);
}
});
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ04bCompletionStageCompleteRefactored.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
CompletionStage<Optional<User>> findUserByName(final String name) {
Supplier<Optional<User>> supplier = () -> _findUserByName(name);
return provideResultAsync(supplier, executor);
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
Supplier<List<Order>> supplier = () -> _findOrdersByUsername(username);
return provideResultAsync(supplier, executor);
}
private <T> CompletionStage<T> provideResultAsync(final Supplier<T> supplier, final ExecutorService executorService) {
final CompletableFuture<T> future = new CompletableFuture<>();
executorService.execute(() -> {
try {
future.complete(supplier.get());
} catch (Exception e) {
future.completeExceptionally(e);
}
});
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | .thenApply(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Streams.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
| import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import shopJava.model.User;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep; | package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Streams {
public static void main(String[] args) {
new Streams();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Streams() {
Observable<String> obsSimpsons = nonblockingIOWithStreams_GetDataFromDB();
obsSimpsons.subscribe(new Observer<String>() {
@Override
public void onNext(String simpson) {
System.out.println(simpson);
}
@Override
public void onCompleted() {
System.out.println("----- DONE -----");
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
| // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// Path: src/main/java/shopJava/async_reactive/Streams.java
import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import shopJava.model.User;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep;
package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Streams {
public static void main(String[] args) {
new Streams();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Streams() {
Observable<String> obsSimpsons = nonblockingIOWithStreams_GetDataFromDB();
obsSimpsons.subscribe(new Observer<String>() {
@Override
public void onNext(String simpson) {
System.out.println(simpson);
}
@Override
public void onCompleted() {
System.out.println("----- DONE -----");
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
| sleep(2); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Streams.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
| import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import shopJava.model.User;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep; | private Streams() {
Observable<String> obsSimpsons = nonblockingIOWithStreams_GetDataFromDB();
obsSimpsons.subscribe(new Observer<String>() {
@Override
public void onNext(String simpson) {
System.out.println(simpson);
}
@Override
public void onCompleted() {
System.out.println("----- DONE -----");
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
sleep(2);
}
private Observable<String> nonblockingIOWithStreams_GetDataFromDB() {
return usersCollection
.find()
.toObservable() | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// Path: src/main/java/shopJava/async_reactive/Streams.java
import com.mongodb.rx.client.MongoClient;
import com.mongodb.rx.client.MongoClients;
import com.mongodb.rx.client.MongoCollection;
import com.mongodb.rx.client.MongoDatabase;
import org.bson.Document;
import rx.Observable;
import rx.Observer;
import shopJava.model.User;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep;
private Streams() {
Observable<String> obsSimpsons = nonblockingIOWithStreams_GetDataFromDB();
obsSimpsons.subscribe(new Observer<String>() {
@Override
public void onNext(String simpson) {
System.out.println(simpson);
}
@Override
public void onCompleted() {
System.out.println("----- DONE -----");
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
sleep(2);
}
private Observable<String> nonblockingIOWithStreams_GetDataFromDB() {
return usersCollection
.find()
.toObservable() | .map(doc -> new User(doc)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ01Blocking.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | }
private Optional<User> _findUserByName(final String name) {
final Document doc = usersCollection
.find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
Optional<User> findUserByName(final String name) {
return _findUserByName(name);
}
List<Order> findOrdersByUsername(final String username) {
return _findOrdersByUsername(username);
}
} // end DAO
private String logIn(final Credentials credentials) {
final Optional<User> optUser = dao.findUserByName(credentials.username); | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ01Blocking.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
}
private Optional<User> _findUserByName(final String name) {
final Document doc = usersCollection
.find(eq("_id", name))
.first();
return Optional.ofNullable(doc).map(User::new);
}
private List<Order> _findOrdersByUsername(final String username) {
final List<Document> docs = ordersCollection
.find(eq("username", username))
.into(new ArrayList<>());
return docs.stream()
.map(doc -> new Order(doc))
.collect(toList());
}
Optional<User> findUserByName(final String name) {
return _findUserByName(name);
}
List<Order> findOrdersByUsername(final String username) {
return _findOrdersByUsername(username);
}
} // end DAO
private String logIn(final Credentials credentials) {
final Optional<User> optUser = dao.findUserByName(credentials.username); | final User user = checkUserLoggedIn(optUser, credentials); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ06aCompletionStageCompleteCallback.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | _findUserByName(name, (user, t) -> {
if (t == null) {
future.complete(user);
} else {
future.completeExceptionally(t);
}
});
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
_findOrdersByUsername(username, (orders, t) -> {
if (t == null) {
future.complete(orders);
} else {
future.completeExceptionally(t);
}
});
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials. username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ06aCompletionStageCompleteCallback.java
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
_findUserByName(name, (user, t) -> {
if (t == null) {
future.complete(user);
} else {
future.completeExceptionally(t);
}
});
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
_findOrdersByUsername(username, (orders, t) -> {
if (t == null) {
future.complete(orders);
} else {
future.completeExceptionally(t);
}
});
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials. username) | .thenApply(user -> checkUserLoggedIn(user, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ05Callback.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | _findUserByName(name, callback);
}
void findOrdersByUsername(final String username, final SingleResultCallback<List<Order>> callback) {
_findOrdersByUsername(username, callback);
}
} // end DAO
private void findUser(final String username, SingleResultCallback<Optional<User>> callback) {
dao.findUserByName(username, callback);
}
private void processOrdersOf(String username, SingleResultCallback<List<Order>> callback) {
dao.findOrdersByUsername(username, callback);
}
private void eCommerceStatistics(final Credentials credentials) throws Exception {
System.out.println("--- Calculating eCommerce statistings of user \"" + credentials.username + "\" ...");
final CountDownLatch latch = new CountDownLatch(1);
findUser(credentials.username, (optUser, t1) -> { // 1st callback
try {
if (t1 != null) {
throw t1;
}
| // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ05Callback.java
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
_findUserByName(name, callback);
}
void findOrdersByUsername(final String username, final SingleResultCallback<List<Order>> callback) {
_findOrdersByUsername(username, callback);
}
} // end DAO
private void findUser(final String username, SingleResultCallback<Optional<User>> callback) {
dao.findUserByName(username, callback);
}
private void processOrdersOf(String username, SingleResultCallback<List<Order>> callback) {
dao.findOrdersByUsername(username, callback);
}
private void eCommerceStatistics(final Credentials credentials) throws Exception {
System.out.println("--- Calculating eCommerce statistings of user \"" + credentials.username + "\" ...");
final CountDownLatch latch = new CountDownLatch(1);
findUser(credentials.username, (optUser, t1) -> { // 1st callback
try {
if (t1 != null) {
throw t1;
}
| checkUserLoggedIn(optUser, credentials); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ06bCompletionStageCompleteCallbackRefactored.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | final CompletableFuture<Optional<User>> future = new CompletableFuture<>();
_findUserByName(name, callbackToCompleteFuture(future));
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
_findOrdersByUsername(username, callbackToCompleteFuture(future));
return future;
}
private <T> SingleResultCallback<T> callbackToCompleteFuture(final CompletableFuture<T> future) {
return (result, t) -> {
if (t == null) {
future.complete(result);
} else {
future.completeExceptionally(t);
}
};
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ06bCompletionStageCompleteCallbackRefactored.java
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
final CompletableFuture<Optional<User>> future = new CompletableFuture<>();
_findUserByName(name, callbackToCompleteFuture(future));
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
_findOrdersByUsername(username, callbackToCompleteFuture(future));
return future;
}
private <T> SingleResultCallback<T> callbackToCompleteFuture(final CompletableFuture<T> future) {
return (result, t) -> {
if (t == null) {
future.complete(result);
} else {
future.completeExceptionally(t);
}
};
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | .thenApply(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Async.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
| import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME; | package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Async {
public static void main(String[] args) {
new Async();
}
private final MongoClient client = new MongoClient();
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Async() {
Runnable r = () -> {
List<String> simpsons = blockingIO_GetDataFromDB();
simpsons.forEach(simpson -> System.out.println(simpson));
};
new Thread(r).start();
}
private List<String> blockingIO_GetDataFromDB() {
final List<Document> docs = usersCollection.find().into(new ArrayList<>());
return docs
.stream() | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
// Path: src/main/java/shopJava/async_reactive/Async.java
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Async {
public static void main(String[] args) {
new Async();
}
private final MongoClient client = new MongoClient();
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Async() {
Runnable r = () -> {
List<String> simpsons = blockingIO_GetDataFromDB();
simpsons.forEach(simpson -> System.out.println(simpson));
};
new Thread(r).start();
}
private List<String> blockingIO_GetDataFromDB() {
final List<Document> docs = usersCollection.find().into(new ArrayList<>());
return docs
.stream() | .map(doc -> new User(doc)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Callback.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
| import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep; | package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Callback {
public static void main(String[] args) {
new Callback();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Callback() {
SingleResultCallback<List<String>> callback = new SingleResultCallback<List<String>>() {
@Override
public void onResult(List<String> simpsons, Throwable t) {
if (t != null) {
t.printStackTrace();
} else {
simpsons.forEach(simpson -> System.out.println(simpson));
}
}
};
nonblockingIOWithCallbacks_GetDataFromDB(callback);
| // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// Path: src/main/java/shopJava/async_reactive/Callback.java
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep;
package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Callback {
public static void main(String[] args) {
new Callback();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Callback() {
SingleResultCallback<List<String>> callback = new SingleResultCallback<List<String>>() {
@Override
public void onResult(List<String> simpsons, Throwable t) {
if (t != null) {
t.printStackTrace();
} else {
simpsons.forEach(simpson -> System.out.println(simpson));
}
}
};
nonblockingIOWithCallbacks_GetDataFromDB(callback);
| sleep(2); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/async_reactive/Callback.java | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
| import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep; | package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Callback {
public static void main(String[] args) {
new Callback();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Callback() {
SingleResultCallback<List<String>> callback = new SingleResultCallback<List<String>>() {
@Override
public void onResult(List<String> simpsons, Throwable t) {
if (t != null) {
t.printStackTrace();
} else {
simpsons.forEach(simpson -> System.out.println(simpson));
}
}
};
nonblockingIOWithCallbacks_GetDataFromDB(callback);
sleep(2);
}
private void nonblockingIOWithCallbacks_GetDataFromDB(SingleResultCallback<List<String>> callback) {
usersCollection
.find() | // Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static void sleep(final int seconds) {
// try {
// Thread.sleep(seconds * 1000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// Path: src/main/java/shopJava/async_reactive/Callback.java
import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import static shopJava.util.Constants.MONGODB_URI;
import static shopJava.util.Constants.SHOP_DB_NAME;
import static shopJava.util.Constants.USERS_COLLECTION_NAME;
import static shopJava.util.Util.sleep;
package shopJava.async_reactive;
@SuppressWarnings("Convert2MethodRef")
public class Callback {
public static void main(String[] args) {
new Callback();
}
private final MongoClient client = MongoClients.create(MONGODB_URI);
private final MongoDatabase db = client.getDatabase(SHOP_DB_NAME);
private final MongoCollection<Document> usersCollection = db.getCollection(USERS_COLLECTION_NAME);
private Callback() {
SingleResultCallback<List<String>> callback = new SingleResultCallback<List<String>>() {
@Override
public void onResult(List<String> simpsons, Throwable t) {
if (t != null) {
t.printStackTrace();
} else {
simpsons.forEach(simpson -> System.out.println(simpson));
}
}
};
nonblockingIOWithCallbacks_GetDataFromDB(callback);
sleep(2);
}
private void nonblockingIOWithCallbacks_GetDataFromDB(SingleResultCallback<List<String>> callback) {
usersCollection
.find() | .map(doc -> new User(doc)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/create/InsertUsersOrders.java | // Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.mongodb.client.model.Filters.eq;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*; | package shopJava.create;
class UserDAO {
private final MongoCollection<Document> collection;
UserDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
| // Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
// Path: src/main/java/shopJava/create/InsertUsersOrders.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.mongodb.client.model.Filters.eq;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
package shopJava.create;
class UserDAO {
private final MongoCollection<Document> collection;
UserDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
| void insertUser(final User user) { |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/create/InsertUsersOrders.java | // Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.mongodb.client.model.Filters.eq;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*; | package shopJava.create;
class UserDAO {
private final MongoCollection<Document> collection;
UserDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
void insertUser(final User user) {
collection.insertOne(user.toDocument());
}
long countUsers() {
return collection.count();
}
List<User> findAllUsers() {
final List<Document> docs = collection.find().into(new ArrayList<>());
return docs.stream().map(doc -> new User(doc)).collect(toList());
}
User findUserByName(final String name) {
final Document doc = collection.find(eq("_id", name)).first();
return doc == null ? null : new User(doc);
}
}
class OrderDAO {
private final MongoCollection<Document> collection;
OrderDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
| // Path: src/main/java/shopJava/model/Order.java
// public class Order {
//
// private static final String ID = "_id";
// private static final String USERNAME = "first";
// private static final String AMOUNT = "amount";
//
// public final int id;
// public final String username;
// public final int amount;
//
// public Order(final int id, final String username, final int amount) {
// this.id = id;
// this.username = username;
// this.amount = amount;
// }
//
// public Order(final Document doc) {
// this(doc.getInteger(ID), doc.getString(USERNAME), doc.getInteger(AMOUNT));
// }
//
// @Override
// public String toString() {
// return "Order{" +
// ID + "=" + id +
// ", " + USERNAME + "='" + username + '\'' +
// ", " + AMOUNT + "=" + (amount/100.0) +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, id).append(USERNAME, username).append(AMOUNT, amount);
// }
// }
//
// Path: src/main/java/shopJava/model/User.java
// public class User {
//
// private static final String ID = "_id";
// private static final String NAME = "name";
// private static final String PASSWORD = "password";
//
// public final String name;
// public final String password;
//
// public User(final String name, final String password) {
// this.name = name;
// this.password = password;
// }
//
// public User(Document doc) {
// this(doc.getString(ID), doc.getString(PASSWORD));
// }
//
// @Override
// public String toString() {
// return "User{" +
// NAME + "='" + name + '\'' +
// ", " + PASSWORD + "='" + password + '\'' +
// '}';
// }
//
// public void print() {
// System.out.print(this);
// }
//
// public void println() {
// System.out.println(this);
// }
//
// public Document toDocument() {
// return new Document(ID, name).append(PASSWORD, password);
// }
// }
//
// Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
// Path: src/main/java/shopJava/create/InsertUsersOrders.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.Order;
import shopJava.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.mongodb.client.model.Filters.eq;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
package shopJava.create;
class UserDAO {
private final MongoCollection<Document> collection;
UserDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
void insertUser(final User user) {
collection.insertOne(user.toDocument());
}
long countUsers() {
return collection.count();
}
List<User> findAllUsers() {
final List<Document> docs = collection.find().into(new ArrayList<>());
return docs.stream().map(doc -> new User(doc)).collect(toList());
}
User findUserByName(final String name) {
final Document doc = collection.find(eq("_id", name)).first();
return doc == null ? null : new User(doc);
}
}
class OrderDAO {
private final MongoCollection<Document> collection;
OrderDAO(final MongoCollection<Document> collection) {
this.collection = collection;
}
| void insertOrder(Order order) { |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/queries/QueryJ04aCompletionStageComplete.java | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
| import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn; | future.completeExceptionally(e);
}
};
executor.execute(runnable);
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
final Runnable runnable = () -> {
try {
future.complete(_findOrdersByUsername(username));
} catch (Exception e) {
future.completeExceptionally(e);
}
};
executor.execute(runnable);
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | // Path: src/main/java/shopJava/util/Constants.java
// public interface Constants {
//
// int MAX_ORDERS_PER_USER = 10;
//
// String MONGODB_URI = "mongodb://localhost:27017";
// String SHOP_DB_NAME = "shop";
// String USERS_COLLECTION_NAME = "users";
// String ORDERS_COLLECTION_NAME = "orders";
//
// String HOMER = "homer";
// String MARGE = "marge";
// String BART = "bart";
// String LISA = "lisa";
// String MAGGIE = "maggie";
//
// String[] SIMPSONS = {HOMER, MARGE, BART, LISA, MAGGIE};
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static User checkUserLoggedIn(final Optional<User> optUser, final Credentials credentials) {
//
// if (!optUser.isPresent()) { // replaces if (user != null)
// throw new RuntimeException(new IllegalAccessException("User unknown: " + credentials.username));
// }
// final User user = optUser.get();
// return checkUserLoggedIn(user, credentials);
// }
// Path: src/main/java/shopJava/queries/QueryJ04aCompletionStageComplete.java
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import shopJava.model.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
import static com.mongodb.client.model.Filters.eq;
import static java.lang.Thread.sleep;
import static java.util.stream.Collectors.toList;
import static shopJava.util.Constants.*;
import static shopJava.util.Util.average;
import static shopJava.util.Util.checkUserLoggedIn;
future.completeExceptionally(e);
}
};
executor.execute(runnable);
return future;
}
CompletionStage<List<Order>> findOrdersByUsername(final String username) {
final CompletableFuture<List<Order>> future = new CompletableFuture<>();
final Runnable runnable = () -> {
try {
future.complete(_findOrdersByUsername(username));
} catch (Exception e) {
future.completeExceptionally(e);
}
};
executor.execute(runnable);
return future;
}
} // end DAO
private CompletionStage<String> logIn(final Credentials credentials) {
return dao.findUserByName(credentials.username) | .thenApply(optUser -> checkUserLoggedIn(optUser, credentials)) |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/model/Result.java | // Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int totalAmountOf(final List<Order> orders) {
// return orders.stream().mapToInt(order -> order.amount).sum();
// }
| import java.util.List;
import static shopJava.util.Util.average;
import static shopJava.util.Util.totalAmountOf; | package shopJava.model;
@SuppressWarnings("WeakerAccess")
public class Result {
public final String username;
public final int orderCount;
public final int totalAmount;
public final int avgAmount;
public Result(final String username, final int orderCount, final int totalAmount, final int avgAmount) {
this.username = username;
this.orderCount = orderCount;
this.totalAmount = totalAmount;
this.avgAmount = avgAmount;
}
public Result(final String username, final int orderCount, final int totalAmount) { | // Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int totalAmountOf(final List<Order> orders) {
// return orders.stream().mapToInt(order -> order.amount).sum();
// }
// Path: src/main/java/shopJava/model/Result.java
import java.util.List;
import static shopJava.util.Util.average;
import static shopJava.util.Util.totalAmountOf;
package shopJava.model;
@SuppressWarnings("WeakerAccess")
public class Result {
public final String username;
public final int orderCount;
public final int totalAmount;
public final int avgAmount;
public Result(final String username, final int orderCount, final int totalAmount, final int avgAmount) {
this.username = username;
this.orderCount = orderCount;
this.totalAmount = totalAmount;
this.avgAmount = avgAmount;
}
public Result(final String username, final int orderCount, final int totalAmount) { | this(username, orderCount, totalAmount, average(totalAmount, orderCount)); |
hermannhueck/reactive-mongo-access | src/main/java/shopJava/model/Result.java | // Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int totalAmountOf(final List<Order> orders) {
// return orders.stream().mapToInt(order -> order.amount).sum();
// }
| import java.util.List;
import static shopJava.util.Util.average;
import static shopJava.util.Util.totalAmountOf; | package shopJava.model;
@SuppressWarnings("WeakerAccess")
public class Result {
public final String username;
public final int orderCount;
public final int totalAmount;
public final int avgAmount;
public Result(final String username, final int orderCount, final int totalAmount, final int avgAmount) {
this.username = username;
this.orderCount = orderCount;
this.totalAmount = totalAmount;
this.avgAmount = avgAmount;
}
public Result(final String username, final int orderCount, final int totalAmount) {
this(username, orderCount, totalAmount, average(totalAmount, orderCount));
}
public Result(final String username, final List<Order> orders) { | // Path: src/main/java/shopJava/util/Util.java
// public static int average(final int totalAmount, final int orderCount) {
// return orderCount == 0 ? 0 : Math.round((100.0f * totalAmount / orderCount) / 100);
// }
//
// Path: src/main/java/shopJava/util/Util.java
// public static int totalAmountOf(final List<Order> orders) {
// return orders.stream().mapToInt(order -> order.amount).sum();
// }
// Path: src/main/java/shopJava/model/Result.java
import java.util.List;
import static shopJava.util.Util.average;
import static shopJava.util.Util.totalAmountOf;
package shopJava.model;
@SuppressWarnings("WeakerAccess")
public class Result {
public final String username;
public final int orderCount;
public final int totalAmount;
public final int avgAmount;
public Result(final String username, final int orderCount, final int totalAmount, final int avgAmount) {
this.username = username;
this.orderCount = orderCount;
this.totalAmount = totalAmount;
this.avgAmount = avgAmount;
}
public Result(final String username, final int orderCount, final int totalAmount) {
this(username, orderCount, totalAmount, average(totalAmount, orderCount));
}
public Result(final String username, final List<Order> orders) { | this(username, orders.size(), totalAmountOf(orders)); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/AboutActivity.java | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import clock.socoolby.com.clock.utils.FuncUnit; | package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 04/01/2017.
*/
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
TextView version=(TextView)findViewById(R.id.version); | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/clock/socoolby/com/clock/AboutActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import clock.socoolby.com.clock.utils.FuncUnit;
package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 04/01/2017.
*/
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
TextView version=(TextView)findViewById(R.id.version); | version.setText(getString(R.string.version)+FuncUnit.getVersionName(FuncUnit.getBoxPackageName())); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/SharePerferenceModel.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
| import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.R; | }
public JSONObject getTimeLocation() {
return timeLocation;
}
public JSONObject getDateLocation() {
return dateLocation;
}
public JSONObject getDayLocation() {
return dayLocation;
}
public JSONObject getWeatherLocation() {
return weatherLocation;
}
public JSONObject getDescriptionLocation() {
return descriptionLocation;
}
private void fromJsonString(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
typeHourPower = jsonObject.getInt(KEY_TYPE_HOUR_POWER);
isDisplaySecond = jsonObject.getBoolean(KEY_IS_DISPLAY_SECOND);
isTickSound = jsonObject.getBoolean(KEY_IS_TICK_SOUND);
isTriggerScreen =jsonObject.optBoolean(KEY_IS_TRIGGER_SCREEN,true);
mCity = jsonObject.getString(KEY_CITY); | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/SharePerferenceModel.java
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.R;
}
public JSONObject getTimeLocation() {
return timeLocation;
}
public JSONObject getDateLocation() {
return dateLocation;
}
public JSONObject getDayLocation() {
return dayLocation;
}
public JSONObject getWeatherLocation() {
return weatherLocation;
}
public JSONObject getDescriptionLocation() {
return descriptionLocation;
}
private void fromJsonString(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
typeHourPower = jsonObject.getInt(KEY_TYPE_HOUR_POWER);
isDisplaySecond = jsonObject.getBoolean(KEY_IS_DISPLAY_SECOND);
isTickSound = jsonObject.getBoolean(KEY_IS_TICK_SOUND);
isTriggerScreen =jsonObject.optBoolean(KEY_IS_TRIGGER_SCREEN,true);
mCity = jsonObject.getString(KEY_CITY); | mDescription = jsonObject.optString(KEY_DESCRPTION, ClockApplication.getContext().getResources().getString(R.string.always_zuo_never_die)); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/NetworkService.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/protocol/RequestBase.java
// public abstract class RequestBase {
// RequestBase() {
// }
//
// public String getUrl() {
// return "";
// }
//
// public JSONObject createRequest() {
// JSONObject object = new JSONObject();
// try {
// buildRequest(object);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return object;
// }
//
// protected abstract void buildRequest(JSONObject object) throws JSONException;
// }
| import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.protocol.RequestBase;
| package clock.socoolby.com.clock.utils;
public final class NetworkService {
private static NetworkService mInstance;
private RequestQueue mRequestQueue;
private DefaultRetryPolicy mRetryPolicy;
private NetworkService() {
mRequestQueue = getRequestQueue();
}
private final static String TAG = "NetworkService";
public static synchronized NetworkService getInstance() {
if (mInstance == null) {
mInstance = new NetworkService();
}
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue =
| // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/protocol/RequestBase.java
// public abstract class RequestBase {
// RequestBase() {
// }
//
// public String getUrl() {
// return "";
// }
//
// public JSONObject createRequest() {
// JSONObject object = new JSONObject();
// try {
// buildRequest(object);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return object;
// }
//
// protected abstract void buildRequest(JSONObject object) throws JSONException;
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/NetworkService.java
import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.protocol.RequestBase;
package clock.socoolby.com.clock.utils;
public final class NetworkService {
private static NetworkService mInstance;
private RequestQueue mRequestQueue;
private DefaultRetryPolicy mRetryPolicy;
private NetworkService() {
mRequestQueue = getRequestQueue();
}
private final static String TAG = "NetworkService";
public static synchronized NetworkService getInstance() {
if (mInstance == null) {
mInstance = new NetworkService();
}
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue =
| Volley.newRequestQueue(ClockApplication.getContext());
|
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/NetworkService.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/protocol/RequestBase.java
// public abstract class RequestBase {
// RequestBase() {
// }
//
// public String getUrl() {
// return "";
// }
//
// public JSONObject createRequest() {
// JSONObject object = new JSONObject();
// try {
// buildRequest(object);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return object;
// }
//
// protected abstract void buildRequest(JSONObject object) throws JSONException;
// }
| import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.protocol.RequestBase;
| package clock.socoolby.com.clock.utils;
public final class NetworkService {
private static NetworkService mInstance;
private RequestQueue mRequestQueue;
private DefaultRetryPolicy mRetryPolicy;
private NetworkService() {
mRequestQueue = getRequestQueue();
}
private final static String TAG = "NetworkService";
public static synchronized NetworkService getInstance() {
if (mInstance == null) {
mInstance = new NetworkService();
}
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue =
Volley.newRequestQueue(ClockApplication.getContext());
}
return mRequestQueue;
}
private void setRequestTimeout(int ms) {
int timeout = (ms == 0) ? DefaultRetryPolicy.DEFAULT_TIMEOUT_MS : ms;
mRetryPolicy = new DefaultRetryPolicy(timeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
| // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/protocol/RequestBase.java
// public abstract class RequestBase {
// RequestBase() {
// }
//
// public String getUrl() {
// return "";
// }
//
// public JSONObject createRequest() {
// JSONObject object = new JSONObject();
// try {
// buildRequest(object);
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return object;
// }
//
// protected abstract void buildRequest(JSONObject object) throws JSONException;
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/NetworkService.java
import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.protocol.RequestBase;
package clock.socoolby.com.clock.utils;
public final class NetworkService {
private static NetworkService mInstance;
private RequestQueue mRequestQueue;
private DefaultRetryPolicy mRetryPolicy;
private NetworkService() {
mRequestQueue = getRequestQueue();
}
private final static String TAG = "NetworkService";
public static synchronized NetworkService getInstance() {
if (mInstance == null) {
mInstance = new NetworkService();
}
return mInstance;
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue =
Volley.newRequestQueue(ClockApplication.getContext());
}
return mRequestQueue;
}
private void setRequestTimeout(int ms) {
int timeout = (ms == 0) ? DefaultRetryPolicy.DEFAULT_TIMEOUT_MS : ms;
mRetryPolicy = new DefaultRetryPolicy(timeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
| public boolean sendRequest(RequestBase request, final RequestListener listener) {
|
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/protocol/UpdateRequest.java | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
| import org.json.JSONException;
import org.json.JSONObject;
import clock.socoolby.com.clock.utils.FuncUnit; | package clock.socoolby.com.clock.protocol;
class UpdateRequest extends RequestBase {
@Override
public String getUrl() {
return "http://www.socoolby.com/clock/update";
}
@Override
protected void buildRequest(JSONObject object) throws JSONException { | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/clock/socoolby/com/clock/protocol/UpdateRequest.java
import org.json.JSONException;
import org.json.JSONObject;
import clock.socoolby.com.clock.utils.FuncUnit;
package clock.socoolby.com.clock.protocol;
class UpdateRequest extends RequestBase {
@Override
public String getUrl() {
return "http://www.socoolby.com/clock/update";
}
@Override
protected void buildRequest(JSONObject object) throws JSONException { | object.put("version", FuncUnit.getVersionName(FuncUnit.getBoxPackageName())); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
| import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication; | package clock.socoolby.com.clock.utils;
/**
* Alway zuo,never die.
* Created by socoolby on 03/01/2017.
*/
public class FuncUnit {
private final static String TAG = FuncUnit.class.getSimpleName();
public static String getBoxPackageName() {
try { | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication;
package clock.socoolby.com.clock.utils;
/**
* Alway zuo,never die.
* Created by socoolby on 03/01/2017.
*/
public class FuncUnit {
private final static String TAG = FuncUnit.class.getSimpleName();
public static String getBoxPackageName() {
try { | PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/ProximityService.java | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
// public class ScreenManager {
// public static boolean isScreenOn() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// return pm.isScreenOn();
// }
//
// public static void turnScreenOff() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// pm.goToSleep(SystemClock.uptimeMillis());
// }
//
// public static void systemLock(Activity context) {
// DevicePolicyManager policyManager;
// ComponentName componentName;
// policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
//
// componentName = new ComponentName(context, ActivateAdmin.class);
//
// if (!policyManager.isAdminActive(componentName)) {
// Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
// intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
// context.startActivity(intent);
// }
// if (policyManager.isAdminActive(componentName)) {
// Window localWindow = context.getWindow();
// WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
// localLayoutParams.screenBrightness = 1.0F;
// localWindow.setAttributes(localLayoutParams);
// policyManager.lockNow();
// }
//
// }
//
// public static void systemUnLock() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "SimpleTimer");
// mWakelock.acquire();
// }
//
// public static boolean isApplicationBroughtToBackground(final Context context) {
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
// if (!tasks.isEmpty()) {
// ComponentName topActivity = tasks.get(0).topActivity;
// if (!topActivity.getPackageName().equals(context.getPackageName())) {
// return true;
// }
// }
// return false;
// }
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import clock.socoolby.com.clock.utils.FuncUnit;
import clock.socoolby.com.clock.utils.ScreenManager; | package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 16/04/2017.
*/
public class ProximityService extends Service {
private final static String TAG = ProximityService.class.getSimpleName();
private SensorManager mSensorManager;
private SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] its = sensorEvent.values;
Log.d(TAG, String.format("its %f %f %f len:,%d", its[0], its[1], its[2], its.length));
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) { | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
// public class ScreenManager {
// public static boolean isScreenOn() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// return pm.isScreenOn();
// }
//
// public static void turnScreenOff() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// pm.goToSleep(SystemClock.uptimeMillis());
// }
//
// public static void systemLock(Activity context) {
// DevicePolicyManager policyManager;
// ComponentName componentName;
// policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
//
// componentName = new ComponentName(context, ActivateAdmin.class);
//
// if (!policyManager.isAdminActive(componentName)) {
// Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
// intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
// context.startActivity(intent);
// }
// if (policyManager.isAdminActive(componentName)) {
// Window localWindow = context.getWindow();
// WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
// localLayoutParams.screenBrightness = 1.0F;
// localWindow.setAttributes(localLayoutParams);
// policyManager.lockNow();
// }
//
// }
//
// public static void systemUnLock() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "SimpleTimer");
// mWakelock.acquire();
// }
//
// public static boolean isApplicationBroughtToBackground(final Context context) {
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
// if (!tasks.isEmpty()) {
// ComponentName topActivity = tasks.get(0).topActivity;
// if (!topActivity.getPackageName().equals(context.getPackageName())) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/clock/socoolby/com/clock/ProximityService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import clock.socoolby.com.clock.utils.FuncUnit;
import clock.socoolby.com.clock.utils.ScreenManager;
package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 16/04/2017.
*/
public class ProximityService extends Service {
private final static String TAG = ProximityService.class.getSimpleName();
private SensorManager mSensorManager;
private SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] its = sensorEvent.values;
Log.d(TAG, String.format("its %f %f %f len:,%d", its[0], its[1], its[2], its.length));
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) { | if (FuncUnit.isForeground(ClockApplication.getContext(), MainActivity.class.getName())) { |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/ProximityService.java | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
// public class ScreenManager {
// public static boolean isScreenOn() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// return pm.isScreenOn();
// }
//
// public static void turnScreenOff() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// pm.goToSleep(SystemClock.uptimeMillis());
// }
//
// public static void systemLock(Activity context) {
// DevicePolicyManager policyManager;
// ComponentName componentName;
// policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
//
// componentName = new ComponentName(context, ActivateAdmin.class);
//
// if (!policyManager.isAdminActive(componentName)) {
// Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
// intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
// context.startActivity(intent);
// }
// if (policyManager.isAdminActive(componentName)) {
// Window localWindow = context.getWindow();
// WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
// localLayoutParams.screenBrightness = 1.0F;
// localWindow.setAttributes(localLayoutParams);
// policyManager.lockNow();
// }
//
// }
//
// public static void systemUnLock() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "SimpleTimer");
// mWakelock.acquire();
// }
//
// public static boolean isApplicationBroughtToBackground(final Context context) {
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
// if (!tasks.isEmpty()) {
// ComponentName topActivity = tasks.get(0).topActivity;
// if (!topActivity.getPackageName().equals(context.getPackageName())) {
// return true;
// }
// }
// return false;
// }
// }
| import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import clock.socoolby.com.clock.utils.FuncUnit;
import clock.socoolby.com.clock.utils.ScreenManager; | package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 16/04/2017.
*/
public class ProximityService extends Service {
private final static String TAG = ProximityService.class.getSimpleName();
private SensorManager mSensorManager;
private SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] its = sensorEvent.values;
Log.d(TAG, String.format("its %f %f %f len:,%d", its[0], its[1], its[2], its.length));
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (FuncUnit.isForeground(ClockApplication.getContext(), MainActivity.class.getName())) {
if (its[0] == 0.0) {
System.out.println("Hand stay"); | // Path: app/src/main/java/clock/socoolby/com/clock/utils/FuncUnit.java
// public class FuncUnit {
// private final static String TAG = FuncUnit.class.getSimpleName();
//
// public static String getBoxPackageName() {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(ClockApplication.getContext().getPackageName(), 0);
// return packageInfo.packageName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static String getVersionName(String packageName) {
// try {
// PackageInfo packageInfo = ClockApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
// return packageInfo.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// return null;
// }
// }
//
// public static void openURL(Context c, String url) {
// if (url == null)
// return;
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// c.startActivity(intent);
// }
//
// /**
// * @param context
// * @param className Activity Class Name
// */
// public static boolean isForeground(Context context, String className) {
// if (context == null || TextUtils.isEmpty(className)) {
// return false;
// }
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
// if (list != null && list.size() > 0) {
// ComponentName cpn = list.get(0).topActivity;
// if (className.equals(cpn.getClassName())) {
// return true;
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
// public class ScreenManager {
// public static boolean isScreenOn() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// return pm.isScreenOn();
// }
//
// public static void turnScreenOff() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// pm.goToSleep(SystemClock.uptimeMillis());
// }
//
// public static void systemLock(Activity context) {
// DevicePolicyManager policyManager;
// ComponentName componentName;
// policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
//
// componentName = new ComponentName(context, ActivateAdmin.class);
//
// if (!policyManager.isAdminActive(componentName)) {
// Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
// intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
// context.startActivity(intent);
// }
// if (policyManager.isAdminActive(componentName)) {
// Window localWindow = context.getWindow();
// WindowManager.LayoutParams localLayoutParams = localWindow.getAttributes();
// localLayoutParams.screenBrightness = 1.0F;
// localWindow.setAttributes(localLayoutParams);
// policyManager.lockNow();
// }
//
// }
//
// public static void systemUnLock() {
// PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
// PowerManager.WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "SimpleTimer");
// mWakelock.acquire();
// }
//
// public static boolean isApplicationBroughtToBackground(final Context context) {
// ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
// if (!tasks.isEmpty()) {
// ComponentName topActivity = tasks.get(0).topActivity;
// if (!topActivity.getPackageName().equals(context.getPackageName())) {
// return true;
// }
// }
// return false;
// }
// }
// Path: app/src/main/java/clock/socoolby/com/clock/ProximityService.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.util.Log;
import clock.socoolby.com.clock.utils.FuncUnit;
import clock.socoolby.com.clock.utils.ScreenManager;
package clock.socoolby.com.clock;
/**
* Alway zuo,never die.
* Created by socoolby on 16/04/2017.
*/
public class ProximityService extends Service {
private final static String TAG = ProximityService.class.getSimpleName();
private SensorManager mSensorManager;
private SensorEventListener mSensorListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] its = sensorEvent.values;
Log.d(TAG, String.format("its %f %f %f len:,%d", its[0], its[1], its[2], its.length));
if (sensorEvent.sensor.getType() == Sensor.TYPE_PROXIMITY) {
if (FuncUnit.isForeground(ClockApplication.getContext(), MainActivity.class.getName())) {
if (its[0] == 0.0) {
System.out.println("Hand stay"); | if (ScreenManager.isScreenOn()) { |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/Player.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
| import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.R; | if (hourUnit > 0) {
playList.add(NUM_AUDIO.get(hourUnit));
}
} else {
playList.add(NUM_AUDIO.get(hour));
}
playList.add(R.raw.hour);
int minuteUnit = minute % 10;
int minuteTenDigit = minute / 10 * 10;
playList.add(NUM_AUDIO.get(minuteTenDigit));
if (minuteUnit > 0)
playList.add(NUM_AUDIO.get(minuteUnit));
playList.add(R.raw.minute);
play(playList, activity);
}
private void play(LinkedList<Integer> playList, Context activity) {
this.playList = playList;
if (mediaPlayer == null)
mediaPlayer = buildMediaPlayer();
play(activity);
}
private AssetFileDescriptor tickFile = null;
public void playTick(Context activity) { | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/Player.java
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.R;
if (hourUnit > 0) {
playList.add(NUM_AUDIO.get(hourUnit));
}
} else {
playList.add(NUM_AUDIO.get(hour));
}
playList.add(R.raw.hour);
int minuteUnit = minute % 10;
int minuteTenDigit = minute / 10 * 10;
playList.add(NUM_AUDIO.get(minuteTenDigit));
if (minuteUnit > 0)
playList.add(NUM_AUDIO.get(minuteUnit));
playList.add(R.raw.minute);
play(playList, activity);
}
private void play(LinkedList<Integer> playList, Context activity) {
this.playList = playList;
if (mediaPlayer == null)
mediaPlayer = buildMediaPlayer();
play(activity);
}
private AssetFileDescriptor tickFile = null;
public void playTick(Context activity) { | if (!ScreenManager.isScreenOn() || ScreenManager.isApplicationBroughtToBackground(ClockApplication.getContext())) |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/FileUtils.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
| import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import clock.socoolby.com.clock.ClockApplication; | package clock.socoolby.com.clock.utils;
/**
* Alway zuo,never die.
* Created by socoolby on 12/11/15.
*/
public class FileUtils {
public static boolean isExistsFile(String fileName) {
File file = getFile(fileName);
return file.exists();
}
public static File getFile(String path) {
try { | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/FileUtils.java
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import clock.socoolby.com.clock.ClockApplication;
package clock.socoolby.com.clock.utils;
/**
* Alway zuo,never die.
* Created by socoolby on 12/11/15.
*/
public class FileUtils {
public static boolean isExistsFile(String fileName) {
File file = getFile(fileName);
return file.exists();
}
public static File getFile(String path) {
try { | return new File(ClockApplication.getContext().getFilesDir() + path); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/ActivateAdmin.java
// public class ActivateAdmin extends DeviceAdminReceiver {
//
// }
| import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.view.Window;
import android.view.WindowManager;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.ActivateAdmin; | package clock.socoolby.com.clock.utils;
public class ScreenManager {
public static boolean isScreenOn() { | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/ActivateAdmin.java
// public class ActivateAdmin extends DeviceAdminReceiver {
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.view.Window;
import android.view.WindowManager;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.ActivateAdmin;
package clock.socoolby.com.clock.utils;
public class ScreenManager {
public static boolean isScreenOn() { | PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE); |
socoolby/CoolClock | app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java | // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/ActivateAdmin.java
// public class ActivateAdmin extends DeviceAdminReceiver {
//
// }
| import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.view.Window;
import android.view.WindowManager;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.ActivateAdmin; | package clock.socoolby.com.clock.utils;
public class ScreenManager {
public static boolean isScreenOn() {
PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
return pm.isScreenOn();
}
public static void turnScreenOff() {
PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis());
}
public static void systemLock(Activity context) {
DevicePolicyManager policyManager;
ComponentName componentName;
policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
| // Path: app/src/main/java/clock/socoolby/com/clock/ClockApplication.java
// public class ClockApplication extends Application {
//
// private static ClockApplication sEndzoneBoxApp;
// private BusinessService mBusinessService = new BusinessService();
//
// public static ClockApplication getInstance() {
// return sEndzoneBoxApp;
// }
//
// @Override
// public void onCreate() {
// sEndzoneBoxApp = this;
// init();
// super.onCreate();
// }
//
//
// public void init() {
// if (!FileUtils.isExistsFile(Constants.SHARE_PERFERENCE_FILE)) {
// SharePerferenceModel model = new SharePerferenceModel();
// model.setTypeHourPower(Constants.TALKING_HALF_AN_HOUR);
// DateModel startTimeModel = new DateModel();
// startTimeModel.setTime(12, 31);
// DateModel stopTimeModel = new DateModel();
// stopTimeModel.setTime(14, 31);
// model.setStartHourPowerTime(startTimeModel);
// model.setStopHourPowerTime(stopTimeModel);
// model.setCity(getString(R.string.shenzhen));
// model.save();
// }
// }
//
// public static Context getContext() {
// return ClockApplication.getInstance().getApplicationContext();
// }
//
// public BusinessService getBusinessService() {
// return mBusinessService;
// }
//
// private MainActivity mMainActivity;
//
// public void setMainActivity(MainActivity mainActivity) {
// this.mMainActivity = mainActivity;
// }
//
// public MainActivity getMainActivity() {
// return mMainActivity;
// }
//
// }
//
// Path: app/src/main/java/clock/socoolby/com/clock/ActivateAdmin.java
// public class ActivateAdmin extends DeviceAdminReceiver {
//
// }
// Path: app/src/main/java/clock/socoolby/com/clock/utils/ScreenManager.java
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.view.Window;
import android.view.WindowManager;
import java.util.List;
import clock.socoolby.com.clock.ClockApplication;
import clock.socoolby.com.clock.ActivateAdmin;
package clock.socoolby.com.clock.utils;
public class ScreenManager {
public static boolean isScreenOn() {
PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
return pm.isScreenOn();
}
public static void turnScreenOff() {
PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis());
}
public static void systemLock(Activity context) {
DevicePolicyManager policyManager;
ComponentName componentName;
policyManager = (DevicePolicyManager) context.getSystemService(Activity.DEVICE_POLICY_SERVICE);
| componentName = new ComponentName(context, ActivateAdmin.class); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/EncryptionService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/crypto/AES.java
// public class AES {
//
//
// private static final Logger LOG = LoggerFactory.getLogger(AES.class);
//
// private static final String ALGORITHM_AES = "AES";
// private static final String ALGORITH_SHA_256 = "SHA-256";
// private static final String ECB_PKCS5_PADDING = "AES/ECB/PKCS5Padding";
// private static final String ECB_PKCS5PADDING = "AES/ECB/PKCS5PADDING";
//
// private AES() {}
//
// public static SecretKeySpec getSecretKey(String myKey) {
//
// SecretKeySpec secretKey = null;
//
// try {
// byte[] key = myKey.getBytes(StandardCharsets.UTF_8);
// MessageDigest sha = MessageDigest.getInstance(ALGORITH_SHA_256);
// key = sha.digest(key);
// key = Arrays.copyOf(key, 16);
// secretKey = new SecretKeySpec(key, ALGORITHM_AES);
// }
// catch (NoSuchAlgorithmException e) {
// LOG.error(e.getMessage(), e);
// }
//
// return secretKey;
// }
//
// public static String encrypt(String strToEncrypt, String secret) {
//
// try {
// SecretKeySpec secretKey = getSecretKey(secret);
// Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
// cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
// }
// catch (Exception e) {
// LOG.error(e.getMessage(), e);
// }
// return null;
// }
//
// public static String decrypt(String strToDecrypt, String secret) {
//
// try {
// SecretKeySpec secretKey = getSecretKey(secret);
// Cipher cipher = Cipher.getInstance(ECB_PKCS5PADDING);
// cipher.init(Cipher.DECRYPT_MODE, secretKey);
// return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
// }
// catch (Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return null;
// }
// }
| import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.crypto.AES; | package de.papke.cloud.portal.service;
@Service
public class EncryptionService {
@Value("${ENCRYPTOR_SECRET}")
private String secret;
public String encrypt(String text) { | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/crypto/AES.java
// public class AES {
//
//
// private static final Logger LOG = LoggerFactory.getLogger(AES.class);
//
// private static final String ALGORITHM_AES = "AES";
// private static final String ALGORITH_SHA_256 = "SHA-256";
// private static final String ECB_PKCS5_PADDING = "AES/ECB/PKCS5Padding";
// private static final String ECB_PKCS5PADDING = "AES/ECB/PKCS5PADDING";
//
// private AES() {}
//
// public static SecretKeySpec getSecretKey(String myKey) {
//
// SecretKeySpec secretKey = null;
//
// try {
// byte[] key = myKey.getBytes(StandardCharsets.UTF_8);
// MessageDigest sha = MessageDigest.getInstance(ALGORITH_SHA_256);
// key = sha.digest(key);
// key = Arrays.copyOf(key, 16);
// secretKey = new SecretKeySpec(key, ALGORITHM_AES);
// }
// catch (NoSuchAlgorithmException e) {
// LOG.error(e.getMessage(), e);
// }
//
// return secretKey;
// }
//
// public static String encrypt(String strToEncrypt, String secret) {
//
// try {
// SecretKeySpec secretKey = getSecretKey(secret);
// Cipher cipher = Cipher.getInstance(ECB_PKCS5_PADDING);
// cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
// }
// catch (Exception e) {
// LOG.error(e.getMessage(), e);
// }
// return null;
// }
//
// public static String decrypt(String strToDecrypt, String secret) {
//
// try {
// SecretKeySpec secretKey = getSecretKey(secret);
// Cipher cipher = Cipher.getInstance(ECB_PKCS5PADDING);
// cipher.init(Cipher.DECRYPT_MODE, secretKey);
// return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
// }
// catch (Exception e) {
// LOG.error(e.getMessage(), e);
// }
//
// return null;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/EncryptionService.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.crypto.AES;
package de.papke.cloud.portal.service;
@Service
public class EncryptionService {
@Value("${ENCRYPTOR_SECRET}")
private String secret;
public String encrypt(String text) { | return AES.encrypt(text, secret); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.papke.cloud.portal.constants.Constants;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.helper;
/**
* Script helper class with utility functions for groovy scripts.
*/
public class ScriptHelper {
private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
private PrintWriter out;
public ScriptHelper(PrintWriter out) {
this.out = out;
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void print(Object result) {
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.papke.cloud.portal.constants.Constants;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.helper;
/**
* Script helper class with utility functions for groovy scripts.
*/
public class ScriptHelper {
private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
private PrintWriter out;
public ScriptHelper(PrintWriter out) {
this.out = out;
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void print(Object result) {
| if (result instanceof User) { |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.papke.cloud.portal.constants.Constants;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.helper;
/**
* Script helper class with utility functions for groovy scripts.
*/
public class ScriptHelper {
private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
private PrintWriter out;
public ScriptHelper(PrintWriter out) {
this.out = out;
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void print(Object result) {
if (result instanceof User) {
User user = (User) result;
printUser(user);
}
else {
if (result instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) result;
printCollection(collection);
}
else {
if (result instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) result;
printMap(map);
}
else {
out.append(String.valueOf(result));
}
}
}
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void println(Object result) {
print(result); | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.papke.cloud.portal.constants.Constants;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.helper;
/**
* Script helper class with utility functions for groovy scripts.
*/
public class ScriptHelper {
private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
private PrintWriter out;
public ScriptHelper(PrintWriter out) {
this.out = out;
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void print(Object result) {
if (result instanceof User) {
User user = (User) result;
printUser(user);
}
else {
if (result instanceof Collection<?>) {
Collection<?> collection = (Collection<?>) result;
printCollection(collection);
}
else {
if (result instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) result;
printMap(map);
}
else {
out.append(String.valueOf(result));
}
}
}
}
/**
* Method for printing an object on console.
*
* @param result
*/
public void println(Object result) {
print(result); | print(Constants.CHAR_NEW_LINE); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/KeyPairService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import de.papke.cloud.portal.constants.Constants; | package de.papke.cloud.portal.service;
@Service
public class KeyPairService {
private static final Logger LOG = LoggerFactory.getLogger(KeyPairService.class);
private static final JSch JSCH = new JSch();
private static final String COMMENT = "keygen@cloud-portal";
public List<File> createKeyPair() {
List<File> keyFileList = new ArrayList<>();
try{ | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/constants/Constants.java
// public class Constants {
//
// public static final String CHAR_EMPTY = "";
// public static final String CHAR_STAR = "*";
// public static final String CHAR_DIAMOND = "#";
// public static final String CHAR_EQUAL = "=";
// public static final String CHAR_DASH = "-";
// public static final String CHAR_UNDERSCORE = "_";
// public static final String CHAR_WHITESPACE = " ";
// public static final String CHAR_DOUBLE_QUOTE = "\"";
// public static final String CHAR_SINGLE_QUOTE = "'";
// public static final String CHAR_NEW_LINE = "\n";
// public static final String CHAR_TAB = "\t";
// public static final String CHAR_DOT = ".";
// public static final String CHAR_DOUBLE_DOT = ":";
// public static final String CHAR_BRACE_OPEN = "{";
// public static final String CHAR_BRACE_CLOSE = "}";
// public static final String CHAR_BRAKET_OPEN = "[";
// public static final String CHAR_BRAKET_CLOSE = "]";
// public static final String CHAR_COMMA = ",";
// public static final String CHAR_PARENTHESES_OPEN = "(";
// public static final String CHAR_PARENTHESES_CLOSE = ")";
//
// public static final String ACTION_INIT = "init";
// public static final String ACTION_APPLY = "apply";
// public static final String ACTION_PLAN = "plan";
// public static final String ACTION_DESTROY = "destroy";
//
// public static final String VM_EXPIRATION_DAYS_STRING = "expiration_days";
//
// public static final String KEY_FILE_PREFIX = "id_rsa";
// public static final String KEY_FILE_PUBLIC_SUFFIX = ".pub";
// public static final String KEY_FILE_PRIVATE_SUFFIX = ".pem";
//
// public static final String RESULT_FILE_PREFIX = "result";
// public static final String RESULT_FILE_SUFFIX = ".zip";
//
// public static final String TMP_FOLDER_PREFIX = System.getProperty("java.io.tmpdir") + "/tmp-";
//
// public static final String FOLDER_CONSOLE = "console";
// public static final String FOLDER_USE_CASE = "usecase";
// public static final String FOLDER_PROVISIONER = "provisioner";
// public static final String FOLDER_TERRAFORM = "terraform";
//
// public static final String VAR_TYPE_SECRET = "secret";
//
// public static final String PROVISIONER_ESXI = "esxi";
//
// public static final String RESPONSE_CONTENT_TYPE_TEXT_PLAIN = "text/plain; charset=utf-8";
//
// private Constants() {}
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/KeyPairService.java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import de.papke.cloud.portal.constants.Constants;
package de.papke.cloud.portal.service;
@Service
public class KeyPairService {
private static final Logger LOG = LoggerFactory.getLogger(KeyPairService.class);
private static final JSch JSCH = new JSch();
private static final String COMMENT = "keygen@cloud-portal";
public List<File> createKeyPair() {
List<File> keyFileList = new ArrayList<>();
try{ | File privateKeyFile = File.createTempFile(Constants.KEY_FILE_PREFIX, Constants.CHAR_EMPTY); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.service;
@Service
public class UserService {
private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
@Value("${APPLICATION_ADMIN_GROUP}")
private String adminGroup;
@Autowired
private DirectoryService directoryService;
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/UserService.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.service;
@Service
public class UserService {
private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
@Value("${APPLICATION_ADMIN_GROUP}")
private String adminGroup;
@Autowired
private DirectoryService directoryService;
| public User getUser(String username) { |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/GroovyService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java
// public class ScriptHelper {
//
// private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
//
// private PrintWriter out;
//
// public ScriptHelper(PrintWriter out) {
// this.out = out;
// }
//
// /**
// * Method for printing an object on console.
// *
// * @param result
// */
// public void print(Object result) {
//
// if (result instanceof User) {
// User user = (User) result;
// printUser(user);
// }
// else {
// if (result instanceof Collection<?>) {
// Collection<?> collection = (Collection<?>) result;
// printCollection(collection);
// }
// else {
// if (result instanceof Map<?, ?>) {
// Map<?, ?> map = (Map<?, ?>) result;
// printMap(map);
// }
// else {
// out.append(String.valueOf(result));
// }
// }
// }
// }
//
// /**
// * Method for printing an object on console.
// *
// * @param result
// */
// public void println(Object result) {
// print(result);
// print(Constants.CHAR_NEW_LINE);
// }
//
// /**
// * Method for printing a collection on console.
// *
// * @param collection
// */
// private void printCollection(Collection<?> collection) {
//
// Object[] collectionArray = collection.toArray();
//
// out
// .append(OBJECTS_FOUND)
// .append(String.valueOf(collectionArray.length))
// .append(Constants.CHAR_NEW_LINE)
// .append(Constants.CHAR_NEW_LINE);
//
// for (Object object : collectionArray) {
// print(object);
// out.append(Constants.CHAR_NEW_LINE);
// }
// }
//
// /**
// * Method for printing a map on console.
// *
// * @param map
// */
// private void printMap(Map<?, ?> map) {
//
// Set<?> keySet = map.keySet();
//
// out
// .append(OBJECTS_FOUND)
// .append(String.valueOf(map.keySet().size()))
// .append(Constants.CHAR_NEW_LINE)
// .append(Constants.CHAR_NEW_LINE);
//
// for (Object key : keySet) {
// Object value = map.get(key);
// out
// .append(String.valueOf(key))
// .append(": ")
// .append(String.valueOf(value))
// .append(Constants.CHAR_NEW_LINE);
// }
// }
//
// /**
// * Method for printing a user object on console.
// *
// * @param user
// */
// private void printUser(User user) {
//
// String username = user.getUsername();
//
// out
// .append(username)
// .append(Constants.CHAR_NEW_LINE);
//
// for (int i = 0; i < username.length(); i++) {
// out.append("-");
// if (i == username.length() - 1) {
// out.append(Constants.CHAR_NEW_LINE);
// }
// }
//
// List<String> groups = user.getGroups();
//
// for (String group : groups) {
// out
// .append(group)
// .append(Constants.CHAR_NEW_LINE);
// }
// }
// }
| import java.io.PrintWriter;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.SimpleScriptContext;
import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.helper.ScriptHelper; | package de.papke.cloud.portal.service;
/**
* Groovy service class for executing groovy scripts
*/
@Component
public class GroovyService {
private static final Logger LOG = LoggerFactory.getLogger(GroovyService.class);
private static final ScriptEngine SCRIPT_ENGINE = new GroovyScriptEngineImpl();
private static final String SCRIPT_VAR_SCRIPT = "script";
/**
* Method for executing a groovy script.
*
* @param script
* @param variableMap
* @return
*/
public void execute(String script, Map<String, Object> variableMap, PrintWriter out) {
try {
// create script helper | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/helper/ScriptHelper.java
// public class ScriptHelper {
//
// private static final String OBJECTS_FOUND = "OBJECTS FOUND: ";
//
// private PrintWriter out;
//
// public ScriptHelper(PrintWriter out) {
// this.out = out;
// }
//
// /**
// * Method for printing an object on console.
// *
// * @param result
// */
// public void print(Object result) {
//
// if (result instanceof User) {
// User user = (User) result;
// printUser(user);
// }
// else {
// if (result instanceof Collection<?>) {
// Collection<?> collection = (Collection<?>) result;
// printCollection(collection);
// }
// else {
// if (result instanceof Map<?, ?>) {
// Map<?, ?> map = (Map<?, ?>) result;
// printMap(map);
// }
// else {
// out.append(String.valueOf(result));
// }
// }
// }
// }
//
// /**
// * Method for printing an object on console.
// *
// * @param result
// */
// public void println(Object result) {
// print(result);
// print(Constants.CHAR_NEW_LINE);
// }
//
// /**
// * Method for printing a collection on console.
// *
// * @param collection
// */
// private void printCollection(Collection<?> collection) {
//
// Object[] collectionArray = collection.toArray();
//
// out
// .append(OBJECTS_FOUND)
// .append(String.valueOf(collectionArray.length))
// .append(Constants.CHAR_NEW_LINE)
// .append(Constants.CHAR_NEW_LINE);
//
// for (Object object : collectionArray) {
// print(object);
// out.append(Constants.CHAR_NEW_LINE);
// }
// }
//
// /**
// * Method for printing a map on console.
// *
// * @param map
// */
// private void printMap(Map<?, ?> map) {
//
// Set<?> keySet = map.keySet();
//
// out
// .append(OBJECTS_FOUND)
// .append(String.valueOf(map.keySet().size()))
// .append(Constants.CHAR_NEW_LINE)
// .append(Constants.CHAR_NEW_LINE);
//
// for (Object key : keySet) {
// Object value = map.get(key);
// out
// .append(String.valueOf(key))
// .append(": ")
// .append(String.valueOf(value))
// .append(Constants.CHAR_NEW_LINE);
// }
// }
//
// /**
// * Method for printing a user object on console.
// *
// * @param user
// */
// private void printUser(User user) {
//
// String username = user.getUsername();
//
// out
// .append(username)
// .append(Constants.CHAR_NEW_LINE);
//
// for (int i = 0; i < username.length(); i++) {
// out.append("-");
// if (i == username.length() - 1) {
// out.append(Constants.CHAR_NEW_LINE);
// }
// }
//
// List<String> groups = user.getGroups();
//
// for (String group : groups) {
// out
// .append(group)
// .append(Constants.CHAR_NEW_LINE);
// }
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/GroovyService.java
import java.io.PrintWriter;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.SimpleScriptContext;
import org.codehaus.groovy.jsr223.GroovyScriptEngineImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import de.papke.cloud.portal.helper.ScriptHelper;
package de.papke.cloud.portal.service;
/**
* Groovy service class for executing groovy scripts
*/
@Component
public class GroovyService {
private static final Logger LOG = LoggerFactory.getLogger(GroovyService.class);
private static final ScriptEngine SCRIPT_ENGINE = new GroovyScriptEngineImpl();
private static final String SCRIPT_VAR_SCRIPT = "script";
/**
* Method for executing a groovy script.
*
* @param script
* @param variableMap
* @return
*/
public void execute(String script, Map<String, Object> variableMap, PrintWriter out) {
try {
// create script helper | ScriptHelper scriptHelper = new ScriptHelper(out); |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/controller/CredentialsController.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/CredentialsModel.java
// public class CredentialsModel {
//
// private List<Credentials> credentialsList;
//
// public List<Credentials> getCredentialsList() {
// return credentialsList;
// }
//
// public void setCredentialsList(List<Credentials> credentialsList) {
// this.credentialsList = credentialsList;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
// @Service
// public class CredentialsService {
//
// @Autowired
// private EncryptionService encryptionService;
//
// @Autowired
// private SessionUserService sessionUserService;
//
// @Autowired
// private CredentialsDao credentialsDao;
//
// public List<Credentials> getCredentialList(String provider) {
//
// List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
//
// for (Credentials credentials : credentialsList) {
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
// }
//
// return credentialsList;
// }
//
// public Credentials getCredentials(String provider) {
// return getCredentials(sessionUserService.getUser(), provider);
// }
//
// public Credentials getCredentials(User user, String provider) {
//
// if (user != null && user.getGroups() != null) {
//
// for (String group : user.getGroups()) {
//
// Credentials credentials = credentialsDao.findByGroupAndProvider(group, provider);
//
// if (credentials != null) {
//
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
//
// return credentials;
// }
// }
// }
//
// return null;
// }
//
// public Credentials create(String group, String provider, Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = encryptSecretMap(secretMap);
// Credentials credentials = new Credentials(group, provider, encryptedSecretMap);
//
// return credentialsDao.save(credentials);
// }
//
// public void delete(String id) {
// credentialsDao.delete(id);
// }
//
// private Map<String, String> encryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// encryptedSecretMap.put(key, encryptionService.encrypt(value));
// }
// }
//
// return encryptedSecretMap;
// }
//
// private Map<String, String> decryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> decryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// decryptedSecretMap.put(key, encryptionService.decrypt(value));
// }
// }
//
// return decryptedSecretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
| import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import de.papke.cloud.portal.model.CredentialsModel;
import de.papke.cloud.portal.service.CredentialsService;
import de.papke.cloud.portal.service.SessionUserService; | package de.papke.cloud.portal.controller;
@Controller
public class CredentialsController extends ApplicationController {
private static final String PREFIX = "/credentials";
private static final String MODEL_VAR_NAME = "credentials";
private static final String LIST_PATH_PREFIX = PREFIX + "/list/form";
private static final String LIST_VIEW_PREFIX = "credentials-list-form-";
private static final String ATTRIBUTE_GROUP = "group";
@Autowired | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/CredentialsModel.java
// public class CredentialsModel {
//
// private List<Credentials> credentialsList;
//
// public List<Credentials> getCredentialsList() {
// return credentialsList;
// }
//
// public void setCredentialsList(List<Credentials> credentialsList) {
// this.credentialsList = credentialsList;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
// @Service
// public class CredentialsService {
//
// @Autowired
// private EncryptionService encryptionService;
//
// @Autowired
// private SessionUserService sessionUserService;
//
// @Autowired
// private CredentialsDao credentialsDao;
//
// public List<Credentials> getCredentialList(String provider) {
//
// List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
//
// for (Credentials credentials : credentialsList) {
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
// }
//
// return credentialsList;
// }
//
// public Credentials getCredentials(String provider) {
// return getCredentials(sessionUserService.getUser(), provider);
// }
//
// public Credentials getCredentials(User user, String provider) {
//
// if (user != null && user.getGroups() != null) {
//
// for (String group : user.getGroups()) {
//
// Credentials credentials = credentialsDao.findByGroupAndProvider(group, provider);
//
// if (credentials != null) {
//
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
//
// return credentials;
// }
// }
// }
//
// return null;
// }
//
// public Credentials create(String group, String provider, Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = encryptSecretMap(secretMap);
// Credentials credentials = new Credentials(group, provider, encryptedSecretMap);
//
// return credentialsDao.save(credentials);
// }
//
// public void delete(String id) {
// credentialsDao.delete(id);
// }
//
// private Map<String, String> encryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// encryptedSecretMap.put(key, encryptionService.encrypt(value));
// }
// }
//
// return encryptedSecretMap;
// }
//
// private Map<String, String> decryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> decryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// decryptedSecretMap.put(key, encryptionService.decrypt(value));
// }
// }
//
// return decryptedSecretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/controller/CredentialsController.java
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import de.papke.cloud.portal.model.CredentialsModel;
import de.papke.cloud.portal.service.CredentialsService;
import de.papke.cloud.portal.service.SessionUserService;
package de.papke.cloud.portal.controller;
@Controller
public class CredentialsController extends ApplicationController {
private static final String PREFIX = "/credentials";
private static final String MODEL_VAR_NAME = "credentials";
private static final String LIST_PATH_PREFIX = PREFIX + "/list/form";
private static final String LIST_VIEW_PREFIX = "credentials-list-form-";
private static final String ATTRIBUTE_GROUP = "group";
@Autowired | private CredentialsService credentialsService; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/controller/CredentialsController.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/CredentialsModel.java
// public class CredentialsModel {
//
// private List<Credentials> credentialsList;
//
// public List<Credentials> getCredentialsList() {
// return credentialsList;
// }
//
// public void setCredentialsList(List<Credentials> credentialsList) {
// this.credentialsList = credentialsList;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
// @Service
// public class CredentialsService {
//
// @Autowired
// private EncryptionService encryptionService;
//
// @Autowired
// private SessionUserService sessionUserService;
//
// @Autowired
// private CredentialsDao credentialsDao;
//
// public List<Credentials> getCredentialList(String provider) {
//
// List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
//
// for (Credentials credentials : credentialsList) {
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
// }
//
// return credentialsList;
// }
//
// public Credentials getCredentials(String provider) {
// return getCredentials(sessionUserService.getUser(), provider);
// }
//
// public Credentials getCredentials(User user, String provider) {
//
// if (user != null && user.getGroups() != null) {
//
// for (String group : user.getGroups()) {
//
// Credentials credentials = credentialsDao.findByGroupAndProvider(group, provider);
//
// if (credentials != null) {
//
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
//
// return credentials;
// }
// }
// }
//
// return null;
// }
//
// public Credentials create(String group, String provider, Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = encryptSecretMap(secretMap);
// Credentials credentials = new Credentials(group, provider, encryptedSecretMap);
//
// return credentialsDao.save(credentials);
// }
//
// public void delete(String id) {
// credentialsDao.delete(id);
// }
//
// private Map<String, String> encryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// encryptedSecretMap.put(key, encryptionService.encrypt(value));
// }
// }
//
// return encryptedSecretMap;
// }
//
// private Map<String, String> decryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> decryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// decryptedSecretMap.put(key, encryptionService.decrypt(value));
// }
// }
//
// return decryptedSecretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
| import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import de.papke.cloud.portal.model.CredentialsModel;
import de.papke.cloud.portal.service.CredentialsService;
import de.papke.cloud.portal.service.SessionUserService; | package de.papke.cloud.portal.controller;
@Controller
public class CredentialsController extends ApplicationController {
private static final String PREFIX = "/credentials";
private static final String MODEL_VAR_NAME = "credentials";
private static final String LIST_PATH_PREFIX = PREFIX + "/list/form";
private static final String LIST_VIEW_PREFIX = "credentials-list-form-";
private static final String ATTRIBUTE_GROUP = "group";
@Autowired
private CredentialsService credentialsService;
@Autowired | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/CredentialsModel.java
// public class CredentialsModel {
//
// private List<Credentials> credentialsList;
//
// public List<Credentials> getCredentialsList() {
// return credentialsList;
// }
//
// public void setCredentialsList(List<Credentials> credentialsList) {
// this.credentialsList = credentialsList;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/CredentialsService.java
// @Service
// public class CredentialsService {
//
// @Autowired
// private EncryptionService encryptionService;
//
// @Autowired
// private SessionUserService sessionUserService;
//
// @Autowired
// private CredentialsDao credentialsDao;
//
// public List<Credentials> getCredentialList(String provider) {
//
// List<Credentials> credentialsList = credentialsDao.findByProvider(provider);
//
// for (Credentials credentials : credentialsList) {
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
// }
//
// return credentialsList;
// }
//
// public Credentials getCredentials(String provider) {
// return getCredentials(sessionUserService.getUser(), provider);
// }
//
// public Credentials getCredentials(User user, String provider) {
//
// if (user != null && user.getGroups() != null) {
//
// for (String group : user.getGroups()) {
//
// Credentials credentials = credentialsDao.findByGroupAndProvider(group, provider);
//
// if (credentials != null) {
//
// Map<String, String> secretMap = credentials.getSecretMap();
// Map<String, String> decryptedSecretMap = decryptSecretMap(secretMap);
// credentials.setSecretMap(decryptedSecretMap);
//
// return credentials;
// }
// }
// }
//
// return null;
// }
//
// public Credentials create(String group, String provider, Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = encryptSecretMap(secretMap);
// Credentials credentials = new Credentials(group, provider, encryptedSecretMap);
//
// return credentialsDao.save(credentials);
// }
//
// public void delete(String id) {
// credentialsDao.delete(id);
// }
//
// private Map<String, String> encryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> encryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// encryptedSecretMap.put(key, encryptionService.encrypt(value));
// }
// }
//
// return encryptedSecretMap;
// }
//
// private Map<String, String> decryptSecretMap(Map<String, String> secretMap) {
//
// Map<String, String> decryptedSecretMap = new HashMap<>();
//
// if (secretMap != null) {
// for (Entry<String, String> entry : secretMap.entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// decryptedSecretMap.put(key, encryptionService.decrypt(value));
// }
// }
//
// return decryptedSecretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/SessionUserService.java
// @Service
// public class SessionUserService {
//
// private static final String SESSION_ATTRIBUTE_USER = "user";
// private static final User DUMMY_USER = new User("anonymous", "Anonymous", "User", "dummy@dummy.com", new ArrayList<>(), false);
//
// @Autowired
// private HttpSession session;
//
// public User getUser() {
//
// User user = (User) session.getAttribute(SESSION_ATTRIBUTE_USER);
//
// if (user == null) {
// user = DUMMY_USER;
// }
//
// return user;
// }
//
// public boolean isAdmin() {
// return getUser().isAdmin();
// }
//
// public boolean isAllowed() {
// return isAdmin();
// }
//
// public boolean isAllowed(ProvisionLog provisionLog) {
// return isAdmin() || getUser().getGroups().contains(provisionLog.getGroup());
// }
//
// public void setUser(User user) {
// session.setAttribute(SESSION_ATTRIBUTE_USER, user);
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/controller/CredentialsController.java
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import de.papke.cloud.portal.model.CredentialsModel;
import de.papke.cloud.portal.service.CredentialsService;
import de.papke.cloud.portal.service.SessionUserService;
package de.papke.cloud.portal.controller;
@Controller
public class CredentialsController extends ApplicationController {
private static final String PREFIX = "/credentials";
private static final String MODEL_VAR_NAME = "credentials";
private static final String LIST_PATH_PREFIX = PREFIX + "/list/form";
private static final String LIST_VIEW_PREFIX = "credentials-list-form-";
private static final String ATTRIBUTE_GROUP = "group";
@Autowired
private CredentialsService credentialsService;
@Autowired | private SessionUserService sessionUserService; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/ApplicationModel.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.List;
import de.papke.cloud.portal.pojo.Menu;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.model;
public class ApplicationModel {
private String applicationTitle; | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/ApplicationModel.java
import java.util.List;
import de.papke.cloud.portal.pojo.Menu;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.model;
public class ApplicationModel {
private String applicationTitle; | private User user; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/ApplicationModel.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
| import java.util.List;
import de.papke.cloud.portal.pojo.Menu;
import de.papke.cloud.portal.pojo.User; | package de.papke.cloud.portal.model;
public class ApplicationModel {
private String applicationTitle;
private User user;
private List<String> cloudProviderList; | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Menu.java
// public class Menu {
//
// private String title;
// private String path;
// private String icon;
// private boolean secure;
// private List<Menu> menus;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getPath() {
// return path;
// }
// public void setPath(String path) {
// this.path = path;
// }
// public String getIcon() {
// return icon;
// }
// public void setIcon(String icon) {
// this.icon = icon;
// }
// public boolean isSecure() {
// return secure;
// }
// public void setSecure(boolean secure) {
// this.secure = secure;
// }
// public List<Menu> getMenus() {
// return menus;
// }
// public void setMenus(List<Menu> menus) {
// this.menus = menus;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String username;
// private String givenName;
// private String surName;
// private String email;
// private List<String> groups;
// private boolean admin;
//
// public User() {}
//
// public User(String username, String givenName, String surName, String email, List<String> groups, boolean admin) {
// super();
// this.givenName = givenName;
// this.surName = surName;
// this.username = username;
// this.email = email;
// this.groups = groups;
// this.admin = admin;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getGivenName() {
// return givenName;
// }
//
// public void setGivenName(String givenName) {
// this.givenName = givenName;
// }
//
// public String getSurName() {
// return surName;
// }
//
// public void setSurName(String surName) {
// this.surName = surName;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getGroups() {
// return groups;
// }
//
// public void setGroups(List<String> groups) {
// this.groups = groups;
// }
//
// public boolean isAdmin() {
// return admin;
// }
//
// public void setAdmin(boolean admin) {
// this.admin = admin;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/model/ApplicationModel.java
import java.util.List;
import de.papke.cloud.portal.pojo.Menu;
import de.papke.cloud.portal.pojo.User;
package de.papke.cloud.portal.model;
public class ApplicationModel {
private String applicationTitle;
private User user;
private List<String> cloudProviderList; | private Menu menu; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase; | package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern(); | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase;
package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern(); | protected abstract void prepare(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase; | package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern(); | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase;
package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern(); | protected abstract void prepare(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException; |
chrisipa/cloud-portal | modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java | // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase; | package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern();
protected abstract void prepare(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException;
protected abstract void cleanup(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException;
@Autowired
private CommandExecutorService commandExecutorService;
| // Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/CommandResult.java
// public class CommandResult {
//
// private String output;
// private boolean success;
//
// public CommandResult() {}
//
// public CommandResult(String output, boolean success) {
// this.output = output;
// this.success = success;
// }
//
// public String getOutput() {
// return output;
// }
// public void setOutput(String output) {
// this.output = output;
// }
// public boolean isSuccess() {
// return success;
// }
// public void setSuccess(boolean success) {
// this.success = success;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/Credentials.java
// public class Credentials {
//
// @Id
// private String id;
// private String group;
// private String provider;
// private Map<String, String> secretMap = new HashMap<>();
//
// public Credentials() {}
//
// public Credentials(String group, String provider, Map<String, String> secretMap) {
// this.group = group;
// this.provider = provider;
// this.secretMap = secretMap;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getGroup() {
// return group;
// }
//
// public void setGroup(String group) {
// this.group = group;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public Map<String, String> getSecretMap() {
// return secretMap;
// }
//
// public void setSecretMap(Map<String, String> secretMap) {
// this.secretMap = secretMap;
// }
// }
//
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/pojo/UseCase.java
// public class UseCase {
//
// private String id;
// private String name;
// private String provider;
// private String provisioner;
// private List<VariableGroup> variableGroups;
// private String resourceFolderPath;
//
// @Override
// public String toString() {
// return "id=" + id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getProvider() {
// return provider;
// }
//
// public void setProvider(String provider) {
// this.provider = provider;
// }
//
// public String getProvisioner() {
// return provisioner;
// }
//
// public void setProvisioner(String provisioner) {
// this.provisioner = provisioner;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public List<VariableGroup> getVariableGroups() {
// return variableGroups;
// }
//
// public void setVariableGroups(List<VariableGroup> variableGroups) {
// this.variableGroups = variableGroups;
// }
//
// public String getResourceFolderPath() {
// return resourceFolderPath;
// }
//
// public void setResourceFolderPath(String resourceFolderPath) {
// this.resourceFolderPath = resourceFolderPath;
// }
// }
// Path: modules/cloud-portal-server/src/main/java/de/papke/cloud/portal/service/ProvisionerService.java
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import de.papke.cloud.portal.pojo.CommandResult;
import de.papke.cloud.portal.pojo.Credentials;
import de.papke.cloud.portal.pojo.UseCase;
package de.papke.cloud.portal.service;
@Service
public abstract class ProvisionerService {
private static final Logger LOG = LoggerFactory.getLogger(ProvisionerService.class);
private static final String INTRODUCTION_SUFFIX = " IS WORKING ON YOUR ACTION. PLEASE BE PATIENT!!!\n\n";
protected abstract String getPrefix();
protected abstract String getBinaryPath();
protected abstract CommandLine buildActionCommand(String ansiblePath, String action, Map<String, Object> variableMap);
protected abstract Pattern getParsingPattern();
protected abstract void prepare(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException;
protected abstract void cleanup(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) throws IOException;
@Autowired
private CommandExecutorService commandExecutorService;
| public CommandResult execute(UseCase useCase, String action, Credentials credentials, Map<String, Object> variableMap, OutputStream outputStream, File tmpFolder) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.