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
threerings/jiggl
core/src/main/java/com/threerings/jiggl/tween/Tweener.java
// Path: core/src/main/java/com/threerings/jiggl/util/Driver.java // public abstract class Driver // { // /** An interface implemented by things that wish to tick. */ // public interface Tickable { // /** Called on every frame tick with the time elapsed since app start, in seconds. // * @return true if the tickable should remain registered, false otherwise. */ // boolean tick (float time); // } // // /** // * Registers a new tickable with the driver. The tickable may only be removed by returning // * false from its {@link Tickable#tick} method. // */ // public void addTickable (Tickable tickable) // { // _tickables.add(tickable); // } // // /** // * Ticks all registered tickables, then re-renders the view. // */ // protected void tick (float time) // { // for (int ii = 0, ll = _tickables.size(); ii < ll; ii++) { // if (!_tickables.get(ii).tick(time)) { // _tickables.remove(ii--); // ll -= 1; // } // } // _view.render(); // } // // protected Driver (View view) // { // _view = view; // } // // protected final View _view; // protected final List<Tickable> _tickables = new ArrayList<Tickable>(); // } // // Path: core/src/main/java/com/threerings/jiggl/util/Scalar.java // public class Scalar // { // /** The current value of this scalar. */ // public float value; // // /** // * Creates a scalar with the specified initial value. // */ // public Scalar (float init) // { // this.value = init; // } // } // // Path: core/src/main/java/com/threerings/jiggl/view/Viz.java // public abstract class Viz // { // /** The x-component of our (container relative) translation. */ // public final Scalar x = new Scalar(0); // // /** The y-component of our (container relative) translation. */ // public final Scalar y = new Scalar(0); // // /** The x-component of our scale. */ // public final Scalar scaleX = new Scalar(1); // // /** The y-component of our scale. */ // public final Scalar scaleY = new Scalar(1); // // /** The rotation of this visible, in radians. */ // public final Scalar rotation = new Scalar(0); // // /** // * Returns the width of this visible, including local scaling transformations (but not // * rotation). Transformations applied by a parent of this visible are also not included. // */ // public abstract float getWidth (); // // /** // * Returns the height of this visible, including local scaling transformations (but not // * rotation). Transformations applied by a parent of this visible are also not included. // */ // public abstract float getHeight (); // // /** // * Returns true if this viz is added to a view, false otherwise. // */ // public abstract boolean isAdded (); // // /** // * Called when this viz is added to a view. The viz should prepare any buffers or shader // * programs it will need to render itself. Any exception thrown by this method will result in // * the viz not being added to the view, so the viz should ensure that partially created // * resources are cleaned up if it throws such an exception. // */ // protected abstract void onAdd (View view); // // /** // * Called when this viz is removed from a view. The viz should destroy any buffers or shader // * programs it created in {@link #onAdd}. // */ // protected abstract void onRemove (); // // /** // * Instructs this viz to issue the rendering calls needed to visualize itself. // */ // protected abstract void render (); // }
import java.util.ArrayList; import java.util.List; import com.threerings.jiggl.util.Driver; import com.threerings.jiggl.util.Scalar; import com.threerings.jiggl.view.Viz;
/** * Creates a tween that delays for the specified number of seconds. */ public Tween.Delay delay (float seconds) { return register(new Tween.Delay(seconds)); } /** * Returns a tweener which can be used to construct a tween that will be repeated until the * supplied viz has been removed from its view. The viz must be added to the view in question * before the next frame tick, or the cancellation will trigger immediately. */ public Tweener repeat (Viz viz) { return register(new Tween.Repeat(viz)).then(); } /** * Creates a tween that executes the supplied runnable and immediately completes. */ public Tween.Action action (Runnable action) { return register(new Tween.Action(action)); } protected abstract <T extends Tween> T register (T tween); /** Implementation details, avert your eyes. */
// Path: core/src/main/java/com/threerings/jiggl/util/Driver.java // public abstract class Driver // { // /** An interface implemented by things that wish to tick. */ // public interface Tickable { // /** Called on every frame tick with the time elapsed since app start, in seconds. // * @return true if the tickable should remain registered, false otherwise. */ // boolean tick (float time); // } // // /** // * Registers a new tickable with the driver. The tickable may only be removed by returning // * false from its {@link Tickable#tick} method. // */ // public void addTickable (Tickable tickable) // { // _tickables.add(tickable); // } // // /** // * Ticks all registered tickables, then re-renders the view. // */ // protected void tick (float time) // { // for (int ii = 0, ll = _tickables.size(); ii < ll; ii++) { // if (!_tickables.get(ii).tick(time)) { // _tickables.remove(ii--); // ll -= 1; // } // } // _view.render(); // } // // protected Driver (View view) // { // _view = view; // } // // protected final View _view; // protected final List<Tickable> _tickables = new ArrayList<Tickable>(); // } // // Path: core/src/main/java/com/threerings/jiggl/util/Scalar.java // public class Scalar // { // /** The current value of this scalar. */ // public float value; // // /** // * Creates a scalar with the specified initial value. // */ // public Scalar (float init) // { // this.value = init; // } // } // // Path: core/src/main/java/com/threerings/jiggl/view/Viz.java // public abstract class Viz // { // /** The x-component of our (container relative) translation. */ // public final Scalar x = new Scalar(0); // // /** The y-component of our (container relative) translation. */ // public final Scalar y = new Scalar(0); // // /** The x-component of our scale. */ // public final Scalar scaleX = new Scalar(1); // // /** The y-component of our scale. */ // public final Scalar scaleY = new Scalar(1); // // /** The rotation of this visible, in radians. */ // public final Scalar rotation = new Scalar(0); // // /** // * Returns the width of this visible, including local scaling transformations (but not // * rotation). Transformations applied by a parent of this visible are also not included. // */ // public abstract float getWidth (); // // /** // * Returns the height of this visible, including local scaling transformations (but not // * rotation). Transformations applied by a parent of this visible are also not included. // */ // public abstract float getHeight (); // // /** // * Returns true if this viz is added to a view, false otherwise. // */ // public abstract boolean isAdded (); // // /** // * Called when this viz is added to a view. The viz should prepare any buffers or shader // * programs it will need to render itself. Any exception thrown by this method will result in // * the viz not being added to the view, so the viz should ensure that partially created // * resources are cleaned up if it throws such an exception. // */ // protected abstract void onAdd (View view); // // /** // * Called when this viz is removed from a view. The viz should destroy any buffers or shader // * programs it created in {@link #onAdd}. // */ // protected abstract void onRemove (); // // /** // * Instructs this viz to issue the rendering calls needed to visualize itself. // */ // protected abstract void render (); // } // Path: core/src/main/java/com/threerings/jiggl/tween/Tweener.java import java.util.ArrayList; import java.util.List; import com.threerings.jiggl.util.Driver; import com.threerings.jiggl.util.Scalar; import com.threerings.jiggl.view.Viz; /** * Creates a tween that delays for the specified number of seconds. */ public Tween.Delay delay (float seconds) { return register(new Tween.Delay(seconds)); } /** * Returns a tweener which can be used to construct a tween that will be repeated until the * supplied viz has been removed from its view. The viz must be added to the view in question * before the next frame tick, or the cancellation will trigger immediately. */ public Tweener repeat (Viz viz) { return register(new Tween.Repeat(viz)).then(); } /** * Creates a tween that executes the supplied runnable and immediately completes. */ public Tween.Action action (Runnable action) { return register(new Tween.Action(action)); } protected abstract <T extends Tween> T register (T tween); /** Implementation details, avert your eyes. */
public static class Impl extends Tweener implements Driver.Tickable {
paritytrading/philadelphia
libraries/core/src/main/java/com/paritytrading/philadelphia/FIXMessage.java
// Path: libraries/core/src/main/java/com/paritytrading/philadelphia/FIXTags.java // class FIXTags { // // static final int BeginSeqNo = 7; // static final int BeginString = 8; // static final int BodyLength = 9; // static final int CheckSum = 10; // static final int EndSeqNo = 16; // static final int MsgSeqNum = 34; // static final int MsgType = 35; // static final int NewSeqNo = 36; // static final int PossDupFlag = 43; // static final int RefSeqNum = 45; // static final int SenderCompID = 49; // static final int SendingTime = 52; // static final int TargetCompID = 56; // static final int Text = 58; // static final int TransactTime = 60; // static final int EncryptMethod = 98; // static final int HeartBtInt = 108; // static final int TestReqID = 112; // static final int GapFillFlag = 123; // static final int ResetSeqNumFlag = 141; // static final int SessionRejectReason = 373; // // static int get(ByteBuffer buffer) { // int tag = 0; // // while (buffer.hasRemaining()) { // byte b = buffer.get(); // // if (b == EQUALS) // return tag; // // tag = 10 * tag + b - '0'; // } // // return 0; // } // // static void put(ByteBuffer buffer, int tag) { // if (tag < 1 || tag > 99999) // tooLargeTag(); // // byte b1 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b2 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b3 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b4 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b5 = (byte)('0' + tag % 10); // // buffer.put(b5); // } // // buffer.put(b4); // } // // buffer.put(b3); // } // // buffer.put(b2); // } // // buffer.put(b1); // buffer.put(EQUALS); // } // // private static void tooLargeTag() { // throw new IllegalArgumentException("Too large tag"); // } // // }
import static com.paritytrading.philadelphia.FIXTags.*; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.ReadOnlyBufferException; import java.util.stream.Stream;
return values[count++]; } /** * Reset this message container. */ public void reset() { count = 0; } /** * Read this message from a buffer. * * @param buffer a buffer * @return true if this message was successfully read from the buffer, * otherwise false * @throws FIXMessageOverflowException if the number of fields exceeds the * maximum number of fields * @throws FIXValueOverflowException if the length of a value exceeds the * capacity of the value container */ public boolean get(ByteBuffer buffer) throws FIXMessageOverflowException, FIXValueOverflowException { reset(); while (buffer.hasRemaining()) { if (count == tags.length) tooManyFields();
// Path: libraries/core/src/main/java/com/paritytrading/philadelphia/FIXTags.java // class FIXTags { // // static final int BeginSeqNo = 7; // static final int BeginString = 8; // static final int BodyLength = 9; // static final int CheckSum = 10; // static final int EndSeqNo = 16; // static final int MsgSeqNum = 34; // static final int MsgType = 35; // static final int NewSeqNo = 36; // static final int PossDupFlag = 43; // static final int RefSeqNum = 45; // static final int SenderCompID = 49; // static final int SendingTime = 52; // static final int TargetCompID = 56; // static final int Text = 58; // static final int TransactTime = 60; // static final int EncryptMethod = 98; // static final int HeartBtInt = 108; // static final int TestReqID = 112; // static final int GapFillFlag = 123; // static final int ResetSeqNumFlag = 141; // static final int SessionRejectReason = 373; // // static int get(ByteBuffer buffer) { // int tag = 0; // // while (buffer.hasRemaining()) { // byte b = buffer.get(); // // if (b == EQUALS) // return tag; // // tag = 10 * tag + b - '0'; // } // // return 0; // } // // static void put(ByteBuffer buffer, int tag) { // if (tag < 1 || tag > 99999) // tooLargeTag(); // // byte b1 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b2 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b3 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b4 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b5 = (byte)('0' + tag % 10); // // buffer.put(b5); // } // // buffer.put(b4); // } // // buffer.put(b3); // } // // buffer.put(b2); // } // // buffer.put(b1); // buffer.put(EQUALS); // } // // private static void tooLargeTag() { // throw new IllegalArgumentException("Too large tag"); // } // // } // Path: libraries/core/src/main/java/com/paritytrading/philadelphia/FIXMessage.java import static com.paritytrading.philadelphia.FIXTags.*; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.ReadOnlyBufferException; import java.util.stream.Stream; return values[count++]; } /** * Reset this message container. */ public void reset() { count = 0; } /** * Read this message from a buffer. * * @param buffer a buffer * @return true if this message was successfully read from the buffer, * otherwise false * @throws FIXMessageOverflowException if the number of fields exceeds the * maximum number of fields * @throws FIXValueOverflowException if the length of a value exceeds the * capacity of the value container */ public boolean get(ByteBuffer buffer) throws FIXMessageOverflowException, FIXValueOverflowException { reset(); while (buffer.hasRemaining()) { if (count == tags.length) tooManyFields();
int tag = FIXTags.get(buffer);
paritytrading/philadelphia
libraries/core/src/test/java/com/paritytrading/philadelphia/TestMessageParser.java
// Path: libraries/core/src/main/java/com/paritytrading/philadelphia/FIXTags.java // class FIXTags { // // static final int BeginSeqNo = 7; // static final int BeginString = 8; // static final int BodyLength = 9; // static final int CheckSum = 10; // static final int EndSeqNo = 16; // static final int MsgSeqNum = 34; // static final int MsgType = 35; // static final int NewSeqNo = 36; // static final int PossDupFlag = 43; // static final int RefSeqNum = 45; // static final int SenderCompID = 49; // static final int SendingTime = 52; // static final int TargetCompID = 56; // static final int Text = 58; // static final int TransactTime = 60; // static final int EncryptMethod = 98; // static final int HeartBtInt = 108; // static final int TestReqID = 112; // static final int GapFillFlag = 123; // static final int ResetSeqNumFlag = 141; // static final int SessionRejectReason = 373; // // static int get(ByteBuffer buffer) { // int tag = 0; // // while (buffer.hasRemaining()) { // byte b = buffer.get(); // // if (b == EQUALS) // return tag; // // tag = 10 * tag + b - '0'; // } // // return 0; // } // // static void put(ByteBuffer buffer, int tag) { // if (tag < 1 || tag > 99999) // tooLargeTag(); // // byte b1 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b2 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b3 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b4 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b5 = (byte)('0' + tag % 10); // // buffer.put(b5); // } // // buffer.put(b4); // } // // buffer.put(b3); // } // // buffer.put(b2); // } // // buffer.put(b1); // buffer.put(EQUALS); // } // // private static void tooLargeTag() { // throw new IllegalArgumentException("Too large tag"); // } // // }
import static com.paritytrading.philadelphia.FIXTags.*; import java.io.IOException; import java.nio.ByteBuffer;
/* * Copyright 2015 Philadelphia authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paritytrading.philadelphia; class TestMessageParser { private TestMessageListener listener; private StringBuilder message; private FIXValue value; TestMessageParser(TestMessageListener listener) { this.listener = listener; this.message = new StringBuilder(); this.value = new FIXValue(32); } boolean parse(ByteBuffer buffer) throws IOException { buffer.mark(); message.setLength(0); while (true) {
// Path: libraries/core/src/main/java/com/paritytrading/philadelphia/FIXTags.java // class FIXTags { // // static final int BeginSeqNo = 7; // static final int BeginString = 8; // static final int BodyLength = 9; // static final int CheckSum = 10; // static final int EndSeqNo = 16; // static final int MsgSeqNum = 34; // static final int MsgType = 35; // static final int NewSeqNo = 36; // static final int PossDupFlag = 43; // static final int RefSeqNum = 45; // static final int SenderCompID = 49; // static final int SendingTime = 52; // static final int TargetCompID = 56; // static final int Text = 58; // static final int TransactTime = 60; // static final int EncryptMethod = 98; // static final int HeartBtInt = 108; // static final int TestReqID = 112; // static final int GapFillFlag = 123; // static final int ResetSeqNumFlag = 141; // static final int SessionRejectReason = 373; // // static int get(ByteBuffer buffer) { // int tag = 0; // // while (buffer.hasRemaining()) { // byte b = buffer.get(); // // if (b == EQUALS) // return tag; // // tag = 10 * tag + b - '0'; // } // // return 0; // } // // static void put(ByteBuffer buffer, int tag) { // if (tag < 1 || tag > 99999) // tooLargeTag(); // // byte b1 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b2 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b3 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b4 = (byte)('0' + tag % 10); // // tag /= 10; // // if (tag != 0) { // byte b5 = (byte)('0' + tag % 10); // // buffer.put(b5); // } // // buffer.put(b4); // } // // buffer.put(b3); // } // // buffer.put(b2); // } // // buffer.put(b1); // buffer.put(EQUALS); // } // // private static void tooLargeTag() { // throw new IllegalArgumentException("Too large tag"); // } // // } // Path: libraries/core/src/test/java/com/paritytrading/philadelphia/TestMessageParser.java import static com.paritytrading.philadelphia.FIXTags.*; import java.io.IOException; import java.nio.ByteBuffer; /* * Copyright 2015 Philadelphia authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paritytrading.philadelphia; class TestMessageParser { private TestMessageListener listener; private StringBuilder message; private FIXValue value; TestMessageParser(TestMessageListener listener) { this.listener = listener; this.message = new StringBuilder(); this.value = new FIXValue(32); } boolean parse(ByteBuffer buffer) throws IOException { buffer.mark(); message.setLength(0); while (true) {
int tag = FIXTags.get(buffer);
chedim/minedriod
src/main/java/com/onkiup/minedroid/exprop/ExPropSync.java
// Path: src/main/java/com/onkiup/minedroid/MineDroid.java // @Mod( // modid = MineDroid.MODID, // version = MineDroid.VERSION, // guiFactory = "com.onkiup.minedroid.config.GuiFactory" // ) // public class MineDroid extends Modification { // public static final String MODID = "minedroid"; // public static final String VERSION = "1.3.2"; // // protected static MineDroid INSTANCE; // // // public MineDroid() { // super(R.class); // } // // public void init() { // INSTANCE = this; // } // // @Override // public void initNetwork() { // super.initNetwork(); // registerPacket(EnvInfoPacket.class); // registerPacket(ClientAlertPacket.class); // registerPacket(ExPropDeltaPacket.class); // registerPacket(ExPropDeltaRequestPacket.class); // } // // public static Class getMineDroidR() { // return R.class; // } // // public static Context getMDContext() { // return new ContextImpl(INSTANCE.contextId()); // } // // @Override // public void initServer() { // ExPropServerSync sync = new ExPropServerSync(); // tickHandler.repeat(1, sync); // } // // @Override // public void initClient() { // tickHandler.repeat(30, new ExPropClientSync()); // } // // @Mod.EventHandler // @SideOnly(Side.CLIENT) // public void onClientInitializing(FMLInitializationEvent event) { // isClient = true; // Modification.initModules(); // Modification.initClients(); // clientThread = Thread.currentThread(); // } // // @Mod.EventHandler // @SideOnly(Side.SERVER) // public void onServerInitializing(FMLInitializationEvent event) { // Modification.initModules(); // } // // @Mod.EventHandler // public void onServerStart(FMLServerStartedEvent event) { // serverThread = Thread.currentThread(); // isServer = true; // } // // @Mod.EventHandler // public void onServerStopped(FMLServerStoppedEvent event) { // isServer = false; // } // // @Mod.EventHandler // public void onServerStopping(FMLServerStoppingEvent event) { // Modification.stopServers(); // } // // @Mod.EventHandler // public void onServerStarting(FMLServerAboutToStartEvent event) { // initServers(); // } // // public static MineDroid getInstance() { // return INSTANCE; // } // // // }
import com.onkiup.minedroid.MineDroid;
package com.onkiup.minedroid.exprop; /** * Created by chedim on 8/13/15. */ public class ExPropSync { protected static boolean isStarted = false; public static void start() { if (isStarted) return;
// Path: src/main/java/com/onkiup/minedroid/MineDroid.java // @Mod( // modid = MineDroid.MODID, // version = MineDroid.VERSION, // guiFactory = "com.onkiup.minedroid.config.GuiFactory" // ) // public class MineDroid extends Modification { // public static final String MODID = "minedroid"; // public static final String VERSION = "1.3.2"; // // protected static MineDroid INSTANCE; // // // public MineDroid() { // super(R.class); // } // // public void init() { // INSTANCE = this; // } // // @Override // public void initNetwork() { // super.initNetwork(); // registerPacket(EnvInfoPacket.class); // registerPacket(ClientAlertPacket.class); // registerPacket(ExPropDeltaPacket.class); // registerPacket(ExPropDeltaRequestPacket.class); // } // // public static Class getMineDroidR() { // return R.class; // } // // public static Context getMDContext() { // return new ContextImpl(INSTANCE.contextId()); // } // // @Override // public void initServer() { // ExPropServerSync sync = new ExPropServerSync(); // tickHandler.repeat(1, sync); // } // // @Override // public void initClient() { // tickHandler.repeat(30, new ExPropClientSync()); // } // // @Mod.EventHandler // @SideOnly(Side.CLIENT) // public void onClientInitializing(FMLInitializationEvent event) { // isClient = true; // Modification.initModules(); // Modification.initClients(); // clientThread = Thread.currentThread(); // } // // @Mod.EventHandler // @SideOnly(Side.SERVER) // public void onServerInitializing(FMLInitializationEvent event) { // Modification.initModules(); // } // // @Mod.EventHandler // public void onServerStart(FMLServerStartedEvent event) { // serverThread = Thread.currentThread(); // isServer = true; // } // // @Mod.EventHandler // public void onServerStopped(FMLServerStoppedEvent event) { // isServer = false; // } // // @Mod.EventHandler // public void onServerStopping(FMLServerStoppingEvent event) { // Modification.stopServers(); // } // // @Mod.EventHandler // public void onServerStarting(FMLServerAboutToStartEvent event) { // initServers(); // } // // public static MineDroid getInstance() { // return INSTANCE; // } // // // } // Path: src/main/java/com/onkiup/minedroid/exprop/ExPropSync.java import com.onkiup.minedroid.MineDroid; package com.onkiup.minedroid.exprop; /** * Created by chedim on 8/13/15. */ public class ExPropSync { protected static boolean isStarted = false; public static void start() { if (isStarted) return;
MineDroid.getInstance().getTickHandler().repeat(10, new ExPropClientSync());
chedim/minedriod
src/main/java/com/onkiup/minedroid/net/ClientAlertPacket.java
// Path: src/main/java/com/onkiup/minedroid/gui/overlay/Alert.java // @SideOnly(Side.CLIENT) // public class Alert extends Notification { // protected TextView mMessage; // protected Button mOkButton; // protected RelativeLayout layout = new RelativeLayout(this); // protected String text; // protected View.OnKeyDown keyListener = new View.OnKeyDown() { // @Override // public void handle(KeyEvent event) { // if (event.keyCode == Keyboard.KEY_Y) { // dismiss(); // } // FMLLog.info("Key pressed: %s", event.keyChar); // } // }; // // protected View.OnClick clickListener = new View.OnClick() { // @Override // public void handle(MouseEvent event) { // dismiss(); // } // }; // // protected Alert(Context context, String text) { // super(context); // this.text = text; // } // // @Override // protected ResourceLocation getContentLayout() { // return R.layout.alert; // } // // @Override // public boolean isModal() { // return true; // } // // @Override // protected void fill(View content) { // mMessage = (TextView) findViewById(R.id.message); // mMessage.setText(text); // content.on(clickListener); // content.on(keyListener); // } // // @Override // protected void onStart() { // // } // // @Override // protected void onStop() { // // } // // public static Alert show(String format, Object... params) { // String message = String.format(format, params); // Alert alert = new Alert(MineDroid.getMDContext(), message); // NotificationManager.open(alert); // return alert; // } // // @Override // public int getTimeLeft() { // return -1; // } // }
import com.onkiup.minedroid.gui.overlay.Alert; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.onkiup.minedroid.net; /** * Created by chedim on 8/11/15. */ public class ClientAlertPacket extends APacket { public ClientAlertPacket() { } public String message; public ClientAlertPacket(String message) { this.message = message; } public static class CHandler extends ClientHandler<ClientAlertPacket> { @Override @SideOnly(Side.CLIENT) public APacket handle(ClientAlertPacket packet, MessageContext messageContext) {
// Path: src/main/java/com/onkiup/minedroid/gui/overlay/Alert.java // @SideOnly(Side.CLIENT) // public class Alert extends Notification { // protected TextView mMessage; // protected Button mOkButton; // protected RelativeLayout layout = new RelativeLayout(this); // protected String text; // protected View.OnKeyDown keyListener = new View.OnKeyDown() { // @Override // public void handle(KeyEvent event) { // if (event.keyCode == Keyboard.KEY_Y) { // dismiss(); // } // FMLLog.info("Key pressed: %s", event.keyChar); // } // }; // // protected View.OnClick clickListener = new View.OnClick() { // @Override // public void handle(MouseEvent event) { // dismiss(); // } // }; // // protected Alert(Context context, String text) { // super(context); // this.text = text; // } // // @Override // protected ResourceLocation getContentLayout() { // return R.layout.alert; // } // // @Override // public boolean isModal() { // return true; // } // // @Override // protected void fill(View content) { // mMessage = (TextView) findViewById(R.id.message); // mMessage.setText(text); // content.on(clickListener); // content.on(keyListener); // } // // @Override // protected void onStart() { // // } // // @Override // protected void onStop() { // // } // // public static Alert show(String format, Object... params) { // String message = String.format(format, params); // Alert alert = new Alert(MineDroid.getMDContext(), message); // NotificationManager.open(alert); // return alert; // } // // @Override // public int getTimeLeft() { // return -1; // } // } // Path: src/main/java/com/onkiup/minedroid/net/ClientAlertPacket.java import com.onkiup.minedroid.gui.overlay.Alert; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; package com.onkiup.minedroid.net; /** * Created by chedim on 8/11/15. */ public class ClientAlertPacket extends APacket { public ClientAlertPacket() { } public String message; public ClientAlertPacket(String message) { this.message = message; } public static class CHandler extends ClientHandler<ClientAlertPacket> { @Override @SideOnly(Side.CLIENT) public APacket handle(ClientAlertPacket packet, MessageContext messageContext) {
Alert.show(packet.message);
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/EntityHeadOverlay.java
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // }
import com.onkiup.minedroid.Context; import net.minecraft.entity.Entity;
package com.onkiup.minedroid.gui; /** * Created by chedim on 8/14/15. */ public abstract class EntityHeadOverlay extends Overlay { protected Entity mEntity;
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // Path: src/main/java/com/onkiup/minedroid/gui/EntityHeadOverlay.java import com.onkiup.minedroid.Context; import net.minecraft.entity.Entity; package com.onkiup.minedroid.gui; /** * Created by chedim on 8/14/15. */ public abstract class EntityHeadOverlay extends Overlay { protected Entity mEntity;
public EntityHeadOverlay(Context context, Entity entity) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // }
import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException;
package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen;
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // } // Path: src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException; package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen;
public VanillaGuiView(Context context, GuiScreen screen) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // }
import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException;
package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen; public VanillaGuiView(Context context, GuiScreen screen) { this(context); this.screen = screen; } public VanillaGuiView(Context context) { super(context); } @Override public void drawContents(float partialTicks) { if (screen != null) { screen.setWorldAndResolution(screen.mc, resolvedLayout.getInnerWidth(), resolvedLayout.getInnerHeight()); screen.drawScreen(Mouse.getX(), Mouse.getY(), partialTicks); } } @Override
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // } // Path: src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException; package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen; public VanillaGuiView(Context context, GuiScreen screen) { this(context); this.screen = screen; } public VanillaGuiView(Context context) { super(context); } @Override public void drawContents(float partialTicks) { if (screen != null) { screen.setWorldAndResolution(screen.mc, resolvedLayout.getInnerWidth(), resolvedLayout.getInnerHeight()); screen.drawScreen(Mouse.getX(), Mouse.getY(), partialTicks); } } @Override
public void handleMouseEvent(MouseEvent event) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // }
import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException;
package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen; public VanillaGuiView(Context context, GuiScreen screen) { this(context); this.screen = screen; } public VanillaGuiView(Context context) { super(context); } @Override public void drawContents(float partialTicks) { if (screen != null) { screen.setWorldAndResolution(screen.mc, resolvedLayout.getInnerWidth(), resolvedLayout.getInnerHeight()); screen.drawScreen(Mouse.getX(), Mouse.getY(), partialTicks); } } @Override public void handleMouseEvent(MouseEvent event) { if (screen == null) return; try { screen.handleMouseInput(); } catch (IOException e) { } } @Override
// Path: src/main/java/com/onkiup/minedroid/Context.java // public interface Context { // /** // * @return Context id // */ // int contextId(); // // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/KeyEvent.java // public class KeyEvent { // /** // * Event type class // */ // public Class type; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Pressed key code // */ // public int keyCode; // /** // * Pressed key char representation // */ // public char keyChar; // /** // * Event cancelation flag // */ // public boolean cancel = false; // // /** // * Some keyboard flags // */ // public boolean shift, control, alt; // // @Override // public KeyEvent clone() { // KeyEvent result = new KeyEvent(); // result.type = type; // result.target = target; // result.source = source; // result.keyCode = keyCode; // result.keyChar = keyChar; // result.shift = shift; // result.control = control; // result.alt = alt; // result.cancel = cancel; // // return result; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/events/MouseEvent.java // public class MouseEvent { // /** // * Event type class // */ // public Class type; // /** // * Event coordinates // */ // public Point coords; // /** // * View that currently handles the event // */ // public View target; // /** // * View that was an original target of the event // */ // public View source; // /** // * Button numder (if pressed/released) // */ // public int button; // /** // * Event coordinates offset of previous event // */ // public Point diff; // /** // * Event cancelation flag // */ // public boolean cancel = false; // /** // * Scroll amount values // */ // public Point wheel; // /** // * Some useful keyboard flags // */ // public boolean shift, control, alt; // // @Override // public MouseEvent clone() { // MouseEvent result = new MouseEvent(); // result.type = type; // result.coords = coords; // result.target = target; // result.source = source; // result.button = button; // result.diff = diff; // result.cancel = cancel; // result.wheel = wheel.clone(); // result.shift = shift; // result.control = control; // result.alt = alt; // // return result; // } // } // Path: src/main/java/com/onkiup/minedroid/gui/views/VanillaGuiView.java import com.onkiup.minedroid.Context; import com.onkiup.minedroid.gui.events.KeyEvent; import com.onkiup.minedroid.gui.events.MouseEvent; import net.minecraft.client.gui.GuiScreen; import org.lwjgl.input.Mouse; import java.io.IOException; package com.onkiup.minedroid.gui.views; /** * Created by chedim on 8/5/15. */ public class VanillaGuiView extends ContentView { protected GuiScreen screen; public VanillaGuiView(Context context, GuiScreen screen) { this(context); this.screen = screen; } public VanillaGuiView(Context context) { super(context); } @Override public void drawContents(float partialTicks) { if (screen != null) { screen.setWorldAndResolution(screen.mc, resolvedLayout.getInnerWidth(), resolvedLayout.getInnerHeight()); screen.drawScreen(Mouse.getX(), Mouse.getY(), partialTicks); } } @Override public void handleMouseEvent(MouseEvent event) { if (screen == null) return; try { screen.handleMouseInput(); } catch (IOException e) { } } @Override
public void handleKeyboardEvent(KeyEvent event) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/drawables/DebugDrawable.java
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // }
import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point;
package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class DebugDrawable extends ColorDrawable { public DebugDrawable(Color color) { super(color); } @Override
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // } // Path: src/main/java/com/onkiup/minedroid/gui/drawables/DebugDrawable.java import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point; package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class DebugDrawable extends ColorDrawable { public DebugDrawable(Color color) { super(color); } @Override
public void draw(Point where) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/drawables/BorderDrawable.java
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // }
import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point;
package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class BorderDrawable extends ColorDrawable { public BorderDrawable() { super(); }
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // } // Path: src/main/java/com/onkiup/minedroid/gui/drawables/BorderDrawable.java import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point; package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class BorderDrawable extends ColorDrawable { public BorderDrawable() { super(); }
public BorderDrawable(Color color) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/drawables/BorderDrawable.java
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // }
import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point;
package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class BorderDrawable extends ColorDrawable { public BorderDrawable() { super(); } public BorderDrawable(Color color) { super(color); } protected int thickness = 1; @Override
// Path: src/main/java/com/onkiup/minedroid/gui/primitives/Color.java // public class Color { // /** // * Color components // */ // public int alpha = 255, red = 0, green = 0, blue = 0; // // public Color(int red, int green, int blue, int alpha) { // this.alpha = alpha; // this.red = red; // this.green = green; // this.blue = blue; // } // // public Color(long color) { // blue = (int) (color & 255); // green = (int) (color >> 8 & 255); // red = (int) (color >> 16 & 255); // if (color > 0xFFFFFF) { // alpha = (int) (color >> 24 & 255); // } // } // // @Override // public Color clone() throws CloneNotSupportedException { // return new Color(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public long raw() { // Long raw = 0l; // raw = raw | alpha; // raw = (raw << 8) | red; // raw = (raw << 8) | green; // raw = (raw << 8) | blue; // return raw; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/GLColor.java // public class GLColor { // public float red, green, blue, alpha; // // public GLColor(Color color) { // red = color.red / 255f; // green = color.green / 255f; // blue = color.blue / 255f; // alpha = color.alpha / 255f; // } // // public GLColor(float red, float green, float blue, float alpha) { // this.red = red; // this.green = green; // this.blue = blue; // this.alpha = alpha; // } // // public GLColor(int red, int green, int blue, int alpha) { // this.red = red / 255f; // this.green = green / 255f; // this.blue = blue / 255f; // this.alpha = alpha / 255f; // } // // @Override // public GLColor clone() { // return new GLColor(red, green, blue, alpha); // } // // @Override // public String toString() { // return "rgba_gl("+red+", "+green+", "+blue+", "+alpha+")"; // } // // public Color getColor() { // return new Color((int) (red * 255), (int) (green *255), (int) (blue * 255), (int) (alpha * 255)); // } // // public void add(GLColor step) { // red += step.red; // blue += step.blue; // green += step.green; // alpha += step.alpha; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // } // Path: src/main/java/com/onkiup/minedroid/gui/drawables/BorderDrawable.java import com.onkiup.minedroid.gui.primitives.Color; import com.onkiup.minedroid.gui.primitives.GLColor; import com.onkiup.minedroid.gui.primitives.Point; package com.onkiup.minedroid.gui.drawables; /** * Draws debug border */ public class BorderDrawable extends ColorDrawable { public BorderDrawable() { super(); } public BorderDrawable(Color color) { super(color); } protected int thickness = 1; @Override
public void draw(Point where) {
chedim/minedriod
src/main/java/com/onkiup/minedroid/gui/NotificationManager.java
// Path: src/main/java/com/onkiup/minedroid/gui/overlay/Confirm.java // public class Confirm extends Notification { // // protected String message; // protected Handler handler; // // protected View.OnKeyPress keyListener = new View.OnKeyPress() { // @Override // public void handle(KeyEvent event) { // if (event.keyCode == Keyboard.KEY_Y) { // if (handler != null) handler.onAnswer(true); // dismiss(); // return; // } // if (event.keyCode == Keyboard.KEY_N) { // if (handler != null) handler.onAnswer(false); // dismiss(); // return; // } // } // }; // // protected Confirm(Context context, String text) { // super(context); // message = text; // } // // protected Confirm(Context context, String text, Handler handler) { // this(context, text); // setHandler(handler); // } // // @Override // protected ResourceLocation getContentLayout() { // return R.layout.confirm; // } // // @Override // protected void fill(View content) { // content.on(keyListener); // TextView messageView = (TextView) content.findViewById(R.id.message); // messageView.setText(message); // } // // @Override // protected void onStart() { // // } // // @Override // protected void onStop() { // // } // // public void setHandler(Handler handler) { // this.handler = handler; // } // // public interface Handler { // public void onAnswer(boolean answer); // } // // public static Confirm show(String format, Object... params) { // String message = String.format(format, params); // Confirm confirm = new Confirm(MineDroid.getMDContext(), message); // NotificationManager.open(confirm); // return confirm; // } // // @Override // public int getTimeLeft() { // return -1; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/resources/ValueLink.java // public class ValueLink { // protected Object value; // protected boolean isResolved; // // public ValueLink(EnvValue[] variants) { // if (variants != null && variants.length > 0) { // int max = -1; // EnvValue result = null; // EnvParams env = GuiManager.getEnvParams(); // for (EnvValue variant : variants) { // int cur = variant.compareTo(env); // if (cur > max) { // result = variant; // max = cur; // if (max == 4) break; // } // } // // if (result != null) { // value = result.value; // } // } // } // // /** // * return value for current environment // * @return // */ // public Object getValue() { // return value; // } // // @Override // public String toString() { // return value.toString(); // } // }
import com.onkiup.minedroid.gui.overlay.Confirm; import com.onkiup.minedroid.gui.primitives.Point; import com.onkiup.minedroid.gui.resources.ValueLink; import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Mouse; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package com.onkiup.minedroid.gui; /** * Created by chedim on 8/12/15. */ @SideOnly(Side.CLIENT) public class NotificationManager { protected NotificationManager() { } static { FMLCommonHandler.instance().bus().register(new EventHandler()); } /** * Notifications list */ private static List<Notification> notifications = new ArrayList<Notification>(); public static void open(Notification notification) { synchronized (notifications) { notifications.add(notification); } } public static class EventHandler { protected EventHandler() { } @SubscribeEvent @SideOnly(Side.CLIENT) public void onEndTick(TickEvent.RenderTickEvent event) { List<Notification> remove = new ArrayList<Notification>(); if (event.phase == TickEvent.Phase.START) { return; }
// Path: src/main/java/com/onkiup/minedroid/gui/overlay/Confirm.java // public class Confirm extends Notification { // // protected String message; // protected Handler handler; // // protected View.OnKeyPress keyListener = new View.OnKeyPress() { // @Override // public void handle(KeyEvent event) { // if (event.keyCode == Keyboard.KEY_Y) { // if (handler != null) handler.onAnswer(true); // dismiss(); // return; // } // if (event.keyCode == Keyboard.KEY_N) { // if (handler != null) handler.onAnswer(false); // dismiss(); // return; // } // } // }; // // protected Confirm(Context context, String text) { // super(context); // message = text; // } // // protected Confirm(Context context, String text, Handler handler) { // this(context, text); // setHandler(handler); // } // // @Override // protected ResourceLocation getContentLayout() { // return R.layout.confirm; // } // // @Override // protected void fill(View content) { // content.on(keyListener); // TextView messageView = (TextView) content.findViewById(R.id.message); // messageView.setText(message); // } // // @Override // protected void onStart() { // // } // // @Override // protected void onStop() { // // } // // public void setHandler(Handler handler) { // this.handler = handler; // } // // public interface Handler { // public void onAnswer(boolean answer); // } // // public static Confirm show(String format, Object... params) { // String message = String.format(format, params); // Confirm confirm = new Confirm(MineDroid.getMDContext(), message); // NotificationManager.open(confirm); // return confirm; // } // // @Override // public int getTimeLeft() { // return -1; // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/primitives/Point.java // public class Point { // // public int x, y; // // public Point(int x, int y) { // this.x = x; // this.y = y; // } // // @Override // public Point clone() { // return new Point(x, y); // } // // @Override // public String toString() { // return "("+x+", "+y+")"; // } // // /** // * Uses given point as an offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point add(Point point) { // Point result = clone(); // result.x += point.x; // result.y += point.y; // return result; // } // // /** // * Uses given point as a negative offset to create a moved point // * @param point Offset // * @return Moved point // */ // public Point sub(Point point) { // Point result = clone(); // result.x -= point.x; // result.y -= point.y; // return result; // } // // public void max(Point o) { // x = Math.max(x, o.x); // y = Math.max(y, o.y); // } // } // // Path: src/main/java/com/onkiup/minedroid/gui/resources/ValueLink.java // public class ValueLink { // protected Object value; // protected boolean isResolved; // // public ValueLink(EnvValue[] variants) { // if (variants != null && variants.length > 0) { // int max = -1; // EnvValue result = null; // EnvParams env = GuiManager.getEnvParams(); // for (EnvValue variant : variants) { // int cur = variant.compareTo(env); // if (cur > max) { // result = variant; // max = cur; // if (max == 4) break; // } // } // // if (result != null) { // value = result.value; // } // } // } // // /** // * return value for current environment // * @return // */ // public Object getValue() { // return value; // } // // @Override // public String toString() { // return value.toString(); // } // } // Path: src/main/java/com/onkiup/minedroid/gui/NotificationManager.java import com.onkiup.minedroid.gui.overlay.Confirm; import com.onkiup.minedroid.gui.primitives.Point; import com.onkiup.minedroid.gui.resources.ValueLink; import net.minecraft.client.gui.ScaledResolution; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Mouse; import java.io.IOException; import java.util.ArrayList; import java.util.List; package com.onkiup.minedroid.gui; /** * Created by chedim on 8/12/15. */ @SideOnly(Side.CLIENT) public class NotificationManager { protected NotificationManager() { } static { FMLCommonHandler.instance().bus().register(new EventHandler()); } /** * Notifications list */ private static List<Notification> notifications = new ArrayList<Notification>(); public static void open(Notification notification) { synchronized (notifications) { notifications.add(notification); } } public static class EventHandler { protected EventHandler() { } @SubscribeEvent @SideOnly(Side.CLIENT) public void onEndTick(TickEvent.RenderTickEvent event) { List<Notification> remove = new ArrayList<Notification>(); if (event.phase == TickEvent.Phase.START) { return; }
Point next = new Point(0, 0);
TUBAME/migration-tool
src/tubame.integration.test/resources/javaProjects/tag-html-struts1/src/main/java/struts1tospringmvc/tag/html/struts1/action/MultiBoxResultAction.java
// Path: src/tubame.integration.test/resources/javaProjects/tag-html-struts1/src/main/java/struts1tospringmvc/tag/html/struts1/action/model/OtherMultiboxBean.java // public class OtherMultiboxBean { // // private String otherMultiboxProperty; // // public OtherMultiboxBean() {} // // public OtherMultiboxBean(String otherMultiboxProperty) { // this.otherMultiboxProperty = otherMultiboxProperty; // } // // public String getOtherMultiboxProperty() { // return otherMultiboxProperty; // } // // public void setOtherMultiboxProperty(String otherMultiboxProperty) { // this.otherMultiboxProperty = otherMultiboxProperty; // } // // }
import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import struts1tospringmvc.tag.html.struts1.action.model.OtherMultiboxBean; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
package struts1tospringmvc.tag.html.struts1.action; /** * @author tanabe */ public class MultiBoxResultAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String requestedOtherMultiboxProperty = request.getParameter("otherMultiboxProperty");
// Path: src/tubame.integration.test/resources/javaProjects/tag-html-struts1/src/main/java/struts1tospringmvc/tag/html/struts1/action/model/OtherMultiboxBean.java // public class OtherMultiboxBean { // // private String otherMultiboxProperty; // // public OtherMultiboxBean() {} // // public OtherMultiboxBean(String otherMultiboxProperty) { // this.otherMultiboxProperty = otherMultiboxProperty; // } // // public String getOtherMultiboxProperty() { // return otherMultiboxProperty; // } // // public void setOtherMultiboxProperty(String otherMultiboxProperty) { // this.otherMultiboxProperty = otherMultiboxProperty; // } // // } // Path: src/tubame.integration.test/resources/javaProjects/tag-html-struts1/src/main/java/struts1tospringmvc/tag/html/struts1/action/MultiBoxResultAction.java import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import struts1tospringmvc.tag.html.struts1.action.model.OtherMultiboxBean; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; package struts1tospringmvc.tag.html.struts1.action; /** * @author tanabe */ public class MultiBoxResultAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String requestedOtherMultiboxProperty = request.getParameter("otherMultiboxProperty");
request.setAttribute("otherMultiboxBean", new OtherMultiboxBean(requestedOtherMultiboxProperty));
TUBAME/migration-tool
src/tubame.knowhow/src/tubame/knowhow/plugin/logic/FileManagement.java
// Path: src/tubame.knowhow.biz/src/main/java/tubame/knowhow/biz/logic/converter/SearchModuleConverter.java // public class SearchModuleConverter { // /** Logger */ // private static final Logger LOGGER = LoggerFactory // .getLogger(SearchModuleConverter.class); // /** Search module map */ // private Map<String, String> searchModuleMap = new LinkedHashMap<String, String>(); // // /** // * Converted to Map format information search module XML.<br/> // * // * @param portabilitySearchModule // * Search module information // */ // public void convert(PortabilitySearchModule portabilitySearchModule) { // LOGGER.debug(MessagePropertiesUtil // .getMessage(MessagePropertiesUtil.LOG_PARAMA) // + "PortabilitySearchModule"); // for (SearchModule searchModule : portabilitySearchModule // .getSearchModuleList().getSearchModule()) { // searchModuleMap.put(searchModule.getModuleName(), // searchModule.getModuleDescription()); // } // } // // /** // * Get searchModuleMap.<br/> // * // * @return searchModuleMap // */ // public Map<String, String> getSearchModuleMap() { // return searchModuleMap; // } // } // // Path: src/tubame.knowhow/src/tubame/knowhow/plugin/ui/view/ViewRefresh.java // public interface ViewRefresh { // // /** // * make the view update.<br/> // * // */ // public void refresh(); // }
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.eclipse.ui.IViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import tubame.common.logic.converter.CmnDocBookConverter; import tubame.common.util.CmnFileUtil; import tubame.common.util.CmnStringUtil; import tubame.knowhow.biz.exception.JbmException; import tubame.knowhow.biz.logic.SearchModuleFacade; import tubame.knowhow.biz.logic.converter.AsciiDocConverter; import tubame.knowhow.biz.logic.converter.SearchModuleConverter; import tubame.knowhow.biz.model.generated.python.PortabilitySearchModule; import tubame.knowhow.biz.util.resource.MessagePropertiesUtil; import tubame.knowhow.plugin.ui.dialog.ErrorDialog; import tubame.knowhow.plugin.ui.view.ViewRefresh; import tubame.knowhow.util.FileUtil; import tubame.knowhow.util.PluginUtil; import tubame.knowhow.util.resource.ResourceUtil;
* get the View of refreshed. * * @param iViewPart * View * @param key * Key message of error * @return ViewRefresh * @throws JbmException * If this is not View of ViewRefresh */ private static ViewRefresh getViewRefresh(IViewPart iViewPart, String key) throws JbmException { if (!(iViewPart instanceof ViewRefresh)) { throw new JbmException(MessagePropertiesUtil.getMessage(key)); } return (ViewRefresh) iViewPart; } /** * Create a search module information.<br/> * create a search module information. It does not generate if the search * module information already exists.<br/> * * @param searchModuleFullPath * Search module file full path */ public static void createSearchModuleMap(String searchModuleFullPath) { FileManagement.LOGGER.debug("[searchModuleFullPath]" + searchModuleFullPath); if (FileManagement.searchModuleMap == null) { try { PortabilitySearchModule portabilitySearchModule = SearchModuleFacade.readFullPath(searchModuleFullPath);
// Path: src/tubame.knowhow.biz/src/main/java/tubame/knowhow/biz/logic/converter/SearchModuleConverter.java // public class SearchModuleConverter { // /** Logger */ // private static final Logger LOGGER = LoggerFactory // .getLogger(SearchModuleConverter.class); // /** Search module map */ // private Map<String, String> searchModuleMap = new LinkedHashMap<String, String>(); // // /** // * Converted to Map format information search module XML.<br/> // * // * @param portabilitySearchModule // * Search module information // */ // public void convert(PortabilitySearchModule portabilitySearchModule) { // LOGGER.debug(MessagePropertiesUtil // .getMessage(MessagePropertiesUtil.LOG_PARAMA) // + "PortabilitySearchModule"); // for (SearchModule searchModule : portabilitySearchModule // .getSearchModuleList().getSearchModule()) { // searchModuleMap.put(searchModule.getModuleName(), // searchModule.getModuleDescription()); // } // } // // /** // * Get searchModuleMap.<br/> // * // * @return searchModuleMap // */ // public Map<String, String> getSearchModuleMap() { // return searchModuleMap; // } // } // // Path: src/tubame.knowhow/src/tubame/knowhow/plugin/ui/view/ViewRefresh.java // public interface ViewRefresh { // // /** // * make the view update.<br/> // * // */ // public void refresh(); // } // Path: src/tubame.knowhow/src/tubame/knowhow/plugin/logic/FileManagement.java import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.eclipse.ui.IViewPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import tubame.common.logic.converter.CmnDocBookConverter; import tubame.common.util.CmnFileUtil; import tubame.common.util.CmnStringUtil; import tubame.knowhow.biz.exception.JbmException; import tubame.knowhow.biz.logic.SearchModuleFacade; import tubame.knowhow.biz.logic.converter.AsciiDocConverter; import tubame.knowhow.biz.logic.converter.SearchModuleConverter; import tubame.knowhow.biz.model.generated.python.PortabilitySearchModule; import tubame.knowhow.biz.util.resource.MessagePropertiesUtil; import tubame.knowhow.plugin.ui.dialog.ErrorDialog; import tubame.knowhow.plugin.ui.view.ViewRefresh; import tubame.knowhow.util.FileUtil; import tubame.knowhow.util.PluginUtil; import tubame.knowhow.util.resource.ResourceUtil; * get the View of refreshed. * * @param iViewPart * View * @param key * Key message of error * @return ViewRefresh * @throws JbmException * If this is not View of ViewRefresh */ private static ViewRefresh getViewRefresh(IViewPart iViewPart, String key) throws JbmException { if (!(iViewPart instanceof ViewRefresh)) { throw new JbmException(MessagePropertiesUtil.getMessage(key)); } return (ViewRefresh) iViewPart; } /** * Create a search module information.<br/> * create a search module information. It does not generate if the search * module information already exists.<br/> * * @param searchModuleFullPath * Search module file full path */ public static void createSearchModuleMap(String searchModuleFullPath) { FileManagement.LOGGER.debug("[searchModuleFullPath]" + searchModuleFullPath); if (FileManagement.searchModuleMap == null) { try { PortabilitySearchModule portabilitySearchModule = SearchModuleFacade.readFullPath(searchModuleFullPath);
SearchModuleConverter searchModuleConverter = SearchModuleFacade.getSearchModuleConverter();
TUBAME/migration-tool
src/tubame.knowhow/src/tubame/knowhow/plugin/logic/command/CommandViewCategory.java
// Path: src/tubame.knowhow.biz/src/main/java/tubame/knowhow/biz/model/EntryViewItemEnum.java // public enum EntryViewItemEnum implements DefineEnumOperator { // // /** Enum Category */ // Category(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.CATEGORY)), // /** Enumeration Knowhow */ // Knowhow(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.KNOWHOW)), // /** Enumeration KnowhowDetail */ // KnowhowDetail(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.KNOWHOWDETAIL)), // /** Enumeration CheckItem */ // CheckItem(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.CHECKITEM)), // /** Enumeration SearchInfo */ // SearchInfo(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.SEARCHINFO)); // // /** Member variable of type String */ // private final String value; // // /** // * Constructor.<br/> // * // * @param v // * Enumeration data string // */ // EntryViewItemEnum(String v) { // value = v; // } // // /** // * Get a search keyword type.<br/> // * // * @param v // * Enumeration data string // * @return InputKeywordFileType // * @IllegalArgumentException Exception handling // */ // public static EntryViewItemEnum fromValue(String v) { // for (EntryViewItemEnum c : EntryViewItemEnum.values()) { // if (c.value.equals(v)) { // return c; // } // } // throw new IllegalArgumentException(v); // } // // /** // * {@inheritDoc} // */ // @Override // public String getName() { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public String getKey() { // return value; // } // }
import tubame.knowhow.plugin.logic.EntryItemManagement; import tubame.knowhow.plugin.model.view.AbstractViewType; import tubame.knowhow.plugin.model.view.CategoryViewType; import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewData; import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewOperation; import tubame.knowhow.util.ViewUtil; import java.util.List; import java.util.Map; import tubame.knowhow.biz.model.generated.knowhow.Category; import tubame.knowhow.biz.model.generated.knowhow.ChildEntry; import tubame.knowhow.biz.model.generated.knowhow.EntryCategory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tubame.knowhow.biz.logic.converter.PortabilityKnowhowConverter; import tubame.knowhow.biz.model.EntryViewItemEnum;
/* * CommandViewCategory.java * Created on 2013/06/28 * * Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation * * 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 tubame.knowhow.plugin.logic.command; /** * Converted to category data from the know-how XML.<br/> * converted to category data entry view of know-how from the know-how for XML.<br/> * JDK7<br/> */ public class CommandViewCategory { /** Logger */ private static final Logger LOGGER = LoggerFactory .getLogger(CommandViewCategory.class); /** Category level */ private static final int CATEGORY_LEVEL = PortabilityKnowhowListViewData.LEVEL_FIRST; /** Map data category */ private Map<String, Category> categoryMap; /** Know-how conversion command object */ private CommandViewKnowhow commandViewKnowhow; /** * Constructor.<br/> * * @param portabilityKnowhowConverter * Know-how XML information */ public CommandViewCategory( PortabilityKnowhowConverter portabilityKnowhowConverter) { this.categoryMap = portabilityKnowhowConverter.getCategoryMap(); commandViewKnowhow = new CommandViewKnowhow(portabilityKnowhowConverter); } /** * Converted to category data for View display.<br/> * Converted know-how XML data to category data in the View for display.<br/> * * @param entryCategory * Entry category tag information * @return PortabilityKnowhowListViewOperation Category data */ public PortabilityKnowhowListViewOperation command( EntryCategory entryCategory) { CommandViewCategory.LOGGER.debug("[entryCategory]" + entryCategory); Category category = getCateogry(entryCategory, null); // Generate the category of Top hierarchy PortabilityKnowhowListViewData topCategory = new PortabilityKnowhowListViewData( null, CATEGORY_LEVEL, knowhowXmlToEntryView(category)); EntryItemManagement.compareEntryItemId(topCategory.getKnowhowViewType()
// Path: src/tubame.knowhow.biz/src/main/java/tubame/knowhow/biz/model/EntryViewItemEnum.java // public enum EntryViewItemEnum implements DefineEnumOperator { // // /** Enum Category */ // Category(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.CATEGORY)), // /** Enumeration Knowhow */ // Knowhow(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.KNOWHOW)), // /** Enumeration KnowhowDetail */ // KnowhowDetail(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.KNOWHOWDETAIL)), // /** Enumeration CheckItem */ // CheckItem(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.CHECKITEM)), // /** Enumeration SearchInfo */ // SearchInfo(ApplicationPropertiesUtil // .getProperty(ApplicationPropertiesUtil.SEARCHINFO)); // // /** Member variable of type String */ // private final String value; // // /** // * Constructor.<br/> // * // * @param v // * Enumeration data string // */ // EntryViewItemEnum(String v) { // value = v; // } // // /** // * Get a search keyword type.<br/> // * // * @param v // * Enumeration data string // * @return InputKeywordFileType // * @IllegalArgumentException Exception handling // */ // public static EntryViewItemEnum fromValue(String v) { // for (EntryViewItemEnum c : EntryViewItemEnum.values()) { // if (c.value.equals(v)) { // return c; // } // } // throw new IllegalArgumentException(v); // } // // /** // * {@inheritDoc} // */ // @Override // public String getName() { // return value; // } // // /** // * {@inheritDoc} // */ // @Override // public String getKey() { // return value; // } // } // Path: src/tubame.knowhow/src/tubame/knowhow/plugin/logic/command/CommandViewCategory.java import tubame.knowhow.plugin.logic.EntryItemManagement; import tubame.knowhow.plugin.model.view.AbstractViewType; import tubame.knowhow.plugin.model.view.CategoryViewType; import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewData; import tubame.knowhow.plugin.model.view.PortabilityKnowhowListViewOperation; import tubame.knowhow.util.ViewUtil; import java.util.List; import java.util.Map; import tubame.knowhow.biz.model.generated.knowhow.Category; import tubame.knowhow.biz.model.generated.knowhow.ChildEntry; import tubame.knowhow.biz.model.generated.knowhow.EntryCategory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tubame.knowhow.biz.logic.converter.PortabilityKnowhowConverter; import tubame.knowhow.biz.model.EntryViewItemEnum; /* * CommandViewCategory.java * Created on 2013/06/28 * * Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation * * 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 tubame.knowhow.plugin.logic.command; /** * Converted to category data from the know-how XML.<br/> * converted to category data entry view of know-how from the know-how for XML.<br/> * JDK7<br/> */ public class CommandViewCategory { /** Logger */ private static final Logger LOGGER = LoggerFactory .getLogger(CommandViewCategory.class); /** Category level */ private static final int CATEGORY_LEVEL = PortabilityKnowhowListViewData.LEVEL_FIRST; /** Map data category */ private Map<String, Category> categoryMap; /** Know-how conversion command object */ private CommandViewKnowhow commandViewKnowhow; /** * Constructor.<br/> * * @param portabilityKnowhowConverter * Know-how XML information */ public CommandViewCategory( PortabilityKnowhowConverter portabilityKnowhowConverter) { this.categoryMap = portabilityKnowhowConverter.getCategoryMap(); commandViewKnowhow = new CommandViewKnowhow(portabilityKnowhowConverter); } /** * Converted to category data for View display.<br/> * Converted know-how XML data to category data in the View for display.<br/> * * @param entryCategory * Entry category tag information * @return PortabilityKnowhowListViewOperation Category data */ public PortabilityKnowhowListViewOperation command( EntryCategory entryCategory) { CommandViewCategory.LOGGER.debug("[entryCategory]" + entryCategory); Category category = getCateogry(entryCategory, null); // Generate the category of Top hierarchy PortabilityKnowhowListViewData topCategory = new PortabilityKnowhowListViewData( null, CATEGORY_LEVEL, knowhowXmlToEntryView(category)); EntryItemManagement.compareEntryItemId(topCategory.getKnowhowViewType()
.getRegisterKey(), EntryViewItemEnum.Category.getName());
seanho/agile-stock
tests/src/hk/reality/stock/service/fetcher/Money18QuoteFetcherTest.java
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // }
import hk.reality.stock.model.StockDetail; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.json.JSONObject; import android.util.Log;
package hk.reality.stock.service.fetcher; public class Money18QuoteFetcherTest extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testJson() throws JSONException { String jsonSrc = "M18.r_00005 = { ltt: '2009/10/07 16:00', np: '87.450', iep: '0.000', iev: '00000000000', ltp: '87.600', vol: '00025255927', tvr: '02204863352', dyh: '87.700', dyl: '86.850'};"; int pos = jsonSrc.indexOf('{'); String result = StringUtils.substring(jsonSrc, pos); JSONObject json = new JSONObject(result); Log.d("TEST", json.toString(2)); } public void testGetStockNormal() { testStock("00005"); testStock("03328"); testStock("00303"); } public void testGetStockDerivatives() { testStock("17032"); } private void testStock(String quote) { QuoteFetcher fetcher = getFetcher();
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // Path: tests/src/hk/reality/stock/service/fetcher/Money18QuoteFetcherTest.java import hk.reality.stock.model.StockDetail; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.commons.lang.StringUtils; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; package hk.reality.stock.service.fetcher; public class Money18QuoteFetcherTest extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testJson() throws JSONException { String jsonSrc = "M18.r_00005 = { ltt: '2009/10/07 16:00', np: '87.450', iep: '0.000', iev: '00000000000', ltp: '87.600', vol: '00025255927', tvr: '02204863352', dyh: '87.700', dyl: '86.850'};"; int pos = jsonSrc.indexOf('{'); String result = StringUtils.substring(jsonSrc, pos); JSONObject json = new JSONObject(result); Log.d("TEST", json.toString(2)); } public void testGetStockNormal() { testStock("00005"); testStock("03328"); testStock("00303"); } public void testGetStockDerivatives() { testStock("17032"); } private void testStock(String quote) { QuoteFetcher fetcher = getFetcher();
StockDetail detail = fetcher.fetch(quote);
seanho/agile-stock
src/hk/reality/stock/service/FilePortfolioService.java
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/service/exception/StorageException.java // public class StorageException extends RuntimeException { // // public StorageException() { // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public StorageException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.model.Portfolio; import hk.reality.stock.service.exception.StorageException; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Vector; import org.apache.commons.io.IOUtils; import android.util.Log; import com.thoughtworks.xstream.io.StreamException;
package hk.reality.stock.service; public class FilePortfolioService implements PortfolioService { private static final String STORAGE_FILE = "portfolio.xml"; private static final String TAG = "FilePortfolioService"; private File baseDirectory;
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/service/exception/StorageException.java // public class StorageException extends RuntimeException { // // public StorageException() { // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public StorageException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/FilePortfolioService.java import hk.reality.stock.model.Portfolio; import hk.reality.stock.service.exception.StorageException; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Vector; import org.apache.commons.io.IOUtils; import android.util.Log; import com.thoughtworks.xstream.io.StreamException; package hk.reality.stock.service; public class FilePortfolioService implements PortfolioService { private static final String STORAGE_FILE = "portfolio.xml"; private static final String TAG = "FilePortfolioService"; private File baseDirectory;
private List<Portfolio> portfolios;
seanho/agile-stock
src/hk/reality/stock/service/FilePortfolioService.java
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/service/exception/StorageException.java // public class StorageException extends RuntimeException { // // public StorageException() { // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public StorageException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.model.Portfolio; import hk.reality.stock.service.exception.StorageException; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Vector; import org.apache.commons.io.IOUtils; import android.util.Log; import com.thoughtworks.xstream.io.StreamException;
return Collections.unmodifiableList(this.portfolios); } @Override public void update(Portfolio p) { Log.i(TAG, "update portfolio: " + p.getName()); int pos = portfolios.indexOf(p); if (pos > -1) { Portfolio orig = portfolios.get(pos); orig.setName(p.getName()); orig.setStocks(p.getStocks()); } else { throw new IllegalArgumentException("record not found"); } save(); } private List<Portfolio> loadOrCreateNew() { Log.i(TAG, "loading portfolio file ..."); File store = new File(baseDirectory, STORAGE_FILE); Reader reader = null; try { if (!store.exists()) { return new Vector<Portfolio>(); } reader = new FileReader(store); return PortfolioSerializer.fromXML(reader); } catch (IOException e) {
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/service/exception/StorageException.java // public class StorageException extends RuntimeException { // // public StorageException() { // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public StorageException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public StorageException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/FilePortfolioService.java import hk.reality.stock.model.Portfolio; import hk.reality.stock.service.exception.StorageException; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.Vector; import org.apache.commons.io.IOUtils; import android.util.Log; import com.thoughtworks.xstream.io.StreamException; return Collections.unmodifiableList(this.portfolios); } @Override public void update(Portfolio p) { Log.i(TAG, "update portfolio: " + p.getName()); int pos = portfolios.indexOf(p); if (pos > -1) { Portfolio orig = portfolios.get(pos); orig.setName(p.getName()); orig.setStocks(p.getStocks()); } else { throw new IllegalArgumentException("record not found"); } save(); } private List<Portfolio> loadOrCreateNew() { Log.i(TAG, "loading portfolio file ..."); File store = new File(baseDirectory, STORAGE_FILE); Reader reader = null; try { if (!store.exists()) { return new Vector<Portfolio>(); } reader = new FileReader(store); return PortfolioSerializer.fromXML(reader); } catch (IOException e) {
throw new StorageException("failed storing datafile", e);
seanho/agile-stock
tests/src/hk/reality/stock/service/searcher/HkexStockSearcherTest.java
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // }
import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import junit.framework.Assert; import junit.framework.TestCase;
package hk.reality.stock.service.searcher; public class HkexStockSearcherTest extends TestCase { HkexStockSearcher searcher; protected void setUp() throws Exception {
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // Path: tests/src/hk/reality/stock/service/searcher/HkexStockSearcherTest.java import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import junit.framework.Assert; import junit.framework.TestCase; package hk.reality.stock.service.searcher; public class HkexStockSearcherTest extends TestCase { HkexStockSearcher searcher; protected void setUp() throws Exception {
searcher = new HkexStockSearcher(Lang.CHI);
seanho/agile-stock
tests/src/hk/reality/stock/service/searcher/HkexStockSearcherTest.java
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // }
import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import junit.framework.Assert; import junit.framework.TestCase;
package hk.reality.stock.service.searcher; public class HkexStockSearcherTest extends TestCase { HkexStockSearcher searcher; protected void setUp() throws Exception { searcher = new HkexStockSearcher(Lang.CHI); } protected void tearDown() throws Exception { super.tearDown(); } public void testSearchStock() {
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // Path: tests/src/hk/reality/stock/service/searcher/HkexStockSearcherTest.java import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import junit.framework.Assert; import junit.framework.TestCase; package hk.reality.stock.service.searcher; public class HkexStockSearcherTest extends TestCase { HkexStockSearcher searcher; protected void setUp() throws Exception { searcher = new HkexStockSearcher(Lang.CHI); } protected void tearDown() throws Exception { super.tearDown(); } public void testSearchStock() {
Stock stock5 = searcher.searchStock("00005");
seanho/agile-stock
tests/src/hk/reality/stock/service/searcher/PortfolioSerializerTest.java
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/PortfolioSerializer.java // public class PortfolioSerializer { // public static String toXML(List<Portfolio> portfolios) { // XStream xstream = getXStream(); // return xstream.toXML(portfolios); // } // // @SuppressWarnings("unchecked") // public static List<Portfolio> fromXML(String xml) { // XStream xstream = getXStream(); // return (List<Portfolio>) xstream.fromXML(xml); // } // // @SuppressWarnings("unchecked") // public static List<Portfolio> fromXML(Reader xml) { // XStream xstream = getXStream(); // return (List<Portfolio>) xstream.fromXML(xml); // } // // private static XStream getXStream() { // XStream xstream = new XStream(); // xstream.alias("sk", Stock.class); // xstream.alias("po", Portfolio.class); // xstream.alias("sd", StockDetail.class); // xstream.aliasField("q", StockDetail.class, "quote"); // xstream.aliasField("n", StockDetail.class, "name"); // xstream.aliasField("su", StockDetail.class, "sourceUrl"); // xstream.aliasField("v", StockDetail.class, "volume"); // xstream.aliasField("p", StockDetail.class, "price"); // xstream.aliasField("cp", StockDetail.class, "changePrice"); // xstream.aliasField("cpp", StockDetail.class, "changePricePercent"); // xstream.aliasField("h", StockDetail.class, "dayHigh"); // xstream.aliasField("l", StockDetail.class, "dayLow"); // xstream.aliasField("ud", StockDetail.class, "updatedAt"); // return xstream; // } // }
import hk.reality.stock.model.Portfolio; import hk.reality.stock.model.Stock; import hk.reality.stock.service.PortfolioSerializer; import java.util.ArrayList; import java.util.List; import java.util.UUID; import junit.framework.Assert; import junit.framework.TestCase; import android.util.Log;
package hk.reality.stock.service.searcher; public class PortfolioSerializerTest extends TestCase { public void testToXML() {
// Path: src/hk/reality/stock/model/Portfolio.java // public class Portfolio implements Serializable { // private static final long serialVersionUID = -5967634365697531599L; // private String id; // private String name; // private List<Stock> stocks; // // public Portfolio() { // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the stocks // */ // public List<Stock> getStocks() { // return stocks; // } // // /** // * @param stocks // * the stocks to set // */ // public void setStocks(List<Stock> stocks) { // this.stocks = stocks; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Portfolio other = (Portfolio) obj; // if (id == null) { // if (other.id != null) // return false; // } else if (!id.equals(other.id)) // return false; // return true; // } // // // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/PortfolioSerializer.java // public class PortfolioSerializer { // public static String toXML(List<Portfolio> portfolios) { // XStream xstream = getXStream(); // return xstream.toXML(portfolios); // } // // @SuppressWarnings("unchecked") // public static List<Portfolio> fromXML(String xml) { // XStream xstream = getXStream(); // return (List<Portfolio>) xstream.fromXML(xml); // } // // @SuppressWarnings("unchecked") // public static List<Portfolio> fromXML(Reader xml) { // XStream xstream = getXStream(); // return (List<Portfolio>) xstream.fromXML(xml); // } // // private static XStream getXStream() { // XStream xstream = new XStream(); // xstream.alias("sk", Stock.class); // xstream.alias("po", Portfolio.class); // xstream.alias("sd", StockDetail.class); // xstream.aliasField("q", StockDetail.class, "quote"); // xstream.aliasField("n", StockDetail.class, "name"); // xstream.aliasField("su", StockDetail.class, "sourceUrl"); // xstream.aliasField("v", StockDetail.class, "volume"); // xstream.aliasField("p", StockDetail.class, "price"); // xstream.aliasField("cp", StockDetail.class, "changePrice"); // xstream.aliasField("cpp", StockDetail.class, "changePricePercent"); // xstream.aliasField("h", StockDetail.class, "dayHigh"); // xstream.aliasField("l", StockDetail.class, "dayLow"); // xstream.aliasField("ud", StockDetail.class, "updatedAt"); // return xstream; // } // } // Path: tests/src/hk/reality/stock/service/searcher/PortfolioSerializerTest.java import hk.reality.stock.model.Portfolio; import hk.reality.stock.model.Stock; import hk.reality.stock.service.PortfolioSerializer; import java.util.ArrayList; import java.util.List; import java.util.UUID; import junit.framework.Assert; import junit.framework.TestCase; import android.util.Log; package hk.reality.stock.service.searcher; public class PortfolioSerializerTest extends TestCase { public void testToXML() {
ArrayList<Portfolio> port = new ArrayList<Portfolio>();
seanho/agile-stock
src/hk/reality/stock/service/searcher/StockSearcher.java
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // }
import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang;
package hk.reality.stock.service.searcher; public interface StockSearcher { void setLanguage(Lang language);
// Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // Path: src/hk/reality/stock/service/searcher/StockSearcher.java import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; package hk.reality.stock.service.searcher; public interface StockSearcher { void setLanguage(Lang language);
Stock searchStock(String quote);
seanho/agile-stock
src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context;
package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
public List<Index> fetch() throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context;
package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
public List<Index> fetch() throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context;
package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; package hk.reality.stock.service.fetcher; public class Money18IndexesFetcher extends BaseIndexesFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; private Context context; public Money18IndexesFetcher(Context context) { this.context = context; } @Override
public List<Index> fetch() throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context;
@Override public List<Index> fetch() throws DownloadException, ParseException { List<Index> indexes = new ArrayList<Index>(); indexes.add(getHsi()); indexes.addAll(getWorldIndexes()); return indexes; } private Index getHsi() throws ParseException, DownloadException { try { Index hsi = new Index(); HttpGet req = new HttpGet(getHSIURL()); req.setHeader("Referer", "http://money18.on.cc/"); HttpResponse resp = getClient().execute(req); String content = EntityUtils.toString(resp.getEntity()); JSONObject json = preprocessJson(content); SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); Date updateTime = formatter.parse(json.getString("ltt")); Calendar updatedAt = Calendar.getInstance(); updatedAt.setTime(updateTime); hsi.setUpdatedAt(updatedAt); double value = json.getDouble("value"); double change = json.getDouble("difference"); double changePercent = change * 100.0 / value; hsi.setName(getContext().getString(R.string.msg_hsi)); hsi.setValue(new BigDecimal(json.getString("value")));
// Path: src/hk/reality/stock/service/fetcher/Utils.java // public static String rounded(double value, double ratio) { // return String.format("%.3f", (Math.round(value * ratio) / ratio)); // } // // Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/Money18IndexesFetcher.java import static hk.reality.stock.service.fetcher.Utils.rounded; import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; @Override public List<Index> fetch() throws DownloadException, ParseException { List<Index> indexes = new ArrayList<Index>(); indexes.add(getHsi()); indexes.addAll(getWorldIndexes()); return indexes; } private Index getHsi() throws ParseException, DownloadException { try { Index hsi = new Index(); HttpGet req = new HttpGet(getHSIURL()); req.setHeader("Referer", "http://money18.on.cc/"); HttpResponse resp = getClient().execute(req); String content = EntityUtils.toString(resp.getEntity()); JSONObject json = preprocessJson(content); SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); Date updateTime = formatter.parse(json.getString("ltt")); Calendar updatedAt = Calendar.getInstance(); updatedAt.setTime(updateTime); hsi.setUpdatedAt(updatedAt); double value = json.getDouble("value"); double change = json.getDouble("difference"); double changePercent = change * 100.0 / value; hsi.setName(getContext().getString(R.string.msg_hsi)); hsi.setValue(new BigDecimal(json.getString("value")));
hsi.setChange(new BigDecimal(rounded(change, 1000.0)));
seanho/agile-stock
src/hk/reality/stock/service/fetcher/BaseQuoteFetcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // }
import hk.reality.stock.Constants; import org.apache.commons.lang.StringUtils; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.TagNode; import org.htmlcleaner.XPatherException;
package hk.reality.stock.service.fetcher; public abstract class BaseQuoteFetcher implements QuoteFetcher { private HttpClient client; private HtmlCleaner cleaner; private static final int TIMEOUT = 10; public BaseQuoteFetcher() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // Path: src/hk/reality/stock/service/fetcher/BaseQuoteFetcher.java import hk.reality.stock.Constants; import org.apache.commons.lang.StringUtils; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.TagNode; import org.htmlcleaner.XPatherException; package hk.reality.stock.service.fetcher; public abstract class BaseQuoteFetcher implements QuoteFetcher { private HttpClient client; private HtmlCleaner cleaner; private static final int TIMEOUT = 10; public BaseQuoteFetcher() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT);
seanho/agile-stock
src/hk/reality/stock/service/fetcher/QuoteFetcher.java
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException;
package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/QuoteFetcher.java import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
StockDetail fetch(String quote) throws DownloadException, ParseException;
seanho/agile-stock
src/hk/reality/stock/service/fetcher/QuoteFetcher.java
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException;
package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/QuoteFetcher.java import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
StockDetail fetch(String quote) throws DownloadException, ParseException;
seanho/agile-stock
src/hk/reality/stock/service/fetcher/QuoteFetcher.java
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException;
package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
// Path: src/hk/reality/stock/model/StockDetail.java // public class StockDetail implements Serializable { // private static final long serialVersionUID = -6897978978998L; // private String quote; // private String sourceUrl; // private String volume; // private BigDecimal price; // private BigDecimal changePrice; // private BigDecimal changePricePercent; // private BigDecimal dayHigh; // private BigDecimal dayLow; // private Calendar updatedAt; // // /** // * @return the price // */ // public BigDecimal getPrice() { // return price; // } // // /** // * @param price // * the price to set // */ // public void setPrice(BigDecimal price) { // this.price = price; // } // // /** // * @return the changePrice // */ // public BigDecimal getChangePrice() { // return changePrice; // } // // /** // * @param changePrice // * the changePrice to set // */ // public void setChangePrice(BigDecimal changePrice) { // this.changePrice = changePrice; // } // // /** // * @return the changePricePercent // */ // public BigDecimal getChangePricePercent() { // return changePricePercent; // } // // /** // * @param changePricePercent // * the changePricePercent to set // */ // public void setChangePricePercent(BigDecimal changePricePercent) { // this.changePricePercent = changePricePercent; // } // // /** // * @return the volume // */ // public String getVolume() { // return volume; // } // // /** // * @param volume // * the volume to set // */ // public void setVolume(String volume) { // this.volume = volume; // } // // /** // * @return the dayHigh // */ // public BigDecimal getDayHigh() { // return dayHigh; // } // // /** // * @param dayHigh // * the dayHigh to set // */ // public void setDayHigh(BigDecimal dayHigh) { // this.dayHigh = dayHigh; // } // // /** // * @return the dayLow // */ // public BigDecimal getDayLow() { // return dayLow; // } // // /** // * @param dayLow // * the dayLow to set // */ // public void setDayLow(BigDecimal dayLow) { // this.dayLow = dayLow; // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt // * the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // /** // * @return the sourceUrl // */ // public String getSourceUrl() { // return sourceUrl; // } // // /** // * @param sourceUrl the sourceUrl to set // */ // public void setSourceUrl(String sourceUrl) { // this.sourceUrl = sourceUrl; // } // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // result = prime * result // + ((updatedAt == null) ? 0 : updatedAt.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // StockDetail other = (StockDetail) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // if (updatedAt == null) { // if (other.updatedAt != null) // return false; // } else if (!updatedAt.equals(other.updatedAt)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/fetcher/QuoteFetcher.java import org.apache.http.client.HttpClient; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; package hk.reality.stock.service.fetcher; public interface QuoteFetcher { HttpClient getClient(); String getUrl(String quote);
StockDetail fetch(String quote) throws DownloadException, ParseException;
seanho/agile-stock
src/hk/reality/stock/service/fetcher/BaseIndexesFetcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // }
import hk.reality.stock.Constants; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams;
package hk.reality.stock.service.fetcher; public abstract class BaseIndexesFetcher implements IndexesFetcher { private HttpClient client; private static final int TIMEOUT = 10; public BaseIndexesFetcher() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // Path: src/hk/reality/stock/service/fetcher/BaseIndexesFetcher.java import hk.reality.stock.Constants; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; package hk.reality.stock.service.fetcher; public abstract class BaseIndexesFetcher implements IndexesFetcher { private HttpClient client; private static final int TIMEOUT = 10; public BaseIndexesFetcher() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT);
seanho/agile-stock
tests/src/hk/reality/stock/service/fetcher/Money18IndexesFetcherTest.java
// Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // }
import hk.reality.stock.model.Index; import java.util.List; import junit.framework.Assert; import android.test.AndroidTestCase; import android.util.Log;
package hk.reality.stock.service.fetcher; public class Money18IndexesFetcherTest extends AndroidTestCase { public static final String TAG = "Money18IndexesFetcherTest"; protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testFetch() { IndexesFetcher fetcher = getFetcher();
// Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // Path: tests/src/hk/reality/stock/service/fetcher/Money18IndexesFetcherTest.java import hk.reality.stock.model.Index; import java.util.List; import junit.framework.Assert; import android.test.AndroidTestCase; import android.util.Log; package hk.reality.stock.service.fetcher; public class Money18IndexesFetcherTest extends AndroidTestCase { public static final String TAG = "Money18IndexesFetcherTest"; protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testFetch() { IndexesFetcher fetcher = getFetcher();
List<Index> indexes = fetcher.fetch();
seanho/agile-stock
src/hk/reality/stock/IndexActivity.java
// Path: src/hk/reality/stock/service/fetcher/IndexesUpdateTask.java // public class IndexesUpdateTask extends AsyncTask<Void, Integer, Boolean> { // public static final String TAG = "IndexesUpdateTask"; // private IndexActivity activity; // private List<Index> results; // // private Error error; // enum Error { // ERROR_NO_NET, ERROR_DOWNLOAD, ERROR_PARSE, ERROR_UNKNOWN // } // // public IndexesUpdateTask(IndexActivity activity) { // this.activity = activity; // } // // @Override // protected Boolean doInBackground(Void ... ignored) { // Log.i(TAG, "running indexes update in background"); // if (!NetworkDetector.hasValidNetwork(activity)) { // error = Error.ERROR_NO_NET; // return Boolean.FALSE; // } // // Log.i(TAG, "start fetcher"); // IndexesFetcher fetcher = IndexesFetcherFactory.getIndexesFetcher(activity); // results = fetcher.fetch(); // // return Boolean.TRUE; // } // // private void updateIndexes(List<Index> indexes) { // IndexAdapter adapter = activity.getIndexAdapter(); // adapter.clear(); // for(Index i : indexes) { // adapter.add(i); // } // adapter.notifyDataSetChanged(); // } // // @Override // protected void onPreExecute() { // activity.getParent().setProgressBarVisibility(true); // activity.getParent().setProgressBarIndeterminateVisibility(true); // } // // @Override // protected void onCancelled() { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // } // // @Override // protected void onPostExecute(Boolean result) { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // if (result) { // Log.i(TAG, "update success, number of results ..." + results.size()); // updateIndexes(results); // } else { // Log.i(TAG, "update failure"); // } // } // } // // Path: src/hk/reality/stock/view/IndexAdapter.java // public class IndexAdapter extends ArrayAdapter<Index> { // private static final String TAG = "IndexAdapter"; // private java.text.DateFormat formatter; // // public IndexAdapter(Context context) { // super(context, 0); // formatter = DateFormat.getTimeFormat(context); // } // // @Override // public View getView(int position, View view, ViewGroup parent) { // View v = view; // if (v == null) { // LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // v = (View) vi.inflate(R.layout.index_item, null); // } // // Log.d(TAG, "prepare view for indexes"); // // prepare views // TextView name = (TextView) v.findViewById(R.id.name); // TextView price = (TextView) v.findViewById(R.id.price); // TextView change = (TextView) v.findViewById(R.id.change); // TextView volume = (TextView) v.findViewById(R.id.volume); // TextView time = (TextView) v.findViewById(R.id.time); // // // set data // Index index = getItem(position); // if (index != null) { // volume.setText(""); // name.setText(index.getName()); // price.setText(PriceFormatter.forPrice(index.getValue().doubleValue())); // // if (index.getUpdatedAt() != null) { // time.setText(formatter.format(index.getUpdatedAt().getTime())); // } else { // time.setText(""); // } // // if (index.getChange() != null) { // change.setText(String.format("%s (%s)", // PriceFormatter.forPrice(index.getChange().doubleValue()), // PriceFormatter.forPercent(index.getChangePercent().doubleValue()))); // } else { // change.setText("---- (---)"); // } // // if (index.getChange() != null && index.getChange().floatValue() > 0) { // price.setTextColor(Color.rgb(0, 213, 65)); // change.setTextColor(Color.rgb(0, 213, 65)); // } else if (index.getChange() != null && index.getChange().floatValue() < 0) { // price.setTextColor(Color.rgb(238, 30, 0)); // change.setTextColor(Color.rgb(238, 30, 0)); // } else { // price.setTextColor(Color.WHITE); // change.setTextColor(Color.WHITE); // } // // } else { // time.setText(""); // volume.setText("---"); // name.setText(""); // price.setText("----"); // change.setText("---- (---)"); // } // return v; // } // }
import hk.reality.stock.service.fetcher.IndexesUpdateTask; import hk.reality.stock.view.IndexAdapter; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView;
package hk.reality.stock; public class IndexActivity extends BaseStockActivity { public static final String TAG = "IndexActivity";
// Path: src/hk/reality/stock/service/fetcher/IndexesUpdateTask.java // public class IndexesUpdateTask extends AsyncTask<Void, Integer, Boolean> { // public static final String TAG = "IndexesUpdateTask"; // private IndexActivity activity; // private List<Index> results; // // private Error error; // enum Error { // ERROR_NO_NET, ERROR_DOWNLOAD, ERROR_PARSE, ERROR_UNKNOWN // } // // public IndexesUpdateTask(IndexActivity activity) { // this.activity = activity; // } // // @Override // protected Boolean doInBackground(Void ... ignored) { // Log.i(TAG, "running indexes update in background"); // if (!NetworkDetector.hasValidNetwork(activity)) { // error = Error.ERROR_NO_NET; // return Boolean.FALSE; // } // // Log.i(TAG, "start fetcher"); // IndexesFetcher fetcher = IndexesFetcherFactory.getIndexesFetcher(activity); // results = fetcher.fetch(); // // return Boolean.TRUE; // } // // private void updateIndexes(List<Index> indexes) { // IndexAdapter adapter = activity.getIndexAdapter(); // adapter.clear(); // for(Index i : indexes) { // adapter.add(i); // } // adapter.notifyDataSetChanged(); // } // // @Override // protected void onPreExecute() { // activity.getParent().setProgressBarVisibility(true); // activity.getParent().setProgressBarIndeterminateVisibility(true); // } // // @Override // protected void onCancelled() { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // } // // @Override // protected void onPostExecute(Boolean result) { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // if (result) { // Log.i(TAG, "update success, number of results ..." + results.size()); // updateIndexes(results); // } else { // Log.i(TAG, "update failure"); // } // } // } // // Path: src/hk/reality/stock/view/IndexAdapter.java // public class IndexAdapter extends ArrayAdapter<Index> { // private static final String TAG = "IndexAdapter"; // private java.text.DateFormat formatter; // // public IndexAdapter(Context context) { // super(context, 0); // formatter = DateFormat.getTimeFormat(context); // } // // @Override // public View getView(int position, View view, ViewGroup parent) { // View v = view; // if (v == null) { // LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // v = (View) vi.inflate(R.layout.index_item, null); // } // // Log.d(TAG, "prepare view for indexes"); // // prepare views // TextView name = (TextView) v.findViewById(R.id.name); // TextView price = (TextView) v.findViewById(R.id.price); // TextView change = (TextView) v.findViewById(R.id.change); // TextView volume = (TextView) v.findViewById(R.id.volume); // TextView time = (TextView) v.findViewById(R.id.time); // // // set data // Index index = getItem(position); // if (index != null) { // volume.setText(""); // name.setText(index.getName()); // price.setText(PriceFormatter.forPrice(index.getValue().doubleValue())); // // if (index.getUpdatedAt() != null) { // time.setText(formatter.format(index.getUpdatedAt().getTime())); // } else { // time.setText(""); // } // // if (index.getChange() != null) { // change.setText(String.format("%s (%s)", // PriceFormatter.forPrice(index.getChange().doubleValue()), // PriceFormatter.forPercent(index.getChangePercent().doubleValue()))); // } else { // change.setText("---- (---)"); // } // // if (index.getChange() != null && index.getChange().floatValue() > 0) { // price.setTextColor(Color.rgb(0, 213, 65)); // change.setTextColor(Color.rgb(0, 213, 65)); // } else if (index.getChange() != null && index.getChange().floatValue() < 0) { // price.setTextColor(Color.rgb(238, 30, 0)); // change.setTextColor(Color.rgb(238, 30, 0)); // } else { // price.setTextColor(Color.WHITE); // change.setTextColor(Color.WHITE); // } // // } else { // time.setText(""); // volume.setText("---"); // name.setText(""); // price.setText("----"); // change.setText("---- (---)"); // } // return v; // } // } // Path: src/hk/reality/stock/IndexActivity.java import hk.reality.stock.service.fetcher.IndexesUpdateTask; import hk.reality.stock.view.IndexAdapter; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; package hk.reality.stock; public class IndexActivity extends BaseStockActivity { public static final String TAG = "IndexActivity";
private IndexAdapter adapter;
seanho/agile-stock
src/hk/reality/stock/IndexActivity.java
// Path: src/hk/reality/stock/service/fetcher/IndexesUpdateTask.java // public class IndexesUpdateTask extends AsyncTask<Void, Integer, Boolean> { // public static final String TAG = "IndexesUpdateTask"; // private IndexActivity activity; // private List<Index> results; // // private Error error; // enum Error { // ERROR_NO_NET, ERROR_DOWNLOAD, ERROR_PARSE, ERROR_UNKNOWN // } // // public IndexesUpdateTask(IndexActivity activity) { // this.activity = activity; // } // // @Override // protected Boolean doInBackground(Void ... ignored) { // Log.i(TAG, "running indexes update in background"); // if (!NetworkDetector.hasValidNetwork(activity)) { // error = Error.ERROR_NO_NET; // return Boolean.FALSE; // } // // Log.i(TAG, "start fetcher"); // IndexesFetcher fetcher = IndexesFetcherFactory.getIndexesFetcher(activity); // results = fetcher.fetch(); // // return Boolean.TRUE; // } // // private void updateIndexes(List<Index> indexes) { // IndexAdapter adapter = activity.getIndexAdapter(); // adapter.clear(); // for(Index i : indexes) { // adapter.add(i); // } // adapter.notifyDataSetChanged(); // } // // @Override // protected void onPreExecute() { // activity.getParent().setProgressBarVisibility(true); // activity.getParent().setProgressBarIndeterminateVisibility(true); // } // // @Override // protected void onCancelled() { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // } // // @Override // protected void onPostExecute(Boolean result) { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // if (result) { // Log.i(TAG, "update success, number of results ..." + results.size()); // updateIndexes(results); // } else { // Log.i(TAG, "update failure"); // } // } // } // // Path: src/hk/reality/stock/view/IndexAdapter.java // public class IndexAdapter extends ArrayAdapter<Index> { // private static final String TAG = "IndexAdapter"; // private java.text.DateFormat formatter; // // public IndexAdapter(Context context) { // super(context, 0); // formatter = DateFormat.getTimeFormat(context); // } // // @Override // public View getView(int position, View view, ViewGroup parent) { // View v = view; // if (v == null) { // LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // v = (View) vi.inflate(R.layout.index_item, null); // } // // Log.d(TAG, "prepare view for indexes"); // // prepare views // TextView name = (TextView) v.findViewById(R.id.name); // TextView price = (TextView) v.findViewById(R.id.price); // TextView change = (TextView) v.findViewById(R.id.change); // TextView volume = (TextView) v.findViewById(R.id.volume); // TextView time = (TextView) v.findViewById(R.id.time); // // // set data // Index index = getItem(position); // if (index != null) { // volume.setText(""); // name.setText(index.getName()); // price.setText(PriceFormatter.forPrice(index.getValue().doubleValue())); // // if (index.getUpdatedAt() != null) { // time.setText(formatter.format(index.getUpdatedAt().getTime())); // } else { // time.setText(""); // } // // if (index.getChange() != null) { // change.setText(String.format("%s (%s)", // PriceFormatter.forPrice(index.getChange().doubleValue()), // PriceFormatter.forPercent(index.getChangePercent().doubleValue()))); // } else { // change.setText("---- (---)"); // } // // if (index.getChange() != null && index.getChange().floatValue() > 0) { // price.setTextColor(Color.rgb(0, 213, 65)); // change.setTextColor(Color.rgb(0, 213, 65)); // } else if (index.getChange() != null && index.getChange().floatValue() < 0) { // price.setTextColor(Color.rgb(238, 30, 0)); // change.setTextColor(Color.rgb(238, 30, 0)); // } else { // price.setTextColor(Color.WHITE); // change.setTextColor(Color.WHITE); // } // // } else { // time.setText(""); // volume.setText("---"); // name.setText(""); // price.setText("----"); // change.setText("---- (---)"); // } // return v; // } // }
import hk.reality.stock.service.fetcher.IndexesUpdateTask; import hk.reality.stock.view.IndexAdapter; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView;
package hk.reality.stock; public class IndexActivity extends BaseStockActivity { public static final String TAG = "IndexActivity"; private IndexAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); adapter = new IndexAdapter(this); setListAdapter(adapter); TextView empty = (TextView) findViewById(android.R.id.empty); empty.setText(R.string.msg_loading); Log.i(TAG, "start index activity");
// Path: src/hk/reality/stock/service/fetcher/IndexesUpdateTask.java // public class IndexesUpdateTask extends AsyncTask<Void, Integer, Boolean> { // public static final String TAG = "IndexesUpdateTask"; // private IndexActivity activity; // private List<Index> results; // // private Error error; // enum Error { // ERROR_NO_NET, ERROR_DOWNLOAD, ERROR_PARSE, ERROR_UNKNOWN // } // // public IndexesUpdateTask(IndexActivity activity) { // this.activity = activity; // } // // @Override // protected Boolean doInBackground(Void ... ignored) { // Log.i(TAG, "running indexes update in background"); // if (!NetworkDetector.hasValidNetwork(activity)) { // error = Error.ERROR_NO_NET; // return Boolean.FALSE; // } // // Log.i(TAG, "start fetcher"); // IndexesFetcher fetcher = IndexesFetcherFactory.getIndexesFetcher(activity); // results = fetcher.fetch(); // // return Boolean.TRUE; // } // // private void updateIndexes(List<Index> indexes) { // IndexAdapter adapter = activity.getIndexAdapter(); // adapter.clear(); // for(Index i : indexes) { // adapter.add(i); // } // adapter.notifyDataSetChanged(); // } // // @Override // protected void onPreExecute() { // activity.getParent().setProgressBarVisibility(true); // activity.getParent().setProgressBarIndeterminateVisibility(true); // } // // @Override // protected void onCancelled() { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // } // // @Override // protected void onPostExecute(Boolean result) { // activity.getParent().setProgressBarVisibility(false); // activity.getParent().setProgressBarIndeterminateVisibility(false); // if (result) { // Log.i(TAG, "update success, number of results ..." + results.size()); // updateIndexes(results); // } else { // Log.i(TAG, "update failure"); // } // } // } // // Path: src/hk/reality/stock/view/IndexAdapter.java // public class IndexAdapter extends ArrayAdapter<Index> { // private static final String TAG = "IndexAdapter"; // private java.text.DateFormat formatter; // // public IndexAdapter(Context context) { // super(context, 0); // formatter = DateFormat.getTimeFormat(context); // } // // @Override // public View getView(int position, View view, ViewGroup parent) { // View v = view; // if (v == null) { // LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // v = (View) vi.inflate(R.layout.index_item, null); // } // // Log.d(TAG, "prepare view for indexes"); // // prepare views // TextView name = (TextView) v.findViewById(R.id.name); // TextView price = (TextView) v.findViewById(R.id.price); // TextView change = (TextView) v.findViewById(R.id.change); // TextView volume = (TextView) v.findViewById(R.id.volume); // TextView time = (TextView) v.findViewById(R.id.time); // // // set data // Index index = getItem(position); // if (index != null) { // volume.setText(""); // name.setText(index.getName()); // price.setText(PriceFormatter.forPrice(index.getValue().doubleValue())); // // if (index.getUpdatedAt() != null) { // time.setText(formatter.format(index.getUpdatedAt().getTime())); // } else { // time.setText(""); // } // // if (index.getChange() != null) { // change.setText(String.format("%s (%s)", // PriceFormatter.forPrice(index.getChange().doubleValue()), // PriceFormatter.forPercent(index.getChangePercent().doubleValue()))); // } else { // change.setText("---- (---)"); // } // // if (index.getChange() != null && index.getChange().floatValue() > 0) { // price.setTextColor(Color.rgb(0, 213, 65)); // change.setTextColor(Color.rgb(0, 213, 65)); // } else if (index.getChange() != null && index.getChange().floatValue() < 0) { // price.setTextColor(Color.rgb(238, 30, 0)); // change.setTextColor(Color.rgb(238, 30, 0)); // } else { // price.setTextColor(Color.WHITE); // change.setTextColor(Color.WHITE); // } // // } else { // time.setText(""); // volume.setText("---"); // name.setText(""); // price.setText("----"); // change.setText("---- (---)"); // } // return v; // } // } // Path: src/hk/reality/stock/IndexActivity.java import hk.reality.stock.service.fetcher.IndexesUpdateTask; import hk.reality.stock.view.IndexAdapter; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; package hk.reality.stock; public class IndexActivity extends BaseStockActivity { public static final String TAG = "IndexActivity"; private IndexAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); adapter = new IndexAdapter(this); setListAdapter(adapter); TextView empty = (TextView) findViewById(android.R.id.empty); empty.setText(R.string.msg_loading); Log.i(TAG, "start index activity");
IndexesUpdateTask task = new IndexesUpdateTask(this);
seanho/agile-stock
src/hk/reality/stock/service/searcher/HkexStockSearcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log;
package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client;
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/searcher/HkexStockSearcher.java import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log; package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client;
private Lang language;
seanho/agile-stock
src/hk/reality/stock/service/searcher/HkexStockSearcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log;
package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000);
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/searcher/HkexStockSearcher.java import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log; package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000);
HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT);
seanho/agile-stock
src/hk/reality/stock/service/searcher/HkexStockSearcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log;
package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/searcher/HkexStockSearcher.java import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log; package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
public Stock searchStock(String quote) throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/service/searcher/HkexStockSearcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log;
package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/searcher/HkexStockSearcher.java import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log; package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
public Stock searchStock(String quote) throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/service/searcher/HkexStockSearcher.java
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // }
import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log;
package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
// Path: src/hk/reality/stock/Constants.java // public interface Constants { // static String USER_AGENT = "Agile Stock / 0.1"; // } // // Path: src/hk/reality/stock/model/Stock.java // public class Stock implements Serializable { // private static final long serialVersionUID = -6452165113616479803L; // private String name; // private String quote; // private StockDetail detail; // // /** // * @return the quote // */ // public String getQuote() { // return quote; // } // // /** // * @param quote // * the quote to set // */ // public void setQuote(String quote) { // this.quote = quote; // } // // /** // * @return the detail // */ // public StockDetail getDetail() { // return detail; // } // // /** // * @param detail the detail to set // */ // public void setDetail(StockDetail detail) { // this.detail = detail; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name the name to set // */ // public void setName(String name) { // this.name = name; // } // // /* (non-Javadoc) // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((quote == null) ? 0 : quote.hashCode()); // return result; // } // // /* (non-Javadoc) // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Stock other = (Stock) obj; // if (quote == null) { // if (other.quote != null) // return false; // } else if (!quote.equals(other.quote)) // return false; // return true; // } // } // // Path: src/hk/reality/stock/service/Lang.java // public enum Lang { // ENG, CHI // } // // Path: src/hk/reality/stock/service/exception/DownloadException.java // public class DownloadException extends RuntimeException { // // public DownloadException() { // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public DownloadException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public DownloadException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // // Path: src/hk/reality/stock/service/exception/ParseException.java // public class ParseException extends RuntimeException { // // public ParseException() { // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage) { // super(detailMessage); // // TODO Auto-generated constructor stub // } // // public ParseException(Throwable throwable) { // super(throwable); // // TODO Auto-generated constructor stub // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // // TODO Auto-generated constructor stub // } // // } // Path: src/hk/reality/stock/service/searcher/HkexStockSearcher.java import hk.reality.stock.Constants; import hk.reality.stock.model.Stock; import hk.reality.stock.service.Lang; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import android.util.Log; package hk.reality.stock.service.searcher; public class HkexStockSearcher implements StockSearcher { private static final String TAG = "HKEX"; private static final String BASE_URL = "http://www.hkex.com.hk/invest/company/profile_page_%s.asp?WidCoID=%s&WidCoAbbName=&Month="; private static final String BEGIN = "#66CCFF\">"; private static final String END = "</font>"; private static final String REGEXP = "(.+)\\(([0-9]{1,5})"; private static final Pattern pattern = Pattern.compile(REGEXP); private HttpClient client; private Lang language; public HkexStockSearcher(Lang language) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * 1000); HttpConnectionParams.setSoTimeout(params, 30 * 1000); HttpProtocolParams.setUserAgent(params, Constants.USER_AGENT); this.client = new DefaultHttpClient(params); this.language = language; } @Override
public Stock searchStock(String quote) throws DownloadException, ParseException {
seanho/agile-stock
src/hk/reality/stock/view/IndexAdapter.java
// Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/utils/PriceFormatter.java // public class PriceFormatter { // private static final DecimalFormat priceFormat = new DecimalFormat("#,##0.###"); // private static final DecimalFormat percentFormat = new DecimalFormat("#,##0.00"); // // public static String forPrice(double value) { // return priceFormat.format(value); // } // // public static String forPercent(double value) { // return percentFormat.format(value); // } // }
import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.utils.PriceFormatter; import android.content.Context; import android.graphics.Color; import android.text.format.DateFormat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView;
package hk.reality.stock.view; public class IndexAdapter extends ArrayAdapter<Index> { private static final String TAG = "IndexAdapter"; private java.text.DateFormat formatter; public IndexAdapter(Context context) { super(context, 0); formatter = DateFormat.getTimeFormat(context); } @Override public View getView(int position, View view, ViewGroup parent) { View v = view; if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = (View) vi.inflate(R.layout.index_item, null); } Log.d(TAG, "prepare view for indexes"); // prepare views TextView name = (TextView) v.findViewById(R.id.name); TextView price = (TextView) v.findViewById(R.id.price); TextView change = (TextView) v.findViewById(R.id.change); TextView volume = (TextView) v.findViewById(R.id.volume); TextView time = (TextView) v.findViewById(R.id.time); // set data Index index = getItem(position); if (index != null) { volume.setText(""); name.setText(index.getName());
// Path: src/hk/reality/stock/model/Index.java // public class Index { // private String name; // // private BigDecimal value; // private BigDecimal change; // private BigDecimal changePercent; // private Calendar updatedAt; // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @return the change // */ // public BigDecimal getChange() { // return change; // } // // /** // * @param change // * the change to set // */ // public void setChange(BigDecimal change) { // this.change = change; // } // // /** // * @return the changePercent // */ // public BigDecimal getChangePercent() { // return changePercent; // } // // /** // * @param changePercent // * the changePercent to set // */ // public void setChangePercent(BigDecimal changePercent) { // this.changePercent = changePercent; // } // // /** // * @return the value // */ // public BigDecimal getValue() { // return value; // } // // /** // * @param value the value to set // */ // public void setValue(BigDecimal value) { // this.value = value; // } // // /* (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return String.format( // "Index [name=%s, value=%s, change=%s, changePercent=%s]", name, // value, change, changePercent); // } // // /** // * @return the updatedAt // */ // public Calendar getUpdatedAt() { // return updatedAt; // } // // /** // * @param updatedAt the updatedAt to set // */ // public void setUpdatedAt(Calendar updatedAt) { // this.updatedAt = updatedAt; // } // // // // } // // Path: src/hk/reality/utils/PriceFormatter.java // public class PriceFormatter { // private static final DecimalFormat priceFormat = new DecimalFormat("#,##0.###"); // private static final DecimalFormat percentFormat = new DecimalFormat("#,##0.00"); // // public static String forPrice(double value) { // return priceFormat.format(value); // } // // public static String forPercent(double value) { // return percentFormat.format(value); // } // } // Path: src/hk/reality/stock/view/IndexAdapter.java import hk.reality.stock.R; import hk.reality.stock.model.Index; import hk.reality.utils.PriceFormatter; import android.content.Context; import android.graphics.Color; import android.text.format.DateFormat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; package hk.reality.stock.view; public class IndexAdapter extends ArrayAdapter<Index> { private static final String TAG = "IndexAdapter"; private java.text.DateFormat formatter; public IndexAdapter(Context context) { super(context, 0); formatter = DateFormat.getTimeFormat(context); } @Override public View getView(int position, View view, ViewGroup parent) { View v = view; if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = (View) vi.inflate(R.layout.index_item, null); } Log.d(TAG, "prepare view for indexes"); // prepare views TextView name = (TextView) v.findViewById(R.id.name); TextView price = (TextView) v.findViewById(R.id.price); TextView change = (TextView) v.findViewById(R.id.change); TextView volume = (TextView) v.findViewById(R.id.volume); TextView time = (TextView) v.findViewById(R.id.time); // set data Index index = getItem(position); if (index != null) { volume.setText(""); name.setText(index.getName());
price.setText(PriceFormatter.forPrice(index.getValue().doubleValue()));
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/registration/OnRegistrationCompleteEvent.java
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // }
import java.util.Locale; import org.springframework.context.ApplicationEvent; import com.login.persistence.model.User;
package com.login.registration; @SuppressWarnings("serial") public class OnRegistrationCompleteEvent extends ApplicationEvent { private final String appUrl; private final Locale locale;
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // } // Path: src/main/java/com/login/registration/OnRegistrationCompleteEvent.java import java.util.Locale; import org.springframework.context.ApplicationEvent; import com.login.persistence.model.User; package com.login.registration; @SuppressWarnings("serial") public class OnRegistrationCompleteEvent extends ApplicationEvent { private final String appUrl; private final Locale locale;
private final User user;
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/validation/PasswordMatchesValidator.java
// Path: src/main/java/com/login/persistence/service/UserDto.java // @PasswordMatches // public class UserDto { // @NotNull // @Size(min = 1) // private String firstName; // // @NotNull // @Size(min = 1) // private String lastName; // // @ValidPassword // private String password; // // @NotNull // @Size(min = 1) // private String matchingPassword; // // @ValidEmail // @NotNull // @Size(min = 1) // private String email; // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // private Integer role; // // public Integer getRole() { // return role; // } // // public void setRole(final Integer role) { // this.role = role; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public String getMatchingPassword() { // return matchingPassword; // } // // public void setMatchingPassword(final String matchingPassword) { // this.matchingPassword = matchingPassword; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]").append("[password").append(password).append("]"); // return builder.toString(); // } // }
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.login.persistence.service.UserDto;
package com.login.validation; public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { @Override public void initialize(final PasswordMatches constraintAnnotation) { // } @Override public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
// Path: src/main/java/com/login/persistence/service/UserDto.java // @PasswordMatches // public class UserDto { // @NotNull // @Size(min = 1) // private String firstName; // // @NotNull // @Size(min = 1) // private String lastName; // // @ValidPassword // private String password; // // @NotNull // @Size(min = 1) // private String matchingPassword; // // @ValidEmail // @NotNull // @Size(min = 1) // private String email; // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // private Integer role; // // public Integer getRole() { // return role; // } // // public void setRole(final Integer role) { // this.role = role; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public String getMatchingPassword() { // return matchingPassword; // } // // public void setMatchingPassword(final String matchingPassword) { // this.matchingPassword = matchingPassword; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]").append("[password").append(password).append("]"); // return builder.toString(); // } // } // Path: src/main/java/com/login/validation/PasswordMatchesValidator.java import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.login.persistence.service.UserDto; package com.login.validation; public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { @Override public void initialize(final PasswordMatches constraintAnnotation) { // } @Override public boolean isValid(final Object obj, final ConstraintValidatorContext context) {
final UserDto user = (UserDto) obj;
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/spring/MvcConfig.java
// Path: src/main/java/com/login/validation/EmailValidator.java // public class EmailValidator implements ConstraintValidator<ValidEmail, String> { // private Pattern pattern; // private Matcher matcher; // private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // // @Override // public void initialize(final ValidEmail constraintAnnotation) { // } // // @Override // public boolean isValid(final String username, final ConstraintValidatorContext context) { // return (validateEmail(username)); // } // // private boolean validateEmail(final String email) { // pattern = Pattern.compile(EMAIL_PATTERN); // matcher = pattern.matcher(email); // return matcher.matches(); // } // } // // Path: src/main/java/com/login/validation/PasswordMatchesValidator.java // public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { // // @Override // public void initialize(final PasswordMatches constraintAnnotation) { // // // } // // @Override // public boolean isValid(final Object obj, final ConstraintValidatorContext context) { // final UserDto user = (UserDto) obj; // return user.getPassword().equals(user.getMatchingPassword()); // } // // }
import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.login.validation.EmailValidator; import com.login.validation.PasswordMatchesValidator;
// beans @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Bean public LocaleResolver localeResolver() { final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); return cookieLocaleResolver; } @Bean public MessageSource messageSource() { final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); return messageSource; } @Bean
// Path: src/main/java/com/login/validation/EmailValidator.java // public class EmailValidator implements ConstraintValidator<ValidEmail, String> { // private Pattern pattern; // private Matcher matcher; // private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // // @Override // public void initialize(final ValidEmail constraintAnnotation) { // } // // @Override // public boolean isValid(final String username, final ConstraintValidatorContext context) { // return (validateEmail(username)); // } // // private boolean validateEmail(final String email) { // pattern = Pattern.compile(EMAIL_PATTERN); // matcher = pattern.matcher(email); // return matcher.matches(); // } // } // // Path: src/main/java/com/login/validation/PasswordMatchesValidator.java // public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { // // @Override // public void initialize(final PasswordMatches constraintAnnotation) { // // // } // // @Override // public boolean isValid(final Object obj, final ConstraintValidatorContext context) { // final UserDto user = (UserDto) obj; // return user.getPassword().equals(user.getMatchingPassword()); // } // // } // Path: src/main/java/com/login/spring/MvcConfig.java import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.login.validation.EmailValidator; import com.login.validation.PasswordMatchesValidator; // beans @Bean public ViewResolver viewResolver() { final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Bean public LocaleResolver localeResolver() { final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); return cookieLocaleResolver; } @Bean public MessageSource messageSource() { final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); return messageSource; } @Bean
public EmailValidator usernameValidator() {
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/spring/MvcConfig.java
// Path: src/main/java/com/login/validation/EmailValidator.java // public class EmailValidator implements ConstraintValidator<ValidEmail, String> { // private Pattern pattern; // private Matcher matcher; // private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // // @Override // public void initialize(final ValidEmail constraintAnnotation) { // } // // @Override // public boolean isValid(final String username, final ConstraintValidatorContext context) { // return (validateEmail(username)); // } // // private boolean validateEmail(final String email) { // pattern = Pattern.compile(EMAIL_PATTERN); // matcher = pattern.matcher(email); // return matcher.matches(); // } // } // // Path: src/main/java/com/login/validation/PasswordMatchesValidator.java // public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { // // @Override // public void initialize(final PasswordMatches constraintAnnotation) { // // // } // // @Override // public boolean isValid(final Object obj, final ConstraintValidatorContext context) { // final UserDto user = (UserDto) obj; // return user.getPassword().equals(user.getMatchingPassword()); // } // // }
import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.login.validation.EmailValidator; import com.login.validation.PasswordMatchesValidator;
final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Bean public LocaleResolver localeResolver() { final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); return cookieLocaleResolver; } @Bean public MessageSource messageSource() { final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); return messageSource; } @Bean public EmailValidator usernameValidator() { return new EmailValidator(); } @Bean
// Path: src/main/java/com/login/validation/EmailValidator.java // public class EmailValidator implements ConstraintValidator<ValidEmail, String> { // private Pattern pattern; // private Matcher matcher; // private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; // // @Override // public void initialize(final ValidEmail constraintAnnotation) { // } // // @Override // public boolean isValid(final String username, final ConstraintValidatorContext context) { // return (validateEmail(username)); // } // // private boolean validateEmail(final String email) { // pattern = Pattern.compile(EMAIL_PATTERN); // matcher = pattern.matcher(email); // return matcher.matches(); // } // } // // Path: src/main/java/com/login/validation/PasswordMatchesValidator.java // public class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> { // // @Override // public void initialize(final PasswordMatches constraintAnnotation) { // // // } // // @Override // public boolean isValid(final Object obj, final ConstraintValidatorContext context) { // final UserDto user = (UserDto) obj; // return user.getPassword().equals(user.getMatchingPassword()); // } // // } // Path: src/main/java/com/login/spring/MvcConfig.java import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import com.login.validation.EmailValidator; import com.login.validation.PasswordMatchesValidator; final InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } @Bean public LocaleResolver localeResolver() { final CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); cookieLocaleResolver.setDefaultLocale(Locale.ENGLISH); return cookieLocaleResolver; } @Bean public MessageSource messageSource() { final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setUseCodeAsDefaultMessage(true); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); return messageSource; } @Bean public EmailValidator usernameValidator() { return new EmailValidator(); } @Bean
public PasswordMatchesValidator passwordMatchesValidator() {
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/web/error/RestResponseEntityExceptionHandler.java
// Path: src/main/java/com/login/web/util/GenericResponse.java // public class GenericResponse { // private String message; // private String error; // // public GenericResponse(final String message) { // super(); // this.message = message; // } // // public GenericResponse(final String message, final String error) { // super(); // this.message = message; // this.error = error; // } // // public GenericResponse(final List<FieldError> fieldErrors, final List<ObjectError> globalErrors) { // super(); // final ObjectMapper mapper = new ObjectMapper(); // try { // this.message = mapper.writeValueAsString(fieldErrors); // this.error = mapper.writeValueAsString(globalErrors); // } catch (final JsonProcessingException e) { // this.message = ""; // this.error = ""; // } // } // // public String getMessage() { // return message; // } // // public void setMessage(final String message) { // this.message = message; // } // // public String getError() { // return error; // } // // public void setError(final String error) { // this.error = error; // } // // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mail.MailAuthenticationException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.login.web.util.GenericResponse;
package com.login.web.error; @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @Autowired private MessageSource messages; public RestResponseEntityExceptionHandler() { super(); } // API // 400 @Override protected ResponseEntity<Object> handleBindException(final BindException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.error("400 Status Code", ex); final BindingResult result = ex.getBindingResult();
// Path: src/main/java/com/login/web/util/GenericResponse.java // public class GenericResponse { // private String message; // private String error; // // public GenericResponse(final String message) { // super(); // this.message = message; // } // // public GenericResponse(final String message, final String error) { // super(); // this.message = message; // this.error = error; // } // // public GenericResponse(final List<FieldError> fieldErrors, final List<ObjectError> globalErrors) { // super(); // final ObjectMapper mapper = new ObjectMapper(); // try { // this.message = mapper.writeValueAsString(fieldErrors); // this.error = mapper.writeValueAsString(globalErrors); // } catch (final JsonProcessingException e) { // this.message = ""; // this.error = ""; // } // } // // public String getMessage() { // return message; // } // // public void setMessage(final String message) { // this.message = message; // } // // public String getError() { // return error; // } // // public void setError(final String error) { // this.error = error; // } // // } // Path: src/main/java/com/login/web/error/RestResponseEntityExceptionHandler.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.mail.MailAuthenticationException; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.login.web.util.GenericResponse; package com.login.web.error; @ControllerAdvice public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @Autowired private MessageSource messages; public RestResponseEntityExceptionHandler() { super(); } // API // 400 @Override protected ResponseEntity<Object> handleBindException(final BindException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.error("400 Status Code", ex); final BindingResult result = ex.getBindingResult();
final GenericResponse bodyOfResponse = new GenericResponse(result.getFieldErrors(), result.getGlobalErrors());
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/registration/listener/RegistrationListener.java
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/login/persistence/service/IUserService.java // public interface IUserService { // // User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; // // User getUser(String verificationToken); // // void saveRegisteredUser(User user); // // void deleteUser(User user); // // void createVerificationTokenForUser(User user, String token); // // VerificationToken getVerificationToken(String VerificationToken); // // VerificationToken generateNewVerificationToken(String token); // // void createPasswordResetTokenForUser(User user, String token); // // User findUserByEmail(String email); // // PasswordResetToken getPasswordResetToken(String token); // // User getUserByPasswordResetToken(String token); // // User getUserByID(long id); // // void changeUserPassword(User user, String password); // // boolean checkIfValidOldPassword(User user, String password); // // } // // Path: src/main/java/com/login/registration/OnRegistrationCompleteEvent.java // @SuppressWarnings("serial") // public class OnRegistrationCompleteEvent extends ApplicationEvent { // // private final String appUrl; // private final Locale locale; // private final User user; // // public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) { // super(user); // this.user = user; // this.locale = locale; // this.appUrl = appUrl; // } // // // // // public String getAppUrl() { // return appUrl; // } // // public Locale getLocale() { // return locale; // } // // public User getUser() { // return user; // } // // }
import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.MessageSource; import org.springframework.core.env.Environment; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import com.login.persistence.model.User; import com.login.persistence.service.IUserService; import com.login.registration.OnRegistrationCompleteEvent;
package com.login.registration.listener; @Component public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> { @Autowired
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/login/persistence/service/IUserService.java // public interface IUserService { // // User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; // // User getUser(String verificationToken); // // void saveRegisteredUser(User user); // // void deleteUser(User user); // // void createVerificationTokenForUser(User user, String token); // // VerificationToken getVerificationToken(String VerificationToken); // // VerificationToken generateNewVerificationToken(String token); // // void createPasswordResetTokenForUser(User user, String token); // // User findUserByEmail(String email); // // PasswordResetToken getPasswordResetToken(String token); // // User getUserByPasswordResetToken(String token); // // User getUserByID(long id); // // void changeUserPassword(User user, String password); // // boolean checkIfValidOldPassword(User user, String password); // // } // // Path: src/main/java/com/login/registration/OnRegistrationCompleteEvent.java // @SuppressWarnings("serial") // public class OnRegistrationCompleteEvent extends ApplicationEvent { // // private final String appUrl; // private final Locale locale; // private final User user; // // public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) { // super(user); // this.user = user; // this.locale = locale; // this.appUrl = appUrl; // } // // // // // public String getAppUrl() { // return appUrl; // } // // public Locale getLocale() { // return locale; // } // // public User getUser() { // return user; // } // // } // Path: src/main/java/com/login/registration/listener/RegistrationListener.java import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.MessageSource; import org.springframework.core.env.Environment; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import com.login.persistence.model.User; import com.login.persistence.service.IUserService; import com.login.registration.OnRegistrationCompleteEvent; package com.login.registration.listener; @Component public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> { @Autowired
private IUserService service;
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/registration/listener/RegistrationListener.java
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/login/persistence/service/IUserService.java // public interface IUserService { // // User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; // // User getUser(String verificationToken); // // void saveRegisteredUser(User user); // // void deleteUser(User user); // // void createVerificationTokenForUser(User user, String token); // // VerificationToken getVerificationToken(String VerificationToken); // // VerificationToken generateNewVerificationToken(String token); // // void createPasswordResetTokenForUser(User user, String token); // // User findUserByEmail(String email); // // PasswordResetToken getPasswordResetToken(String token); // // User getUserByPasswordResetToken(String token); // // User getUserByID(long id); // // void changeUserPassword(User user, String password); // // boolean checkIfValidOldPassword(User user, String password); // // } // // Path: src/main/java/com/login/registration/OnRegistrationCompleteEvent.java // @SuppressWarnings("serial") // public class OnRegistrationCompleteEvent extends ApplicationEvent { // // private final String appUrl; // private final Locale locale; // private final User user; // // public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) { // super(user); // this.user = user; // this.locale = locale; // this.appUrl = appUrl; // } // // // // // public String getAppUrl() { // return appUrl; // } // // public Locale getLocale() { // return locale; // } // // public User getUser() { // return user; // } // // }
import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.MessageSource; import org.springframework.core.env.Environment; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import com.login.persistence.model.User; import com.login.persistence.service.IUserService; import com.login.registration.OnRegistrationCompleteEvent;
package com.login.registration.listener; @Component public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> { @Autowired private IUserService service; @Autowired private MessageSource messages; @Autowired private JavaMailSender mailSender; @Autowired private Environment env; // API @Override public void onApplicationEvent(final OnRegistrationCompleteEvent event) { this.confirmRegistration(event); } private void confirmRegistration(final OnRegistrationCompleteEvent event) {
// Path: src/main/java/com/login/persistence/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // // private String firstName; // // private String lastName; // // private String email; // // @Column(length = 60) // private String password; // // private boolean enabled; // // private boolean tokenExpired; // // // // // @ManyToMany // @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") , inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) // private Collection<Role> roles; // // public User() { // super(); // this.enabled = false; // this.tokenExpired = false; // } // // public Long getId() { // return id; // } // // public void setId(final Long id) { // this.id = id; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getEmail() { // return email; // } // // public void setEmail(final String username) { // this.email = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public Collection<Role> getRoles() { // return roles; // } // // public void setRoles(final Collection<Role> roles) { // this.roles = roles; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(final boolean enabled) { // this.enabled = enabled; // } // // public boolean isTokenExpired() { // return tokenExpired; // } // // public void setTokenExpired(final boolean expired) { // this.tokenExpired = expired; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((email == null) ? 0 : email.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final User user = (User) obj; // if (!email.equals(user.email)) { // return false; // } // return true; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); // return builder.toString(); // } // // } // // Path: src/main/java/com/login/persistence/service/IUserService.java // public interface IUserService { // // User registerNewUserAccount(UserDto accountDto) throws EmailExistsException; // // User getUser(String verificationToken); // // void saveRegisteredUser(User user); // // void deleteUser(User user); // // void createVerificationTokenForUser(User user, String token); // // VerificationToken getVerificationToken(String VerificationToken); // // VerificationToken generateNewVerificationToken(String token); // // void createPasswordResetTokenForUser(User user, String token); // // User findUserByEmail(String email); // // PasswordResetToken getPasswordResetToken(String token); // // User getUserByPasswordResetToken(String token); // // User getUserByID(long id); // // void changeUserPassword(User user, String password); // // boolean checkIfValidOldPassword(User user, String password); // // } // // Path: src/main/java/com/login/registration/OnRegistrationCompleteEvent.java // @SuppressWarnings("serial") // public class OnRegistrationCompleteEvent extends ApplicationEvent { // // private final String appUrl; // private final Locale locale; // private final User user; // // public OnRegistrationCompleteEvent(final User user, final Locale locale, final String appUrl) { // super(user); // this.user = user; // this.locale = locale; // this.appUrl = appUrl; // } // // // // // public String getAppUrl() { // return appUrl; // } // // public Locale getLocale() { // return locale; // } // // public User getUser() { // return user; // } // // } // Path: src/main/java/com/login/registration/listener/RegistrationListener.java import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.MessageSource; import org.springframework.core.env.Environment; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Component; import com.login.persistence.model.User; import com.login.persistence.service.IUserService; import com.login.registration.OnRegistrationCompleteEvent; package com.login.registration.listener; @Component public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> { @Autowired private IUserService service; @Autowired private MessageSource messages; @Autowired private JavaMailSender mailSender; @Autowired private Environment env; // API @Override public void onApplicationEvent(final OnRegistrationCompleteEvent event) { this.confirmRegistration(event); } private void confirmRegistration(final OnRegistrationCompleteEvent event) {
final User user = event.getUser();
RamuRChenchaiah/SpringSecurity-registration-login
src/main/java/com/login/validation/UserValidator.java
// Path: src/main/java/com/login/persistence/service/UserDto.java // @PasswordMatches // public class UserDto { // @NotNull // @Size(min = 1) // private String firstName; // // @NotNull // @Size(min = 1) // private String lastName; // // @ValidPassword // private String password; // // @NotNull // @Size(min = 1) // private String matchingPassword; // // @ValidEmail // @NotNull // @Size(min = 1) // private String email; // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // private Integer role; // // public Integer getRole() { // return role; // } // // public void setRole(final Integer role) { // this.role = role; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public String getMatchingPassword() { // return matchingPassword; // } // // public void setMatchingPassword(final String matchingPassword) { // this.matchingPassword = matchingPassword; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]").append("[password").append(password).append("]"); // return builder.toString(); // } // }
import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.login.persistence.service.UserDto;
package com.login.validation; public class UserValidator implements Validator { @Override public boolean supports(final Class<?> clazz) {
// Path: src/main/java/com/login/persistence/service/UserDto.java // @PasswordMatches // public class UserDto { // @NotNull // @Size(min = 1) // private String firstName; // // @NotNull // @Size(min = 1) // private String lastName; // // @ValidPassword // private String password; // // @NotNull // @Size(min = 1) // private String matchingPassword; // // @ValidEmail // @NotNull // @Size(min = 1) // private String email; // // public String getEmail() { // return email; // } // // public void setEmail(final String email) { // this.email = email; // } // // private Integer role; // // public Integer getRole() { // return role; // } // // public void setRole(final Integer role) { // this.role = role; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(final String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(final String lastName) { // this.lastName = lastName; // } // // public String getPassword() { // return password; // } // // public void setPassword(final String password) { // this.password = password; // } // // public String getMatchingPassword() { // return matchingPassword; // } // // public void setMatchingPassword(final String matchingPassword) { // this.matchingPassword = matchingPassword; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[email").append(email).append("]").append("[password").append(password).append("]"); // return builder.toString(); // } // } // Path: src/main/java/com/login/validation/UserValidator.java import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.login.persistence.service.UserDto; package com.login.validation; public class UserValidator implements Validator { @Override public boolean supports(final Class<?> clazz) {
return UserDto.class.isAssignableFrom(clazz);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GroupRequest.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress;
/* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupRequest { private int gr_interface = 0; private InetAddress gr_group = null; public GroupRequest (int if_index, InetAddress mcastaddr) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GroupRequest.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; /* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupRequest { private int gr_interface = 0; private InetAddress gr_group = null; public GroupRequest (int if_index, InetAddress mcastaddr) {
checkNotNull (mcastaddr);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GroupRequest.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress;
/* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupRequest { private int gr_interface = 0; private InetAddress gr_group = null; public GroupRequest (int if_index, InetAddress mcastaddr) { checkNotNull (mcastaddr);
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GroupRequest.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; /* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupRequest { private int gr_interface = 0; private InetAddress gr_group = null; public GroupRequest (int if_index, InetAddress mcastaddr) { checkNotNull (mcastaddr);
checkArgument (mcastaddr.isMulticastAddress());
steve-o/javapgm
src/main/java/hk/miru/javapgm/PollResponsePacket.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull;
/* Poll-response or POLR packet. */ package hk.miru.javapgm; public class PollResponsePacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int POLR_SQN_OFFSET = 0; private static final int POLR_ROUND_OFFSET = 4; private static final int POLR_RESERVED_OFFSET = 6; @SuppressWarnings("unused") private static final int POLR_OPTIONS_OFFSET = 8; public PollResponsePacket (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/PollResponsePacket.java import static hk.miru.javapgm.Preconditions.checkNotNull; /* Poll-response or POLR packet. */ package hk.miru.javapgm; public class PollResponsePacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int POLR_SQN_OFFSET = 0; private static final int POLR_ROUND_OFFSET = 4; private static final int POLR_RESERVED_OFFSET = 6; @SuppressWarnings("unused") private static final int POLR_OPTIONS_OFFSET = 8; public PollResponsePacket (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Ints.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.Collection;
/* */ package hk.miru.javapgm; public final class Ints { private Ints() {} public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } public static int[] toArray(Collection<? extends Number> collection) { Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize)
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Ints.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.Collection; /* */ package hk.miru.javapgm; public final class Ints { private Ints() {} public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } public static int[] toArray(Collection<? extends Number> collection) { Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
steve-o/javapgm
src/main/java/hk/miru/javapgm/Peer.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; import java.util.List; import java.util.Queue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* A peer in the context of the sock is another party on the network sending PGM * packets. */ package hk.miru.javapgm; public class Peer { private Logger LOG = LogManager.getLogger (Peer.class.getName()); private TransportSessionId tsi = null; private InetAddress group_nla = null; private InetAddress nla = null, local_nla = null; private long lastPacketTimestamp = 0; private SequenceNumber spm_sqn = null; private ReceiveWindow window; private boolean hasPendingLinkData = false; private long lastCommit = 0; private long lostCount = 0; private long lastCumulativeLosses = 0; private long spmrExpiration = 0; private long expiration = 0; public Peer ( Socket sock, TransportSessionId tsi, InetAddress src_addr, InetAddress dst_addr, long now ) { /* Pre-conditions */
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Peer.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; import java.util.List; import java.util.Queue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* A peer in the context of the sock is another party on the network sending PGM * packets. */ package hk.miru.javapgm; public class Peer { private Logger LOG = LogManager.getLogger (Peer.class.getName()); private TransportSessionId tsi = null; private InetAddress group_nla = null; private InetAddress nla = null, local_nla = null; private long lastPacketTimestamp = 0; private SequenceNumber spm_sqn = null; private ReceiveWindow window; private boolean hasPendingLinkData = false; private long lastCommit = 0; private long lostCount = 0; private long lastCumulativeLosses = 0; private long spmrExpiration = 0; private long expiration = 0; public Peer ( Socket sock, TransportSessionId tsi, InetAddress src_addr, InetAddress dst_addr, long now ) { /* Pre-conditions */
checkNotNull (sock);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SocketBuffer.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager;
private byte[] _buf = null; private int _head = 0; private int _data = 0; private int _tail = 0; private int _end = 0; private AtomicInteger _users = new AtomicInteger (0); public SocketBuffer (int size) { this._buf = new byte[size]; this._users.lazySet (1); this._head = 0; this._data = this._tail = this._head; this._end = size; } public void setSocket (hk.miru.javapgm.Socket socket) { this._socket = socket; } public long getTimestamp() { return this._timestamp; } public void setTimestamp (long timestamp) { this._timestamp = timestamp; } public void setTransportSessionId (TransportSessionId tsi) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SocketBuffer.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager; private byte[] _buf = null; private int _head = 0; private int _data = 0; private int _tail = 0; private int _end = 0; private AtomicInteger _users = new AtomicInteger (0); public SocketBuffer (int size) { this._buf = new byte[size]; this._users.lazySet (1); this._head = 0; this._data = this._tail = this._head; this._end = size; } public void setSocket (hk.miru.javapgm.Socket socket) { this._socket = socket; } public long getTimestamp() { return this._timestamp; } public void setTimestamp (long timestamp) { this._timestamp = timestamp; } public void setTransportSessionId (TransportSessionId tsi) {
checkNotNull (tsi);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SocketBuffer.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager;
/* TODO: hashCode has limited meaning with nullable or wait-state SKBs. */ public byte[] getRawBytes() { return this._buf; } public int getDataOffset() { return this._data; } public int getLength() { return this._len; } /* Increase reference count */ public SocketBuffer get() { this._users.incrementAndGet(); return this; } public void free() { this._users.decrementAndGet(); } /* Add data */ public void put (int len) { this._tail += len; this._len += len;
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SocketBuffer.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager; /* TODO: hashCode has limited meaning with nullable or wait-state SKBs. */ public byte[] getRawBytes() { return this._buf; } public int getDataOffset() { return this._data; } public int getLength() { return this._len; } /* Increase reference count */ public SocketBuffer get() { this._users.incrementAndGet(); return this; } public void free() { this._users.decrementAndGet(); } /* Add data */ public void put (int len) { this._tail += len; this._len += len;
checkArgument (this._tail <= this._end);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GroupSourceRequest.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import javax.annotation.Nullable; import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress;
/* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupSourceRequest implements Comparable<GroupSourceRequest> { private int gsr_interface = 0; private InetAddress gsr_group = null; private InetAddress gsr_source = null; public GroupSourceRequest (int if_index, InetAddress mcastaddr, @Nullable InetAddress srcaddr) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GroupSourceRequest.java import javax.annotation.Nullable; import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; /* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupSourceRequest implements Comparable<GroupSourceRequest> { private int gsr_interface = 0; private InetAddress gsr_group = null; private InetAddress gsr_source = null; public GroupSourceRequest (int if_index, InetAddress mcastaddr, @Nullable InetAddress srcaddr) {
checkNotNull (mcastaddr);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GroupSourceRequest.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import javax.annotation.Nullable; import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress;
/* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupSourceRequest implements Comparable<GroupSourceRequest> { private int gsr_interface = 0; private InetAddress gsr_group = null; private InetAddress gsr_source = null; public GroupSourceRequest (int if_index, InetAddress mcastaddr, @Nullable InetAddress srcaddr) { checkNotNull (mcastaddr);
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GroupSourceRequest.java import javax.annotation.Nullable; import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.InetAddress; /* Sections 5 and 8.2 of RFC 3678: Multicast group request. */ package hk.miru.javapgm; public class GroupSourceRequest implements Comparable<GroupSourceRequest> { private int gsr_interface = 0; private InetAddress gsr_group = null; private InetAddress gsr_source = null; public GroupSourceRequest (int if_index, InetAddress mcastaddr, @Nullable InetAddress srcaddr) { checkNotNull (mcastaddr);
checkArgument (mcastaddr.isMulticastAddress());
steve-o/javapgm
src/main/java/hk/miru/javapgm/OriginalData.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.ProtocolFamily;
/* Original data or ODATA packet. Used for wrapping first tranmission of data * on the wire. */ package hk.miru.javapgm; public class OriginalData { protected SocketBuffer _skb = null; protected int _offset = 0; public static final int SIZEOF_DATA_HEADER = 8; private static final int DATA_SQN_OFFSET = 0; private static final int DATA_TRAIL_OFFSET = 4; private static final int DATA_OPTIONS_OFFSET = SIZEOF_DATA_HEADER; private static final int OPT_TOTAL_LENGTH_OFFSET = 2; public OriginalData (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OriginalData.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.ProtocolFamily; /* Original data or ODATA packet. Used for wrapping first tranmission of data * on the wire. */ package hk.miru.javapgm; public class OriginalData { protected SocketBuffer _skb = null; protected int _offset = 0; public static final int SIZEOF_DATA_HEADER = 8; private static final int DATA_SQN_OFFSET = 0; private static final int DATA_TRAIL_OFFSET = 4; private static final int DATA_OPTIONS_OFFSET = SIZEOF_DATA_HEADER; private static final int OPT_TOTAL_LENGTH_OFFSET = 2; public OriginalData (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/OptionNakList.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM Option NAK List Extension. */ package hk.miru.javapgm; public class OptionNakList { protected SocketBuffer _skb = null; protected int _offset = 0; protected int _length = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_SQN_OFFSET = 4; private static final int SIZEOF_PGM_OPT_NAK_LIST_HEADER = 4; private static final int SIZEOF_PGM_SQN = 4; public OptionNakList (SocketBuffer skb, int offset, int length) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OptionNakList.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM Option NAK List Extension. */ package hk.miru.javapgm; public class OptionNakList { protected SocketBuffer _skb = null; protected int _offset = 0; protected int _length = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_SQN_OFFSET = 4; private static final int SIZEOF_PGM_OPT_NAK_LIST_HEADER = 4; private static final int SIZEOF_PGM_SQN = 4; public OptionNakList (SocketBuffer skb, int offset, int length) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/OptionNakList.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM Option NAK List Extension. */ package hk.miru.javapgm; public class OptionNakList { protected SocketBuffer _skb = null; protected int _offset = 0; protected int _length = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_SQN_OFFSET = 4; private static final int SIZEOF_PGM_OPT_NAK_LIST_HEADER = 4; private static final int SIZEOF_PGM_SQN = 4; public OptionNakList (SocketBuffer skb, int offset, int length) { checkNotNull (skb); this._skb = skb; this._offset = offset; this._length = length; } public static OptionNakList create (SocketBuffer skb, int offset, int count) { OptionNakList optNakList = new OptionNakList (skb, offset, calculateLength (count)); skb.setUnsignedByte (offset + OPT_TYPE_OFFSET, OptionHeader.OPT_NAK_LIST); skb.setUnsignedByte (offset + OPT_LENGTH_OFFSET, optNakList.getLength()); skb.reserve (optNakList.getLength()); return optNakList; } public int getOffset() { return this._offset; } public int getLength() { return this._length; } private static int calculateLength (int count) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OptionNakList.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM Option NAK List Extension. */ package hk.miru.javapgm; public class OptionNakList { protected SocketBuffer _skb = null; protected int _offset = 0; protected int _length = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_SQN_OFFSET = 4; private static final int SIZEOF_PGM_OPT_NAK_LIST_HEADER = 4; private static final int SIZEOF_PGM_SQN = 4; public OptionNakList (SocketBuffer skb, int offset, int length) { checkNotNull (skb); this._skb = skb; this._offset = offset; this._length = length; } public static OptionNakList create (SocketBuffer skb, int offset, int count) { OptionNakList optNakList = new OptionNakList (skb, offset, calculateLength (count)); skb.setUnsignedByte (offset + OPT_TYPE_OFFSET, OptionHeader.OPT_NAK_LIST); skb.setUnsignedByte (offset + OPT_LENGTH_OFFSET, optNakList.getLength()); skb.reserve (optNakList.getLength()); return optNakList; } public int getOffset() { return this._offset; } public int getLength() { return this._length; } private static int calculateLength (int count) {
checkArgument (count > 0 && count <= 62);
steve-o/javapgm
src/main/java/hk/miru/javapgm/OptionHeader.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM Option Extension. */ package hk.miru.javapgm; public class OptionHeader { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; public static final int OPT_TOTAL_LENGTH_OFFSET = 2; private static final int OPT_MASK = 0x7f; private static final int OPT_END = 0x80; public static final int OPT_LENGTH = 0x00; public static final int OPT_FRAGMENT = 0x01; public static final int OPT_NAK_LIST = 0x02; public static final int OPT_JOIN = 0x03; public static final int OPT_REDIRECT = 0x07; public static final int OPT_SYN = 0x0d; public static final int OPT_FIN = 0x0e; public static final int OPT_RST = 0x0f; public OptionHeader (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OptionHeader.java import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM Option Extension. */ package hk.miru.javapgm; public class OptionHeader { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; public static final int OPT_TOTAL_LENGTH_OFFSET = 2; private static final int OPT_MASK = 0x7f; private static final int OPT_END = 0x80; public static final int OPT_LENGTH = 0x00; public static final int OPT_FRAGMENT = 0x01; public static final int OPT_NAK_LIST = 0x02; public static final int OPT_JOIN = 0x03; public static final int OPT_REDIRECT = 0x07; public static final int OPT_SYN = 0x0d; public static final int OPT_FIN = 0x0e; public static final int OPT_RST = 0x0f; public OptionHeader (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/OptionLength.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM Option Length Extension. */ package hk.miru.javapgm; public class OptionLength { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_TOTAL_LENGTH_OFFSET = 2; private static final int SIZEOF_PGM_OPT_LENGTH = 4; public OptionLength (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OptionLength.java import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM Option Length Extension. */ package hk.miru.javapgm; public class OptionLength { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_TYPE_OFFSET = 0; private static final int OPT_LENGTH_OFFSET = 1; private static final int OPT_TOTAL_LENGTH_OFFSET = 2; private static final int SIZEOF_PGM_OPT_LENGTH = 4; public OptionLength (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SourcePathMessage.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.ProtocolFamily; import java.net.StandardProtocolFamily; import java.net.UnknownHostException;
/* Source path message or SPM packet. Used for defining and keeping multicast * circuit state. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class SourcePathMessage { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int SPM_SQN_OFFSET = 0; private static final int SPM_TRAIL_OFFSET = 4; private static final int SPM_LEAD_OFFSET = 8; private static final int SPM_NLA_AFI_OFFSET = 12; private static final int SPM_RESERVED_OFFSET = 14; private static final int SPM_NLA_OFFSET = 16; private static final int SPM_OPTIONS_OFFSET = 20; private static final int SPM6_SQN_OFFSET = 0; private static final int SPM6_TRAIL_OFFSET = 4; private static final int SPM6_LEAD_OFFSET = 8; private static final int SPM6_NLA_AFI_OFFSET = 12; private static final int SPM6_RESERVED_OFFSET = 14; private static final int SPM6_NLA_OFFSET = 16; private static final int SPM6_OPTIONS_OFFSET = 32; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_SPM_HEADER = SPM_OPTIONS_OFFSET; private static final int SIZEOF_SPM6_HEADER = SPM6_OPTIONS_OFFSET; public SourcePathMessage (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SourcePathMessage.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.ProtocolFamily; import java.net.StandardProtocolFamily; import java.net.UnknownHostException; /* Source path message or SPM packet. Used for defining and keeping multicast * circuit state. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class SourcePathMessage { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int SPM_SQN_OFFSET = 0; private static final int SPM_TRAIL_OFFSET = 4; private static final int SPM_LEAD_OFFSET = 8; private static final int SPM_NLA_AFI_OFFSET = 12; private static final int SPM_RESERVED_OFFSET = 14; private static final int SPM_NLA_OFFSET = 16; private static final int SPM_OPTIONS_OFFSET = 20; private static final int SPM6_SQN_OFFSET = 0; private static final int SPM6_TRAIL_OFFSET = 4; private static final int SPM6_LEAD_OFFSET = 8; private static final int SPM6_NLA_AFI_OFFSET = 12; private static final int SPM6_RESERVED_OFFSET = 14; private static final int SPM6_NLA_OFFSET = 16; private static final int SPM6_OPTIONS_OFFSET = 32; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_SPM_HEADER = SPM_OPTIONS_OFFSET; private static final int SIZEOF_SPM6_HEADER = SPM6_OPTIONS_OFFSET; public SourcePathMessage (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SourcePathMessageRequest.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull;
/* SPM-request or SPMR packet. Used for early access to source NLA. */ package hk.miru.javapgm; public class SourcePathMessageRequest { protected SocketBuffer _skb = null; protected int _offset = 0; public SourcePathMessageRequest (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SourcePathMessageRequest.java import static hk.miru.javapgm.Preconditions.checkNotNull; /* SPM-request or SPMR packet. Used for early access to source NLA. */ package hk.miru.javapgm; public class SourcePathMessageRequest { protected SocketBuffer _skb = null; protected int _offset = 0; public SourcePathMessageRequest (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Socket.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_APPENDED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_BOUNDS; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_DUPLICATE; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_INSERTED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MALFORMED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MISSING; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.SocketException; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.MembershipKey; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable;
* required (IPv6). * * All receiver addresses must be the same family. * interface and multiaddr must be the same family. * family cannot be AF_UNSPEC! */ public Socket (ProtocolFamily family) throws IOException { LOG.debug ("Socket (family: {})", family); this.family = family; this.canSendData = true; this.canSendNak = true; this.canReceiveData = true; this.dataDestinationPort = Packet.DEFAULT_DATA_DESTINATION_PORT; this.tsi = new TransportSessionId (null, Packet.DEFAULT_DATA_SOURCE_PORT); LOG.trace (NETWORK_MARKER, "Opening UDP encapsulated sockets."); this.recv_sock = DatagramChannel.open (this.family); LOG.trace (NETWORK_MARKER, "Set socket sharing."); this.recv_sock.setOption (StandardSocketOptions.SO_REUSEADDR, true); this.recv_sock.configureBlocking (false); this.send_sock = new MulticastSocket (); LOG.debug ("PGM socket successfully created."); } /* Timeout for pending timer in microseconds */ public long getTimeRemain() {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Socket.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_APPENDED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_BOUNDS; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_DUPLICATE; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_INSERTED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MALFORMED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MISSING; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.SocketException; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.MembershipKey; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable; * required (IPv6). * * All receiver addresses must be the same family. * interface and multiaddr must be the same family. * family cannot be AF_UNSPEC! */ public Socket (ProtocolFamily family) throws IOException { LOG.debug ("Socket (family: {})", family); this.family = family; this.canSendData = true; this.canSendNak = true; this.canReceiveData = true; this.dataDestinationPort = Packet.DEFAULT_DATA_DESTINATION_PORT; this.tsi = new TransportSessionId (null, Packet.DEFAULT_DATA_SOURCE_PORT); LOG.trace (NETWORK_MARKER, "Opening UDP encapsulated sockets."); this.recv_sock = DatagramChannel.open (this.family); LOG.trace (NETWORK_MARKER, "Set socket sharing."); this.recv_sock.setOption (StandardSocketOptions.SO_REUSEADDR, true); this.recv_sock.configureBlocking (false); this.send_sock = new MulticastSocket (); LOG.debug ("PGM socket successfully created."); } /* Timeout for pending timer in microseconds */ public long getTimeRemain() {
checkArgument (this.isConnected);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Socket.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_APPENDED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_BOUNDS; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_DUPLICATE; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_INSERTED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MALFORMED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MISSING; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.SocketException; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.MembershipKey; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable;
case SocketOptions.PGM_UDP_ENCAP_MCAST_PORT: checkArgument (optval instanceof Integer); this.udpEncapsulationMulticastPort = (((Integer)optval).intValue()); return true; /** Read-only options **/ case SocketOptions.PGM_MSSS: case SocketOptions.PGM_MSS: case SocketOptions.PGM_PDU: case SocketOptions.PGM_SEND_SOCK: case SocketOptions.PGM_RECV_SOCK: case SocketOptions.PGM_REPAIR_SOCK: case SocketOptions.PGM_PENDING_SOCK: case SocketOptions.PGM_ACK_SOCK: case SocketOptions.PGM_TIME_REMAIN: case SocketOptions.PGM_RATE_REMAIN: default: break; } return false; } /* Bind the sockets to the link layer to start receiving data. * * Returns TRUE on success, or FALSE on error and sets error appropriately, */ public boolean bind (hk.miru.javapgm.SocketAddress sockaddr, @Nullable InterfaceRequest send_req, @Nullable InterfaceRequest recv_req) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Socket.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_APPENDED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_BOUNDS; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_DUPLICATE; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_INSERTED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MALFORMED; import static hk.miru.javapgm.ReceiveWindow.Returns.RXW_MISSING; import java.io.IOException; import java.net.DatagramPacket; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.ProtocolFamily; import java.net.SocketException; import java.net.StandardProtocolFamily; import java.net.StandardSocketOptions; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.MembershipKey; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.TreeMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import javax.annotation.Nullable; case SocketOptions.PGM_UDP_ENCAP_MCAST_PORT: checkArgument (optval instanceof Integer); this.udpEncapsulationMulticastPort = (((Integer)optval).intValue()); return true; /** Read-only options **/ case SocketOptions.PGM_MSSS: case SocketOptions.PGM_MSS: case SocketOptions.PGM_PDU: case SocketOptions.PGM_SEND_SOCK: case SocketOptions.PGM_RECV_SOCK: case SocketOptions.PGM_REPAIR_SOCK: case SocketOptions.PGM_PENDING_SOCK: case SocketOptions.PGM_ACK_SOCK: case SocketOptions.PGM_TIME_REMAIN: case SocketOptions.PGM_RATE_REMAIN: default: break; } return false; } /* Bind the sockets to the link layer to start receiving data. * * Returns TRUE on success, or FALSE on error and sets error appropriately, */ public boolean bind (hk.miru.javapgm.SocketAddress sockaddr, @Nullable InterfaceRequest send_req, @Nullable InterfaceRequest recv_req) {
checkNotNull (sockaddr);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Nak.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager;
protected int _offset = 0; private static final int NAK_SQN_OFFSET = 0; private static final int NAK_SRC_NLA_AFI_OFFSET = 4; private static final int NAK_RESERVED_OFFSET = 6; private static final int NAK_SRC_NLA_OFFSET = 8; private static final int NAK_GRP_NLA_AFI_OFFSET = 12; private static final int NAK_RESERVED2_OFFSET = 14; private static final int NAK_GRP_NLA_OFFSET = 16; private static final int NAK_OPTIONS_OFFSET = 20; private static final int NAK6_SQN_OFFSET = 0; private static final int NAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NAK6_RESERVED_OFFSET = 6; private static final int NAK6_SRC_NLA_OFFSET = 8; private static final int NAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NAK6_RESERVED2_OFFSET = 26; private static final int NAK6_GRP_NLA_OFFSET = 28; private static final int NAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_PGM_NAK = 20; private static final int SIZEOF_PGM_NAK6 = 44; private static final int SIZEOF_PGM_OPT_LENGTH = 4; private static final int SIZEOF_PGM_OPT_HEADER = 3; private static final int SIZEOF_PGM_OPT_RESERVED = 1; private static final int SIZEOF_PGM_SQN = 4; public Nak (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Nak.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; protected int _offset = 0; private static final int NAK_SQN_OFFSET = 0; private static final int NAK_SRC_NLA_AFI_OFFSET = 4; private static final int NAK_RESERVED_OFFSET = 6; private static final int NAK_SRC_NLA_OFFSET = 8; private static final int NAK_GRP_NLA_AFI_OFFSET = 12; private static final int NAK_RESERVED2_OFFSET = 14; private static final int NAK_GRP_NLA_OFFSET = 16; private static final int NAK_OPTIONS_OFFSET = 20; private static final int NAK6_SQN_OFFSET = 0; private static final int NAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NAK6_RESERVED_OFFSET = 6; private static final int NAK6_SRC_NLA_OFFSET = 8; private static final int NAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NAK6_RESERVED2_OFFSET = 26; private static final int NAK6_GRP_NLA_OFFSET = 28; private static final int NAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_PGM_NAK = 20; private static final int SIZEOF_PGM_NAK6 = 44; private static final int SIZEOF_PGM_OPT_LENGTH = 4; private static final int SIZEOF_PGM_OPT_HEADER = 3; private static final int SIZEOF_PGM_OPT_RESERVED = 1; private static final int SIZEOF_PGM_SQN = 4; public Nak (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Nak.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager;
private static final int NAK_GRP_NLA_OFFSET = 16; private static final int NAK_OPTIONS_OFFSET = 20; private static final int NAK6_SQN_OFFSET = 0; private static final int NAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NAK6_RESERVED_OFFSET = 6; private static final int NAK6_SRC_NLA_OFFSET = 8; private static final int NAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NAK6_RESERVED2_OFFSET = 26; private static final int NAK6_GRP_NLA_OFFSET = 28; private static final int NAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_PGM_NAK = 20; private static final int SIZEOF_PGM_NAK6 = 44; private static final int SIZEOF_PGM_OPT_LENGTH = 4; private static final int SIZEOF_PGM_OPT_HEADER = 3; private static final int SIZEOF_PGM_OPT_RESERVED = 1; private static final int SIZEOF_PGM_SQN = 4; public Nak (SocketBuffer skb, int offset) { checkNotNull (skb); this._skb = skb; this._offset = offset; } public static SocketBuffer create (InetAddress nak_src_nla, InetAddress nak_grp_nla, int count) { checkNotNull (nak_src_nla); checkNotNull (nak_grp_nla);
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Nak.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; private static final int NAK_GRP_NLA_OFFSET = 16; private static final int NAK_OPTIONS_OFFSET = 20; private static final int NAK6_SQN_OFFSET = 0; private static final int NAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NAK6_RESERVED_OFFSET = 6; private static final int NAK6_SRC_NLA_OFFSET = 8; private static final int NAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NAK6_RESERVED2_OFFSET = 26; private static final int NAK6_GRP_NLA_OFFSET = 28; private static final int NAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; private static final int SIZEOF_PGM_NAK = 20; private static final int SIZEOF_PGM_NAK6 = 44; private static final int SIZEOF_PGM_OPT_LENGTH = 4; private static final int SIZEOF_PGM_OPT_HEADER = 3; private static final int SIZEOF_PGM_OPT_RESERVED = 1; private static final int SIZEOF_PGM_SQN = 4; public Nak (SocketBuffer skb, int offset) { checkNotNull (skb); this._skb = skb; this._offset = offset; } public static SocketBuffer create (InetAddress nak_src_nla, InetAddress nak_grp_nla, int count) { checkNotNull (nak_src_nla); checkNotNull (nak_grp_nla);
checkArgument (count > 0 && count <= 63);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SequenceNumber.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable;
/* Wrapper for Java primitives data type to handle window semantics of * comparison and wrapping. */ package hk.miru.javapgm; @SuppressWarnings("serial") public final class SequenceNumber extends Number implements Comparable<SequenceNumber> { public static final SequenceNumber ZERO = fromIntBits (0); public static final SequenceNumber ONE = fromIntBits (1); public static final SequenceNumber MAX_VALUE = fromIntBits (-1); private final int value; private SequenceNumber (int value) { this.value = value & 0xffffffff; } public static SequenceNumber fromIntBits (int bits) { return new SequenceNumber (bits); } public static SequenceNumber valueOf (long value) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // } // Path: src/main/java/hk/miru/javapgm/SequenceNumber.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /* Wrapper for Java primitives data type to handle window semantics of * comparison and wrapping. */ package hk.miru.javapgm; @SuppressWarnings("serial") public final class SequenceNumber extends Number implements Comparable<SequenceNumber> { public static final SequenceNumber ZERO = fromIntBits (0); public static final SequenceNumber ONE = fromIntBits (1); public static final SequenceNumber MAX_VALUE = fromIntBits (-1); private final int value; private SequenceNumber (int value) { this.value = value & 0xffffffff; } public static SequenceNumber fromIntBits (int bits) { return new SequenceNumber (bits); } public static SequenceNumber valueOf (long value) {
checkArgument ((value & UnsignedInts.INT_MASK) == value,
steve-o/javapgm
src/main/java/hk/miru/javapgm/SequenceNumber.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable;
/* Wrapper for Java primitives data type to handle window semantics of * comparison and wrapping. */ package hk.miru.javapgm; @SuppressWarnings("serial") public final class SequenceNumber extends Number implements Comparable<SequenceNumber> { public static final SequenceNumber ZERO = fromIntBits (0); public static final SequenceNumber ONE = fromIntBits (1); public static final SequenceNumber MAX_VALUE = fromIntBits (-1); private final int value; private SequenceNumber (int value) { this.value = value & 0xffffffff; } public static SequenceNumber fromIntBits (int bits) { return new SequenceNumber (bits); } public static SequenceNumber valueOf (long value) { checkArgument ((value & UnsignedInts.INT_MASK) == value, "value (%s) is outside the range for an unsigned integer value", value); return fromIntBits ((int)value); } public static SequenceNumber valueOf (String string) { return valueOf (string, 10); } public static SequenceNumber valueOf (String string, int radix) { return fromIntBits (UnsignedInts.parseUnsignedInt (string, radix)); } @CheckReturnValue public SequenceNumber plus (int val) { return fromIntBits (this.value + val); } @CheckReturnValue public SequenceNumber plus (SequenceNumber val) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // } // Path: src/main/java/hk/miru/javapgm/SequenceNumber.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /* Wrapper for Java primitives data type to handle window semantics of * comparison and wrapping. */ package hk.miru.javapgm; @SuppressWarnings("serial") public final class SequenceNumber extends Number implements Comparable<SequenceNumber> { public static final SequenceNumber ZERO = fromIntBits (0); public static final SequenceNumber ONE = fromIntBits (1); public static final SequenceNumber MAX_VALUE = fromIntBits (-1); private final int value; private SequenceNumber (int value) { this.value = value & 0xffffffff; } public static SequenceNumber fromIntBits (int bits) { return new SequenceNumber (bits); } public static SequenceNumber valueOf (long value) { checkArgument ((value & UnsignedInts.INT_MASK) == value, "value (%s) is outside the range for an unsigned integer value", value); return fromIntBits ((int)value); } public static SequenceNumber valueOf (String string) { return valueOf (string, 10); } public static SequenceNumber valueOf (String string, int radix) { return fromIntBits (UnsignedInts.parseUnsignedInt (string, radix)); } @CheckReturnValue public SequenceNumber plus (int val) { return fromIntBits (this.value + val); } @CheckReturnValue public SequenceNumber plus (SequenceNumber val) {
checkNotNull (val);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SequenceNumber.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable;
} @CheckReturnValue public SequenceNumber plus (int val) { return fromIntBits (this.value + val); } @CheckReturnValue public SequenceNumber plus (SequenceNumber val) { checkNotNull (val); return fromIntBits (this.value + checkNotNull (val).value); } @CheckReturnValue public SequenceNumber minus (int val) { return fromIntBits (this.value - val); } @CheckReturnValue public SequenceNumber minus (SequenceNumber val) { return fromIntBits (this.value - checkNotNull (val).value); } @Override public int intValue() { /* Number interface */ return this.value; } @Override public long longValue() {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // } // Path: src/main/java/hk/miru/javapgm/SequenceNumber.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; } @CheckReturnValue public SequenceNumber plus (int val) { return fromIntBits (this.value + val); } @CheckReturnValue public SequenceNumber plus (SequenceNumber val) { checkNotNull (val); return fromIntBits (this.value + checkNotNull (val).value); } @CheckReturnValue public SequenceNumber minus (int val) { return fromIntBits (this.value - val); } @CheckReturnValue public SequenceNumber minus (SequenceNumber val) { return fromIntBits (this.value - checkNotNull (val).value); } @Override public int intValue() { /* Number interface */ return this.value; } @Override public long longValue() {
return toLong (this.value);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SequenceNumber.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable;
} @CheckReturnValue public SequenceNumber minus (SequenceNumber val) { return fromIntBits (this.value - checkNotNull (val).value); } @Override public int intValue() { /* Number interface */ return this.value; } @Override public long longValue() { return toLong (this.value); } @Override public float floatValue() { /* Number interface */ return longValue(); } @Override public double doubleValue() { /* Number interface */ return longValue(); } @Override public int compareTo (SequenceNumber other) { checkNotNull (other);
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static int compare (int a, int b) { // return Ints.compare (flip(a), flip(b)); // } // // Path: src/main/java/hk/miru/javapgm/UnsignedInts.java // public static long toLong (int value) { // return value & INT_MASK; // } // Path: src/main/java/hk/miru/javapgm/SequenceNumber.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import static hk.miru.javapgm.UnsignedInts.compare; import static hk.miru.javapgm.UnsignedInts.toLong; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; } @CheckReturnValue public SequenceNumber minus (SequenceNumber val) { return fromIntBits (this.value - checkNotNull (val).value); } @Override public int intValue() { /* Number interface */ return this.value; } @Override public long longValue() { return toLong (this.value); } @Override public float floatValue() { /* Number interface */ return longValue(); } @Override public double doubleValue() { /* Number interface */ return longValue(); } @Override public int compareTo (SequenceNumber other) { checkNotNull (other);
return compare (this.value, other.value);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GlobalSourceId.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import org.apache.logging.log4j.LogManager; import javax.annotation.Nullable;
/* Unique Global Source Identifier (GSI), usually derived from the system node * name or IPv4 address as a convenient unique value. When combined with a * data-source port it becomes a Transport Session Identifier (TSI). */ package hk.miru.javapgm; public class GlobalSourceId { /** * The number of bytes require to represent a GSI. */ public static final int SIZE = 6; private final byte[] identifier; /** * Create a new {@code GlobalSourceId} from an sequence of bytes. * * @param bytes the primitive value in bytes. */ public GlobalSourceId (byte[] bytes) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GlobalSourceId.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import org.apache.logging.log4j.LogManager; import javax.annotation.Nullable; /* Unique Global Source Identifier (GSI), usually derived from the system node * name or IPv4 address as a convenient unique value. When combined with a * data-source port it becomes a Transport Session Identifier (TSI). */ package hk.miru.javapgm; public class GlobalSourceId { /** * The number of bytes require to represent a GSI. */ public static final int SIZE = 6; private final byte[] identifier; /** * Create a new {@code GlobalSourceId} from an sequence of bytes. * * @param bytes the primitive value in bytes. */ public GlobalSourceId (byte[] bytes) {
checkArgument (bytes.length == SIZE);
steve-o/javapgm
src/main/java/hk/miru/javapgm/GlobalSourceId.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import org.apache.logging.log4j.LogManager; import javax.annotation.Nullable;
} @Override public boolean equals (@Nullable Object object) { if (! (object instanceof GlobalSourceId)) return false; byte[] identifier2 = ((GlobalSourceId)object).identifier; if (this.identifier.length != identifier2.length) return false; for (int i = 0; i < this.identifier.length; i++) if (this.identifier[i] != identifier2[i]) return false; return true; } public final byte[] getBytes() { return this.identifier; } /* Create a global session ID as recommended by the PGM draft specification * using low order 48 bits of MD5 of a hostname. * * IDN hostnames must be already converted to ASCII character set via * java.net.IDN */ public final void set (String hostname) throws NoSuchAlgorithmException {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/GlobalSourceId.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; import org.apache.logging.log4j.LogManager; import javax.annotation.Nullable; } @Override public boolean equals (@Nullable Object object) { if (! (object instanceof GlobalSourceId)) return false; byte[] identifier2 = ((GlobalSourceId)object).identifier; if (this.identifier.length != identifier2.length) return false; for (int i = 0; i < this.identifier.length; i++) if (this.identifier[i] != identifier2[i]) return false; return true; } public final byte[] getBytes() { return this.identifier; } /* Create a global session ID as recommended by the PGM draft specification * using low order 48 bits of MD5 of a hostname. * * IDN hostnames must be already converted to ASCII character set via * java.net.IDN */ public final void set (String hostname) throws NoSuchAlgorithmException {
checkNotNull (hostname);
steve-o/javapgm
src/main/java/hk/miru/javapgm/TransportSessionId.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import javax.annotation.Nullable;
/* Unique identifier for each PGM transport session. */ package hk.miru.javapgm; public class TransportSessionId { private GlobalSourceId gsi = null; private int sourcePort = 0; public TransportSessionId (@Nullable GlobalSourceId gsi, int sourcePort) { this.gsi = gsi; this.sourcePort = sourcePort; } public TransportSessionId (TransportSessionId tsi) { this (tsi.getGlobalSourceId(), tsi.getSourcePort()); } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals (@Nullable Object object) { if (null != object && (object instanceof TransportSessionId)) { /* using this.gsi == other.gsi does not call this.gsi.equals(other.gsi) */ if (this.gsi.equals (((TransportSessionId)object).getGlobalSourceId()) && this.sourcePort== ((TransportSessionId)object).getSourcePort()) { return true; } } return false; } public GlobalSourceId getGlobalSourceId() { return this.gsi; } public int getSourcePort() { return this.sourcePort; } @SuppressWarnings("PointlessBitwiseExpression") public final byte[] getAsBytes() { byte[] bytes = new byte[8]; byte[] gsiBytes = this.gsi.getBytes(); bytes[0] = gsiBytes[0]; bytes[1] = gsiBytes[1]; bytes[2] = gsiBytes[2]; bytes[3] = gsiBytes[3]; bytes[4] = gsiBytes[4]; bytes[5] = gsiBytes[5]; bytes[6] = (byte) ((this.sourcePort >> 8) & 0xff); bytes[7] = (byte) ((this.sourcePort >> 0) & 0xff); return bytes; } private void setGlobalSourceId (GlobalSourceId gsi) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/TransportSessionId.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import javax.annotation.Nullable; /* Unique identifier for each PGM transport session. */ package hk.miru.javapgm; public class TransportSessionId { private GlobalSourceId gsi = null; private int sourcePort = 0; public TransportSessionId (@Nullable GlobalSourceId gsi, int sourcePort) { this.gsi = gsi; this.sourcePort = sourcePort; } public TransportSessionId (TransportSessionId tsi) { this (tsi.getGlobalSourceId(), tsi.getSourcePort()); } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals (@Nullable Object object) { if (null != object && (object instanceof TransportSessionId)) { /* using this.gsi == other.gsi does not call this.gsi.equals(other.gsi) */ if (this.gsi.equals (((TransportSessionId)object).getGlobalSourceId()) && this.sourcePort== ((TransportSessionId)object).getSourcePort()) { return true; } } return false; } public GlobalSourceId getGlobalSourceId() { return this.gsi; } public int getSourcePort() { return this.sourcePort; } @SuppressWarnings("PointlessBitwiseExpression") public final byte[] getAsBytes() { byte[] bytes = new byte[8]; byte[] gsiBytes = this.gsi.getBytes(); bytes[0] = gsiBytes[0]; bytes[1] = gsiBytes[1]; bytes[2] = gsiBytes[2]; bytes[3] = gsiBytes[3]; bytes[4] = gsiBytes[4]; bytes[5] = gsiBytes[5]; bytes[6] = (byte) ((this.sourcePort >> 8) & 0xff); bytes[7] = (byte) ((this.sourcePort >> 0) & 0xff); return bytes; } private void setGlobalSourceId (GlobalSourceId gsi) {
checkNotNull (gsi);
steve-o/javapgm
src/main/java/hk/miru/javapgm/TransportSessionId.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import javax.annotation.Nullable;
/* Unique identifier for each PGM transport session. */ package hk.miru.javapgm; public class TransportSessionId { private GlobalSourceId gsi = null; private int sourcePort = 0; public TransportSessionId (@Nullable GlobalSourceId gsi, int sourcePort) { this.gsi = gsi; this.sourcePort = sourcePort; } public TransportSessionId (TransportSessionId tsi) { this (tsi.getGlobalSourceId(), tsi.getSourcePort()); } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals (@Nullable Object object) { if (null != object && (object instanceof TransportSessionId)) { /* using this.gsi == other.gsi does not call this.gsi.equals(other.gsi) */ if (this.gsi.equals (((TransportSessionId)object).getGlobalSourceId()) && this.sourcePort== ((TransportSessionId)object).getSourcePort()) { return true; } } return false; } public GlobalSourceId getGlobalSourceId() { return this.gsi; } public int getSourcePort() { return this.sourcePort; } @SuppressWarnings("PointlessBitwiseExpression") public final byte[] getAsBytes() { byte[] bytes = new byte[8]; byte[] gsiBytes = this.gsi.getBytes(); bytes[0] = gsiBytes[0]; bytes[1] = gsiBytes[1]; bytes[2] = gsiBytes[2]; bytes[3] = gsiBytes[3]; bytes[4] = gsiBytes[4]; bytes[5] = gsiBytes[5]; bytes[6] = (byte) ((this.sourcePort >> 8) & 0xff); bytes[7] = (byte) ((this.sourcePort >> 0) & 0xff); return bytes; } private void setGlobalSourceId (GlobalSourceId gsi) { checkNotNull (gsi); this.gsi = gsi; } public void setSourcePort (int sourcePort) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/TransportSessionId.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; import javax.annotation.Nullable; /* Unique identifier for each PGM transport session. */ package hk.miru.javapgm; public class TransportSessionId { private GlobalSourceId gsi = null; private int sourcePort = 0; public TransportSessionId (@Nullable GlobalSourceId gsi, int sourcePort) { this.gsi = gsi; this.sourcePort = sourcePort; } public TransportSessionId (TransportSessionId tsi) { this (tsi.getGlobalSourceId(), tsi.getSourcePort()); } @Override public int hashCode() { return toString().hashCode(); } @Override public boolean equals (@Nullable Object object) { if (null != object && (object instanceof TransportSessionId)) { /* using this.gsi == other.gsi does not call this.gsi.equals(other.gsi) */ if (this.gsi.equals (((TransportSessionId)object).getGlobalSourceId()) && this.sourcePort== ((TransportSessionId)object).getSourcePort()) { return true; } } return false; } public GlobalSourceId getGlobalSourceId() { return this.gsi; } public int getSourcePort() { return this.sourcePort; } @SuppressWarnings("PointlessBitwiseExpression") public final byte[] getAsBytes() { byte[] bytes = new byte[8]; byte[] gsiBytes = this.gsi.getBytes(); bytes[0] = gsiBytes[0]; bytes[1] = gsiBytes[1]; bytes[2] = gsiBytes[2]; bytes[3] = gsiBytes[3]; bytes[4] = gsiBytes[4]; bytes[5] = gsiBytes[5]; bytes[6] = (byte) ((this.sourcePort >> 8) & 0xff); bytes[7] = (byte) ((this.sourcePort >> 0) & 0xff); return bytes; } private void setGlobalSourceId (GlobalSourceId gsi) { checkNotNull (gsi); this.gsi = gsi; } public void setSourcePort (int sourcePort) {
checkArgument (sourcePort >= 0 && sourcePort <= 65535);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Packet.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.ProtocolFamily; import java.net.StandardProtocolFamily; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.Nullable;
public static final int PGM_OPT_PARITY = 0x80; public static final int PGM_OPT_VAR_PKTLEN = 0x40; public static final int PGM_OP_ENCODED = 0x08; public static final int PGM_OPT_NETWORK = 0x02; public static final int PGM_OPT_PRESENT = 0x01; public static final int PGM_SPORT_OFFSET = 0; public static final int PGM_DPORT_OFFSET = 2; public static final int PGM_TYPE_OFFSET = 4; public static final int PGM_OPTIONS_OFFSET = 5; public static final int PGM_CHECKSUM_OFFSET = 6; public static final int PGM_GSI_OFFSET = 8; public static final int PGM_TSDU_LENGTH_OFFSET = 14; public static final int PGM_TYPE_DATA_OFFSET = SIZEOF_PGM_HEADER; public static int calculateOffset (boolean canFragment, @Nullable ProtocolFamily pgmcc_family) { int data_size = SIZEOF_PGM_HEADER + SIZEOF_PGM_DATA; int pkt_size = data_size; if (canFragment || (null != pgmcc_family)) pkt_size += SIZEOF_PGM_OPT_LENGTH + SIZEOF_PGM_OPT_HEADER; if (canFragment) pkt_size += SIZEOF_PGM_OPT_FRAGMENT; if (StandardProtocolFamily.INET == pgmcc_family) pkt_size += SIZEOF_PGM_OPT_PGMCC_DATA; else if (StandardProtocolFamily.INET6 == pgmcc_family) pkt_size += SIZEOF_PGM_OPT6_PGMCC_DATA; return pkt_size; } public static boolean parseUdpEncapsulated (SocketBuffer skb) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Packet.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.ProtocolFamily; import java.net.StandardProtocolFamily; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.Nullable; public static final int PGM_OPT_PARITY = 0x80; public static final int PGM_OPT_VAR_PKTLEN = 0x40; public static final int PGM_OP_ENCODED = 0x08; public static final int PGM_OPT_NETWORK = 0x02; public static final int PGM_OPT_PRESENT = 0x01; public static final int PGM_SPORT_OFFSET = 0; public static final int PGM_DPORT_OFFSET = 2; public static final int PGM_TYPE_OFFSET = 4; public static final int PGM_OPTIONS_OFFSET = 5; public static final int PGM_CHECKSUM_OFFSET = 6; public static final int PGM_GSI_OFFSET = 8; public static final int PGM_TSDU_LENGTH_OFFSET = 14; public static final int PGM_TYPE_DATA_OFFSET = SIZEOF_PGM_HEADER; public static int calculateOffset (boolean canFragment, @Nullable ProtocolFamily pgmcc_family) { int data_size = SIZEOF_PGM_HEADER + SIZEOF_PGM_DATA; int pkt_size = data_size; if (canFragment || (null != pgmcc_family)) pkt_size += SIZEOF_PGM_OPT_LENGTH + SIZEOF_PGM_OPT_HEADER; if (canFragment) pkt_size += SIZEOF_PGM_OPT_FRAGMENT; if (StandardProtocolFamily.INET == pgmcc_family) pkt_size += SIZEOF_PGM_OPT_PGMCC_DATA; else if (StandardProtocolFamily.INET6 == pgmcc_family) pkt_size += SIZEOF_PGM_OPT6_PGMCC_DATA; return pkt_size; } public static boolean parseUdpEncapsulated (SocketBuffer skb) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/NullNakPacket.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException;
/* Null-NAK or NNAK packet. Feedback by PGM infrastructure after * suppressing local network NAKs for adaptive parameter calculation. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class NullNakPacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int NNAK_SQN_OFFSET = 0; private static final int NNAK_SRC_NLA_AFI_OFFSET = 4; private static final int NNAK_RESERVED_OFFSET = 6; private static final int NNAK_SRC_NLA_OFFSET = 8; private static final int NNAK_GRP_NLA_AFI_OFFSET = 12; private static final int NNAK_RESERVED2_OFFSET = 14; private static final int NNAK_GRP_NLA_OFFSET = 16; private static final int NNAK_OPTIONS_OFFSET = 20; private static final int NNAK6_SQN_OFFSET = 0; private static final int NNAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NNAK6_RESERVED_OFFSET = 6; private static final int NNAK6_SRC_NLA_OFFSET = 8; private static final int NNAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NNAK6_RESERVED2_OFFSET = 26; private static final int NNAK6_GRP_NLA_OFFSET = 28; private static final int NNAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; public NullNakPacket (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/NullNakPacket.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; /* Null-NAK or NNAK packet. Feedback by PGM infrastructure after * suppressing local network NAKs for adaptive parameter calculation. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class NullNakPacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int NNAK_SQN_OFFSET = 0; private static final int NNAK_SRC_NLA_AFI_OFFSET = 4; private static final int NNAK_RESERVED_OFFSET = 6; private static final int NNAK_SRC_NLA_OFFSET = 8; private static final int NNAK_GRP_NLA_AFI_OFFSET = 12; private static final int NNAK_RESERVED2_OFFSET = 14; private static final int NNAK_GRP_NLA_OFFSET = 16; private static final int NNAK_OPTIONS_OFFSET = 20; private static final int NNAK6_SQN_OFFSET = 0; private static final int NNAK6_SRC_NLA_AFI_OFFSET = 4; private static final int NNAK6_RESERVED_OFFSET = 6; private static final int NNAK6_SRC_NLA_OFFSET = 8; private static final int NNAK6_GRP_NLA_AFI_OFFSET = 24; private static final int NNAK6_RESERVED2_OFFSET = 26; private static final int NNAK6_GRP_NLA_OFFSET = 28; private static final int NNAK6_OPTIONS_OFFSET = 44; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; public NullNakPacket (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/PollPacket.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException;
/* Poll packet for starting receiver poll rounds. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class PollPacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int POLL_SQN_OFFSET = 0; private static final int POLL_ROUND_OFFSET = 4; private static final int POLL_S_TYPE_OFFSET = 6; private static final int POLL_NLA_AFI_OFFSET = 8; private static final int POLL_RESERVED_OFFSET = 10; private static final int POLL_NLA_OFFSET = 12; private static final int POLL_BO_IVL_OFFSET = 16; private static final int POLL_RAND_OFFSET = 20; private static final int POLL_MASK_OFFSET = 24; private static final int POLL_OPTIONS_OFFSET = 28; private static final int POLL6_SQN_OFFSET = 0; private static final int POLL6_ROUND_OFFSET = 4; private static final int POLL6_S_TYPE_OFFSET = 6; private static final int POLL6_NLA_AFI_OFFSET = 8; private static final int POLL6_RESERVED_OFFSET = 10; private static final int POLL6_NLA_OFFSET = 12; private static final int POLL6_BO_IVL_OFFSET = 28; private static final int POLL6_RAND_OFFSET = 32; private static final int POLL6_MASK_OFFSET = 36; private static final int POLL6_OPTIONS_OFFSET = 40; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; public PollPacket (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/PollPacket.java import static hk.miru.javapgm.Preconditions.checkNotNull; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; /* Poll packet for starting receiver poll rounds. */ package hk.miru.javapgm; @SuppressWarnings("unused") public class PollPacket { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int POLL_SQN_OFFSET = 0; private static final int POLL_ROUND_OFFSET = 4; private static final int POLL_S_TYPE_OFFSET = 6; private static final int POLL_NLA_AFI_OFFSET = 8; private static final int POLL_RESERVED_OFFSET = 10; private static final int POLL_NLA_OFFSET = 12; private static final int POLL_BO_IVL_OFFSET = 16; private static final int POLL_RAND_OFFSET = 20; private static final int POLL_MASK_OFFSET = 24; private static final int POLL_OPTIONS_OFFSET = 28; private static final int POLL6_SQN_OFFSET = 0; private static final int POLL6_ROUND_OFFSET = 4; private static final int POLL6_S_TYPE_OFFSET = 6; private static final int POLL6_NLA_AFI_OFFSET = 8; private static final int POLL6_RESERVED_OFFSET = 10; private static final int POLL6_NLA_OFFSET = 12; private static final int POLL6_BO_IVL_OFFSET = 28; private static final int POLL6_RAND_OFFSET = 32; private static final int POLL6_MASK_OFFSET = 36; private static final int POLL6_OPTIONS_OFFSET = 40; private static final int SIZEOF_INADDR = 4; private static final int SIZEOF_INADDR6 = 16; public PollPacket (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/RateControl.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // }
import static hk.miru.javapgm.Preconditions.checkArgument;
/* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class RateControl { private long rate_per_sec; private long rate_per_msec; private int iphdr_len; private long rate_limit; private long last_rate_check; /* Create machinery for rate regulation. * The rate_per_sec is ammortized over millisecond time periods. */ public RateControl (long rate_per_sec, int iphdr_len, int max_tpdu) { /* Pre-conditions */
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // Path: src/main/java/hk/miru/javapgm/RateControl.java import static hk.miru.javapgm.Preconditions.checkArgument; /* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class RateControl { private long rate_per_sec; private long rate_per_msec; private int iphdr_len; private long rate_limit; private long last_rate_check; /* Create machinery for rate regulation. * The rate_per_sec is ammortized over millisecond time periods. */ public RateControl (long rate_per_sec, int iphdr_len, int max_tpdu) { /* Pre-conditions */
checkArgument (rate_per_sec >= max_tpdu);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Header.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM packet header. */ package hk.miru.javapgm; public class Header { protected SocketBuffer _skb = null; protected int _offset = 0; public Header (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Header.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM packet header. */ package hk.miru.javapgm; public class Header { protected SocketBuffer _skb = null; protected int _offset = 0; public Header (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/Header.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM packet header. */ package hk.miru.javapgm; public class Header { protected SocketBuffer _skb = null; protected int _offset = 0; public Header (SocketBuffer skb, int offset) { checkNotNull (skb); this._skb = skb; this._offset = offset; } public final int getChecksum() { return this._skb.getUnsignedShort (this._offset + Packet.PGM_CHECKSUM_OFFSET); } public final boolean hasChecksum() { return (0 != getChecksum()); } public void setChecksum (int csum) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/Header.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM packet header. */ package hk.miru.javapgm; public class Header { protected SocketBuffer _skb = null; protected int _offset = 0; public Header (SocketBuffer skb, int offset) { checkNotNull (skb); this._skb = skb; this._offset = offset; } public final int getChecksum() { return this._skb.getUnsignedShort (this._offset + Packet.PGM_CHECKSUM_OFFSET); } public final boolean hasChecksum() { return (0 != getChecksum()); } public void setChecksum (int csum) {
checkArgument (csum >> 16 == 0);
steve-o/javapgm
src/main/java/hk/miru/javapgm/OptionFragment.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkNotNull;
/* PGM Option Fragment Extension. */ package hk.miru.javapgm; public class OptionFragment { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_SQN_OFFSET = 4; private static final int OPT_FRAG_OFF_OFFSET = 8; private static final int OPT_FRAG_LEN_OFFSET = 12; public OptionFragment (SocketBuffer skb, int offset) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/OptionFragment.java import static hk.miru.javapgm.Preconditions.checkNotNull; /* PGM Option Fragment Extension. */ package hk.miru.javapgm; public class OptionFragment { protected SocketBuffer _skb = null; protected int _offset = 0; private static final int OPT_SQN_OFFSET = 4; private static final int OPT_FRAG_OFF_OFFSET = 8; private static final int OPT_FRAG_LEN_OFFSET = 12; public OptionFragment (SocketBuffer skb, int offset) {
checkNotNull (skb);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SocketAddress.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class SocketAddress { private TransportSessionId tsi = null; private int port = 0; /* data-destination port */ public SocketAddress (TransportSessionId tsi, int destinationPort) {
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SocketAddress.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class SocketAddress { private TransportSessionId tsi = null; private int port = 0; /* data-destination port */ public SocketAddress (TransportSessionId tsi, int destinationPort) {
checkNotNull (tsi);
steve-o/javapgm
src/main/java/hk/miru/javapgm/SocketAddress.java
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull;
/* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class SocketAddress { private TransportSessionId tsi = null; private int port = 0; /* data-destination port */ public SocketAddress (TransportSessionId tsi, int destinationPort) { checkNotNull (tsi);
// Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static void checkArgument (boolean expression) { // if (!expression) { // throw new IllegalArgumentException(); // } // } // // Path: src/main/java/hk/miru/javapgm/Preconditions.java // public static <T> T checkNotNull (T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/hk/miru/javapgm/SocketAddress.java import static hk.miru.javapgm.Preconditions.checkArgument; import static hk.miru.javapgm.Preconditions.checkNotNull; /* Socket address type for PGM sockets. */ package hk.miru.javapgm; public class SocketAddress { private TransportSessionId tsi = null; private int port = 0; /* data-destination port */ public SocketAddress (TransportSessionId tsi, int destinationPort) { checkNotNull (tsi);
checkArgument (destinationPort >= 0 && destinationPort <= 65535);
CypherCove/LWPTools
android-src/com/cyphercove/lwptools/android/LiveWallpaperAndroidAdapter.java
// Path: core-src/com/cyphercove/lwptools/core/LiveWallpaperBaseRenderer.java // public interface LiveWallpaperBaseRenderer { // void create(); // void dispose(); // void pause(); // void resume(); // void resize(int width, int height); // void draw(float deltaTime, float xOffsetFake, float xOffsetLooping, float xOffsetSmooth, float yOffset); // void onSettingsChanged(); // void onDoubleTap(); // void onTripleTap(); // void setIsPreview(boolean isPreview); // } // // Path: core-src/com/cyphercove/lwptools/core/MultiTapListener.java // public interface MultiTapListener { // void onDoubleTap(); // void onTripleTap(); // }
import android.content.Context; import android.content.SharedPreferences; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.backends.android.AndroidWallpaperListener; import com.badlogic.gdx.math.MathUtils; import com.cyphercove.lwptools.core.LiveWallpaperBaseRenderer; import com.cyphercove.lwptools.core.MultiTapListener;
package com.cyphercove.lwptools.android; public class LiveWallpaperAndroidAdapter implements ApplicationListener, AndroidWallpaperListener, SharedPreferences.OnSharedPreferenceChangeListener{
// Path: core-src/com/cyphercove/lwptools/core/LiveWallpaperBaseRenderer.java // public interface LiveWallpaperBaseRenderer { // void create(); // void dispose(); // void pause(); // void resume(); // void resize(int width, int height); // void draw(float deltaTime, float xOffsetFake, float xOffsetLooping, float xOffsetSmooth, float yOffset); // void onSettingsChanged(); // void onDoubleTap(); // void onTripleTap(); // void setIsPreview(boolean isPreview); // } // // Path: core-src/com/cyphercove/lwptools/core/MultiTapListener.java // public interface MultiTapListener { // void onDoubleTap(); // void onTripleTap(); // } // Path: android-src/com/cyphercove/lwptools/android/LiveWallpaperAndroidAdapter.java import android.content.Context; import android.content.SharedPreferences; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.backends.android.AndroidWallpaperListener; import com.badlogic.gdx.math.MathUtils; import com.cyphercove.lwptools.core.LiveWallpaperBaseRenderer; import com.cyphercove.lwptools.core.MultiTapListener; package com.cyphercove.lwptools.android; public class LiveWallpaperAndroidAdapter implements ApplicationListener, AndroidWallpaperListener, SharedPreferences.OnSharedPreferenceChangeListener{
LiveWallpaperBaseRenderer liveWallpaper;
CypherCove/LWPTools
android-src/com/cyphercove/lwptools/android/LiveWallpaperAndroidAdapter.java
// Path: core-src/com/cyphercove/lwptools/core/LiveWallpaperBaseRenderer.java // public interface LiveWallpaperBaseRenderer { // void create(); // void dispose(); // void pause(); // void resume(); // void resize(int width, int height); // void draw(float deltaTime, float xOffsetFake, float xOffsetLooping, float xOffsetSmooth, float yOffset); // void onSettingsChanged(); // void onDoubleTap(); // void onTripleTap(); // void setIsPreview(boolean isPreview); // } // // Path: core-src/com/cyphercove/lwptools/core/MultiTapListener.java // public interface MultiTapListener { // void onDoubleTap(); // void onTripleTap(); // }
import android.content.Context; import android.content.SharedPreferences; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.backends.android.AndroidWallpaperListener; import com.badlogic.gdx.math.MathUtils; import com.cyphercove.lwptools.core.LiveWallpaperBaseRenderer; import com.cyphercove.lwptools.core.MultiTapListener;
package com.cyphercove.lwptools.android; public class LiveWallpaperAndroidAdapter implements ApplicationListener, AndroidWallpaperListener, SharedPreferences.OnSharedPreferenceChangeListener{ LiveWallpaperBaseRenderer liveWallpaper;
// Path: core-src/com/cyphercove/lwptools/core/LiveWallpaperBaseRenderer.java // public interface LiveWallpaperBaseRenderer { // void create(); // void dispose(); // void pause(); // void resume(); // void resize(int width, int height); // void draw(float deltaTime, float xOffsetFake, float xOffsetLooping, float xOffsetSmooth, float yOffset); // void onSettingsChanged(); // void onDoubleTap(); // void onTripleTap(); // void setIsPreview(boolean isPreview); // } // // Path: core-src/com/cyphercove/lwptools/core/MultiTapListener.java // public interface MultiTapListener { // void onDoubleTap(); // void onTripleTap(); // } // Path: android-src/com/cyphercove/lwptools/android/LiveWallpaperAndroidAdapter.java import android.content.Context; import android.content.SharedPreferences; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.backends.android.AndroidWallpaperListener; import com.badlogic.gdx.math.MathUtils; import com.cyphercove.lwptools.core.LiveWallpaperBaseRenderer; import com.cyphercove.lwptools.core.MultiTapListener; package com.cyphercove.lwptools.android; public class LiveWallpaperAndroidAdapter implements ApplicationListener, AndroidWallpaperListener, SharedPreferences.OnSharedPreferenceChangeListener{ LiveWallpaperBaseRenderer liveWallpaper;
MultiTapListener multiTapListener;
bverbeken/litmus
samples/test/unit/validation/PastValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/PastModel.java // public class PastModel { // // @InPast // public Date pastDate; // // @InPast("2012-12-31") // public Date dateBefore31Dec2012; // // // } // // Path: app/litmus/util/DateUtil.java // public final class DateUtil { // // // public static Date asDate(String dateAsString){ // try { // return getDefaultFormatter().parse(dateAsString); // } catch (ParseException e) { // throw new RuntimeException("failed to parse date [" + dateAsString + "]", e); // } // } // // public static Date tomorrow() { // return addDays(new Date(), 1); // } // // public static Date yesterday() { // return addDays(new Date(), -1); // } // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.PastModel; import org.junit.Test; import static litmus.util.DateUtil.*;
package unit.validation; public class PastValidationTest extends ValidationTest<PastModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/PastModel.java // public class PastModel { // // @InPast // public Date pastDate; // // @InPast("2012-12-31") // public Date dateBefore31Dec2012; // // // } // // Path: app/litmus/util/DateUtil.java // public final class DateUtil { // // // public static Date asDate(String dateAsString){ // try { // return getDefaultFormatter().parse(dateAsString); // } catch (ParseException e) { // throw new RuntimeException("failed to parse date [" + dateAsString + "]", e); // } // } // // public static Date tomorrow() { // return addDays(new Date(), 1); // } // // public static Date yesterday() { // return addDays(new Date(), -1); // } // // // } // Path: samples/test/unit/validation/PastValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.PastModel; import org.junit.Test; import static litmus.util.DateUtil.*; package unit.validation; public class PastValidationTest extends ValidationTest<PastModel> { @Override
protected Builder<PastModel> valid() {
bverbeken/litmus
samples/test/unit/validation/URLValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/URLModel.java // public class URLModel { // // @URL // public String url; // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.URLModel; import org.junit.Test;
package unit.validation; public class URLValidationTest extends ValidationTest<URLModel> { @Override protected URLModelBuilder valid() { return new URLModelBuilder(); } @Test public void url() { assertThat("url").withValue(null).isValid(); assertThat("url").withValue("not a url!!").isInvalid(); assertThat("url").mustBeAURL(); }
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/URLModel.java // public class URLModel { // // @URL // public String url; // } // Path: samples/test/unit/validation/URLValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.URLModel; import org.junit.Test; package unit.validation; public class URLValidationTest extends ValidationTest<URLModel> { @Override protected URLModelBuilder valid() { return new URLModelBuilder(); } @Test public void url() { assertThat("url").withValue(null).isValid(); assertThat("url").withValue("not a url!!").isInvalid(); assertThat("url").mustBeAURL(); }
private class URLModelBuilder extends Builder<URLModel> {
bverbeken/litmus
samples/test/webdriver/pages/Pages.java
// Path: app/litmus/webdriver/Page.java // public static void open(String relativeUrl) { // WebDriverFactory.getWebDriver().get(getAppUrl() + relativeUrl); // }
import static litmus.webdriver.Page.open;
package webdriver.pages; public class Pages { public static HelloWorldPage goToHelloWorldPage() {
// Path: app/litmus/webdriver/Page.java // public static void open(String relativeUrl) { // WebDriverFactory.getWebDriver().get(getAppUrl() + relativeUrl); // } // Path: samples/test/webdriver/pages/Pages.java import static litmus.webdriver.Page.open; package webdriver.pages; public class Pages { public static HelloWorldPage goToHelloWorldPage() {
open("/html/helloworld");
bverbeken/litmus
samples/test/unit/validation/FutureValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/FutureModel.java // public class FutureModel { // // @InFuture // public Date futureDate; // // @InFuture("2100-01-01") // public Date dateAfter1Jan2100; // // // } // // Path: app/litmus/util/DateUtil.java // public final class DateUtil { // // // public static Date asDate(String dateAsString){ // try { // return getDefaultFormatter().parse(dateAsString); // } catch (ParseException e) { // throw new RuntimeException("failed to parse date [" + dateAsString + "]", e); // } // } // // public static Date tomorrow() { // return addDays(new Date(), 1); // } // // public static Date yesterday() { // return addDays(new Date(), -1); // } // // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.FutureModel; import org.junit.Test; import static litmus.util.DateUtil.*;
package unit.validation; public class FutureValidationTest extends ValidationTest<FutureModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/FutureModel.java // public class FutureModel { // // @InFuture // public Date futureDate; // // @InFuture("2100-01-01") // public Date dateAfter1Jan2100; // // // } // // Path: app/litmus/util/DateUtil.java // public final class DateUtil { // // // public static Date asDate(String dateAsString){ // try { // return getDefaultFormatter().parse(dateAsString); // } catch (ParseException e) { // throw new RuntimeException("failed to parse date [" + dateAsString + "]", e); // } // } // // public static Date tomorrow() { // return addDays(new Date(), 1); // } // // public static Date yesterday() { // return addDays(new Date(), -1); // } // // // } // Path: samples/test/unit/validation/FutureValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.FutureModel; import org.junit.Test; import static litmus.util.DateUtil.*; package unit.validation; public class FutureValidationTest extends ValidationTest<FutureModel> { @Override
protected Builder<FutureModel> valid() {
bverbeken/litmus
app/litmus/unit/validation/ValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // }
import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels;
/* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // } // Path: app/litmus/unit/validation/ValidationTest.java import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels; /* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */
protected ValidationAssert<T> assertThat(Builder<T> builder){
bverbeken/litmus
app/litmus/unit/validation/ValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // }
import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels;
/* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(Builder<T> builder){ return new ValidationAssert<T>(builder.build()); } /** * Test to verify that the valid() method actually returns a valid object. * * @see ValidationTest#valid() */ @Test public void validObjectShouldValidate() { T validObject = buildValid();
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // } // Path: app/litmus/unit/validation/ValidationTest.java import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels; /* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(Builder<T> builder){ return new ValidationAssert<T>(builder.build()); } /** * Test to verify that the valid() method actually returns a valid object. * * @see ValidationTest#valid() */ @Test public void validObjectShouldValidate() { T validObject = buildValid();
Assertions.assertThat(isValid(validObject))
bverbeken/litmus
app/litmus/unit/validation/ValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // }
import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels;
/* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(Builder<T> builder){ return new ValidationAssert<T>(builder.build()); } /** * Test to verify that the valid() method actually returns a valid object. * * @see ValidationTest#valid() */ @Test public void validObjectShouldValidate() { T validObject = buildValid(); Assertions.assertThat(isValid(validObject)) .as(invalidMessage(validObject)) .isTrue(); } private String invalidMessage(T valid) { return String.format( "Expected object of type %s to be valid, but it was invalid because: %s", valid.getClass().getCanonicalName(),
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/engine/CategoryInstance.java // public static final String UNIT = "Unit Tests"; // // Path: app/litmus/unit/validation/Validator.java // public static Map<String, List<Error>> getAllErrors() { // return Validation.current().errorsMap(); // } // // Path: app/litmus/unit/validation/Validator.java // public static boolean isValid(Object actual) { // return validate(actual).ok; // } // Path: app/litmus/unit/validation/ValidationTest.java import litmus.Builder; import litmus.Category; import org.fest.assertions.Assertions; import org.junit.Before; import org.junit.Test; import play.test.UnitTest; import static litmus.engine.CategoryInstance.UNIT; import static litmus.unit.validation.Validator.getAllErrors; import static litmus.unit.validation.Validator.isValid; import static play.test.Fixtures.deleteAllModels; /* * Copyright 2012 Ben Verbeken * * 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 litmus.unit.validation; /** * <p>Base class for testing validation annotations on {@link play.db.Model} classes. * </p> * * @author Ben Verbeken */ @Category(value = UNIT, priority = 10000) public abstract class ValidationTest<T> extends UnitTest { @Before public void cleanDb() { deleteAllModels(); } /** * @param fieldName the name of the field on the Model class you want to assert * @return a {@link FieldValidationAssert} instance */ protected FieldValidationAssert<T> assertThat(String fieldName) { return new FieldValidationAssert<T>(buildValid(), fieldName); } private T buildValid() { return valid().build(); } /** * @param t the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(T t) { return new ValidationAssert<T>(t); } /** * * @param builder the {@link Builder} that will be used to build the object to validate * @return a {@link ValidationAssert} instance */ protected ValidationAssert<T> assertThat(Builder<T> builder){ return new ValidationAssert<T>(builder.build()); } /** * Test to verify that the valid() method actually returns a valid object. * * @see ValidationTest#valid() */ @Test public void validObjectShouldValidate() { T validObject = buildValid(); Assertions.assertThat(isValid(validObject)) .as(invalidMessage(validObject)) .isTrue(); } private String invalidMessage(T valid) { return String.format( "Expected object of type %s to be valid, but it was invalid because: %s", valid.getClass().getCanonicalName(),
getAllErrors());
bverbeken/litmus
samples/test/unit/validation/RequiredValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/RequiredModel.java // public class RequiredModel { // // @Required // public String requiredString; // // @Required // public List<?> requiredCollection; // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.RequiredModel; import org.junit.Test; import static com.google.common.collect.Lists.newArrayList;
package unit.validation; public class RequiredValidationTest extends ValidationTest<RequiredModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/RequiredModel.java // public class RequiredModel { // // @Required // public String requiredString; // // @Required // public List<?> requiredCollection; // } // Path: samples/test/unit/validation/RequiredValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.RequiredModel; import org.junit.Test; import static com.google.common.collect.Lists.newArrayList; package unit.validation; public class RequiredValidationTest extends ValidationTest<RequiredModel> { @Override
protected Builder<RequiredModel> valid() {
bverbeken/litmus
app/litmus/engine/Tests.java
// Path: app/litmus/engine/CategoryInstance.java // public static final CategoryInstance NONE = new CategoryInstance("Uncategorized Tests", 999999, false);
import litmus.Category; import org.junit.Assert; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static java.lang.reflect.Modifier.isAbstract; import static java.util.Collections.sort; import static litmus.engine.CategoryInstance.NONE; import static play.Play.classloader;
package litmus.engine; public class Tests { private HashMap<CategoryInstance, List<TestClass>> map = new HashMap<CategoryInstance, List<TestClass>>(); public Tests() { for (Class testClass : getAllTests()) { if (!isAbstract(testClass.getModifiers())) { addTest(testClass); } } } private List<Class> getAllTests() { // TODO: don't just pick up Assert subclasses, but all non abstract classes that end with *Test // Check junit's naming rules return classloader.getAssignableClasses(Assert.class); } private void addTest(Class<?> testClass) { Category annotation = findCategoryAnnotation(testClass); if (annotation != null) { addToCategory(testClass, new CategoryInstance(annotation)); } else {
// Path: app/litmus/engine/CategoryInstance.java // public static final CategoryInstance NONE = new CategoryInstance("Uncategorized Tests", 999999, false); // Path: app/litmus/engine/Tests.java import litmus.Category; import org.junit.Assert; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static java.lang.reflect.Modifier.isAbstract; import static java.util.Collections.sort; import static litmus.engine.CategoryInstance.NONE; import static play.Play.classloader; package litmus.engine; public class Tests { private HashMap<CategoryInstance, List<TestClass>> map = new HashMap<CategoryInstance, List<TestClass>>(); public Tests() { for (Class testClass : getAllTests()) { if (!isAbstract(testClass.getModifiers())) { addTest(testClass); } } } private List<Class> getAllTests() { // TODO: don't just pick up Assert subclasses, but all non abstract classes that end with *Test // Check junit's naming rules return classloader.getAssignableClasses(Assert.class); } private void addTest(Class<?> testClass) { Category annotation = findCategoryAnnotation(testClass); if (annotation != null) { addToCategory(testClass, new CategoryInstance(annotation)); } else {
addToCategory(testClass, NONE);
bverbeken/litmus
samples/test/unit/validation/MinSizeValidationTest.java
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MinSizeModel.java // public class MinSizeModel { // // @MinSize(4) // public String minString; // // }
import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MinSizeModel; import org.junit.Test;
package unit.validation; public class MinSizeValidationTest extends ValidationTest<MinSizeModel> { @Override
// Path: app/litmus/Builder.java // public abstract class Builder<T> { // // public abstract T build(); // // } // // Path: app/litmus/unit/validation/ValidationTest.java // @Category(value = UNIT, priority = 10000) // public abstract class ValidationTest<T> extends UnitTest { // // @Before // public void cleanDb() { // deleteAllModels(); // } // // /** // * @param fieldName the name of the field on the Model class you want to assert // * @return a {@link FieldValidationAssert} instance // */ // protected FieldValidationAssert<T> assertThat(String fieldName) { // return new FieldValidationAssert<T>(buildValid(), fieldName); // } // // private T buildValid() { // return valid().build(); // } // // // /** // * @param t the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(T t) { // return new ValidationAssert<T>(t); // } // // /** // * // * @param builder the {@link Builder} that will be used to build the object to validate // * @return a {@link ValidationAssert} instance // */ // protected ValidationAssert<T> assertThat(Builder<T> builder){ // return new ValidationAssert<T>(builder.build()); // } // // /** // * Test to verify that the valid() method actually returns a valid object. // * // * @see ValidationTest#valid() // */ // @Test // public void validObjectShouldValidate() { // T validObject = buildValid(); // Assertions.assertThat(isValid(validObject)) // .as(invalidMessage(validObject)) // .isTrue(); // } // // private String invalidMessage(T valid) { // return String.format( // "Expected object of type %s to be valid, but it was invalid because: %s", // valid.getClass().getCanonicalName(), // getAllErrors()); // } // // /** // * Subclasses of ValidationTest should implement this method. It's used in // * The validObjectShouldValidate() test verifies that this method actually // * returns a valid object. // * // * @return a valid object of type T // * @see litmus.unit.validation.ValidationTest#validObjectShouldValidate() // */ // protected abstract Builder<T> valid(); // // } // // Path: samples/app/models/MinSizeModel.java // public class MinSizeModel { // // @MinSize(4) // public String minString; // // } // Path: samples/test/unit/validation/MinSizeValidationTest.java import litmus.Builder; import litmus.unit.validation.ValidationTest; import models.MinSizeModel; import org.junit.Test; package unit.validation; public class MinSizeValidationTest extends ValidationTest<MinSizeModel> { @Override
protected Builder<MinSizeModel> valid() {
bverbeken/litmus
app/litmus/functional/Request.java
// Path: app/litmus/util/ReflectionUtil.java // @SuppressWarnings("unchecked") // public static <T> T getStaticFieldValue(String fieldName, Class<?> clazz) { // try { // Field field = clazz.getDeclaredField(fieldName); // field.setAccessible(true); // return (T) field.get(clazz); // } catch (Exception e) { // throw new RuntimeException(e); // } // }
import static litmus.functional.HttpMethod.GET; import static litmus.functional.HttpMethod.POST; import static litmus.util.ReflectionUtil.getStaticFieldValue; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import play.mvc.Http; import play.mvc.results.Result; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.google.common.collect.Maps.newHashMap;
return play.test.FunctionalTest.GET(url + "?" + toQueryString(params)); } return play.test.FunctionalTest.GET(url); } }); } private String toQueryString(Map<String, String> params) { List<String> queryParts = Lists.newArrayList(Iterables.transform(params.entrySet(), new Function<Map.Entry<String, String>, String>() { public String apply(Map.Entry<String, String> input) { return input.getKey() + "=" + input.getValue(); } })); return StringUtils.join(queryParts, '&'); } public Response post() { return wrapResponse(POST, url, new ResponseFetcher() { Http.Response fetch() { return play.test.FunctionalTest.POST(url, params); } }); } public Response post(Map<String, String> parameters) { params.putAll(parameters); return post(); } private static Response wrapResponse(HttpMethod httpMethod, Object request, ResponseFetcher fetcher) {
// Path: app/litmus/util/ReflectionUtil.java // @SuppressWarnings("unchecked") // public static <T> T getStaticFieldValue(String fieldName, Class<?> clazz) { // try { // Field field = clazz.getDeclaredField(fieldName); // field.setAccessible(true); // return (T) field.get(clazz); // } catch (Exception e) { // throw new RuntimeException(e); // } // } // Path: app/litmus/functional/Request.java import static litmus.functional.HttpMethod.GET; import static litmus.functional.HttpMethod.POST; import static litmus.util.ReflectionUtil.getStaticFieldValue; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import play.mvc.Http; import play.mvc.results.Result; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; return play.test.FunctionalTest.GET(url + "?" + toQueryString(params)); } return play.test.FunctionalTest.GET(url); } }); } private String toQueryString(Map<String, String> params) { List<String> queryParts = Lists.newArrayList(Iterables.transform(params.entrySet(), new Function<Map.Entry<String, String>, String>() { public String apply(Map.Entry<String, String> input) { return input.getKey() + "=" + input.getValue(); } })); return StringUtils.join(queryParts, '&'); } public Response post() { return wrapResponse(POST, url, new ResponseFetcher() { Http.Response fetch() { return play.test.FunctionalTest.POST(url, params); } }); } public Response post(Map<String, String> parameters) { params.putAll(parameters); return post(); } private static Response wrapResponse(HttpMethod httpMethod, Object request, ResponseFetcher fetcher) {
Map<String, Object> renderArgs = getStaticFieldValue("renderArgs", play.test.FunctionalTest.class);
bverbeken/litmus
samples/test/webdriver/SampleWebDriverTest.java
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // }
import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage;
package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() {
// Path: app/litmus/webdriver/WebDriverTest.java // @Category(value = WEBDRIVER, priority = 20000, slow = true) // public abstract class WebDriverTest extends FestAssertFunctionalTest { // // @BeforeClass // public static void checkPlayConfig() { // String playPool = Play.configuration.getProperty("play.pool"); // if (playPool == null) { // throw new IllegalStateException("'play.pool' property not found. Please set the 'play.pool' property in your application.conf to at least 2"); // } else if (parseInt(playPool) < 2) { // throw new IllegalStateException("Cannot run WebDriver tests when 'play.pool' config value is < 2. Please set the 'play.pool' property in your application.conf to at least 2"); // } // } // // @AfterClass // public static void quitWebDriver() { // WebDriverFactory.quitAndInit(); // } // // protected WebElementAssert assertThat(WebElement element) { // return WebDriverAssertions.assertThat(element); // } // // protected PageAssert assertThat(Page page) { // return WebDriverAssertions.assertThat(page); // } // // } // // Path: samples/test/webdriver/pages/HelloWorldPage.java // public class HelloWorldPage extends Page<HelloWorldPage> { // // @FindBy(id="name") // public WebElement nameInput; // // @FindBy(id="submit") // public WebElement submit; // // @FindBy(className = "error") // public WebElement error; // // // @Override // protected boolean arrivedAt() { // return getTitle().equals("HelloWorld"); // } // // public HelloWorldPage enterName(String name) { // nameInput.sendKeys(name); // return this; // } // // public SayHelloPage clickSubmit() { // submit.click(); // return new SayHelloPage(); // } // // public HelloWorldPage clickSubmitAndExpectValidationErrors() { // submit.click(); // return new HelloWorldPage().assertArrivedAt(); // } // // } // // Path: samples/test/webdriver/pages/SayHelloPage.java // public class SayHelloPage extends Page<SayHelloPage> { // // @FindBy(id = "msg") // public WebElement message; // // @Override // protected boolean arrivedAt() { // return getTitle().equals("SayHello"); // } // // } // // Path: samples/test/webdriver/pages/Pages.java // public static HelloWorldPage goToHelloWorldPage() { // open("/html/helloworld"); // return new HelloWorldPage(); // } // // Path: samples/test/webdriver/pages/Pages.java // public static SayHelloPage goToSayHelloPage(String name){ // open("/html/sayHello?name=" + name); // return new SayHelloPage(); // } // Path: samples/test/webdriver/SampleWebDriverTest.java import litmus.webdriver.WebDriverTest; import org.junit.Test; import webdriver.pages.HelloWorldPage; import webdriver.pages.SayHelloPage; import static webdriver.pages.Pages.goToHelloWorldPage; import static webdriver.pages.Pages.goToSayHelloPage; package webdriver; public class SampleWebDriverTest extends WebDriverTest { @Test public void iShouldBeAbleToSubmitAndSeeTheMessage() {
SayHelloPage page = goToHelloWorldPage()